// ───────────────────────── Step 1 · Selección de contenido ─────────────────────────
const unitPages = (unit) => {
  const start = 8 + (unit.n - 1) * 20;
  return Array.from({ length: unit.pages }, (_, i) => start + i);
};

// tri-state box (none / some / all) used on each unit row
function TriBox({ state, onClick, className = '' }) {
  return (
    <span role="checkbox" aria-checked={state === 'all'} tabIndex={0}
      onClick={(e) => { e.stopPropagation(); onClick(); }}
      className={cx('w-5 h-5 rounded-[6px] border-2 flex items-center justify-center transition-all shrink-0 cursor-pointer',
        state === 'all' ? 'bg-primary border-primary' : state === 'some' ? 'bg-primary-100 border-primary' : 'bg-white border-[#cdcdd6] hover:border-primary-300', className)}>
      {state === 'all' ? <Icon name="check" size={13} strokeWidth={3} className="text-white" /> : null}
    </span>
  );
}

function UnitRow({ unit, expanded, onExpand, type, pageSel, togglePage, toggleAllPages, blockSel, toggleBlock, toggleAllBlocks, setUnitAll, onPreview }) {
  const pages = unitPages(unit);
  const selPages = pageSel[unit.id] || [];
  const selBlocks = blockSel[unit.id] || [];

  const allItems = type === 'flipbook' ? pages.length : unit.blocks.length;
  const selItems = type === 'flipbook' ? selPages.length : selBlocks.length;
  const count = selItems;
  const triState = selItems === 0 ? 'none' : selItems >= allItems ? 'all' : 'some';
  const allBlocksSel = selBlocks.length === unit.blocks.length;

  return (
    <Card className="overflow-hidden">
      <div className={cx('w-full flex items-center gap-3 pl-4 pr-4 py-3 transition-colors', expanded ? 'bg-canvas/40' : 'hover:bg-canvas/60')}>
        <TriBox state={triState} onClick={() => setUnitAll(unit, triState !== 'all')} />
        <button onClick={onExpand} className="flex items-center gap-3.5 flex-1 min-w-0 text-left">
          <div className={cx('relative w-[72px] h-12 rounded-lg overflow-hidden shrink-0 ring-1 transition-shadow', count ? 'ring-primary shadow-[0_0_0_1px_#00BCD4]' : 'ring-black/10')}
            style={{ background: `url(${unit.img}) center/cover` }}>
            {count > 0 && <span className="absolute inset-0 bg-primary/15" />}
          </div>
          <div className="flex-1 min-w-0">
            <span className="block text-[11.5px] font-semibold text-muted tracking-wide">Unidad {unit.n}</span>
            <h4 className="text-[15px] font-semibold text-ink truncate leading-tight mt-0.5">{unit.title}</h4>
          </div>
          {count > 0 && <Badge tone="primary">{count} {type === 'flipbook' ? 'págs.' : 'bloques'}</Badge>}
          <Icon name="chevron-down" size={20} className={cx('text-faint transition-transform shrink-0', expanded && 'rotate-180')} />
        </button>
      </div>

      {expanded && (
        <div className="px-4 pb-5 pt-1 border-t border-line anim-fade-in">
          {type === 'flipbook' ? (
            <>
              <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 py-3">
                <span className="text-[13px] text-muted flex-1 min-w-[200px]">Pasa el ratón por una página y pulsa <span className="font-semibold text-ink">Ver</span> para leer su contenido</span>
                <SelectAllPair allOn={selPages.length === pages.length} hasSelection={selPages.length > 0}
                  onSelectAll={() => setUnitAll(unit, true)} onClear={() => setUnitAll(unit, false)} />
              </div>
              <div className="flex flex-wrap gap-2.5">
                {pages.map(p => (
                  <PageThumb key={p} unit={unit} page={p} selected={selPages.includes(p)}
                    onToggle={() => togglePage(unit.id, p)} onPreview={() => onPreview(unit.id, p)} />
                ))}
              </div>
            </>
          ) : (
            <>
              <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 py-3">
                <span className="text-[13px] text-muted flex-1 min-w-[200px]">Selecciona los bloques de contenido</span>
                <SelectAllPair allOn={allBlocksSel} hasSelection={selBlocks.length > 0}
                  onSelectAll={() => setUnitAll(unit, true)} onClear={() => setUnitAll(unit, false)} />
              </div>
              <div className="space-y-2">
                {unit.blocks.map((b, i) => {
                  const sel = selBlocks.includes(i);
                  return (
                    <button key={i} onClick={() => toggleBlock(unit.id, i)}
                      className={cx('w-full flex items-center gap-3.5 px-4 py-3 rounded-xl border transition-all text-left',
                        sel ? 'border-primary bg-primary-50/50' : 'border-line bg-white hover:border-primary-200')}>
                      <Checkbox checked={sel} onChange={() => toggleBlock(unit.id, i)} />
                      <span className="text-sm font-medium text-ink flex-1">{b}</span>
                    </button>
                  );
                })}
              </div>
            </>
          )}
        </div>
      )}
    </Card>
  );
}

function ContentStep({ type, setType, pageSel, setPageSel, blockSel, setBlockSel }) {
  const [expanded, setExpanded] = React.useState('u4');
  const [preview, setPreview] = React.useState(null); // { unitId, page }

  const togglePage = (uid, p) => setPageSel(prev => {
    const cur = prev[uid] || [];
    return { ...prev, [uid]: cur.includes(p) ? cur.filter(x => x !== p) : [...cur, p] };
  });
  const toggleAllPages = (unit, pages) => setPageSel(prev => {
    const cur = prev[unit.id] || [];
    return { ...prev, [unit.id]: cur.length === pages.length ? [] : pages };
  });
  const toggleBlock = (uid, i) => setBlockSel(prev => {
    const cur = prev[uid] || [];
    return { ...prev, [uid]: cur.includes(i) ? cur.filter(x => x !== i) : [...cur, i] };
  });
  const toggleAllBlocks = (unit) => setBlockSel(prev => {
    const cur = prev[unit.id] || [];
    const all = unit.blocks.map((_, i) => i);
    return { ...prev, [unit.id]: cur.length === all.length ? [] : all };
  });

  // select / clear a whole unit
  const setUnitAll = (unit, on) => {
    if (type === 'flipbook') setPageSel(prev => ({ ...prev, [unit.id]: on ? unitPages(unit) : [] }));
    else setBlockSel(prev => ({ ...prev, [unit.id]: on ? unit.blocks.map((_, i) => i) : [] }));
  };
  // select / clear ALL units
  const setAllUnits = (on) => {
    if (type === 'flipbook') {
      const next = {}; UNITS.forEach(u => { next[u.id] = on ? unitPages(u) : []; }); setPageSel(next);
    } else {
      const next = {}; UNITS.forEach(u => { next[u.id] = on ? u.blocks.map((_, i) => i) : []; }); setBlockSel(next);
    }
  };

  const sel = type === 'flipbook' ? pageSel : blockSel;
  const totalSel = Object.values(sel).reduce((a, x) => a + x.length, 0);
  const totalAvail = type === 'flipbook' ? UNITS.reduce((a, u) => a + u.pages, 0) : UNITS.reduce((a, u) => a + u.blocks.length, 0);
  const unitsTouched = UNITS.filter(u => (sel[u.id] || []).length > 0).length;
  const allGlobal = totalSel > 0 && totalSel >= totalAvail ? 'all' : totalSel > 0 ? 'some' : 'none';
  const word = type === 'flipbook' ? 'páginas' : 'contenidos';

  // preview navigation within the current unit
  const pv = preview ? UNITS.find(u => u.id === preview.unitId) : null;
  const pvPages = pv ? unitPages(pv) : [];
  const pvIdx = pv ? pvPages.indexOf(preview.page) : -1;

  return (
    <div className="space-y-5">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-end gap-4">
        <Segmented value={type} onChange={setType}
          options={[{ value: 'flipbook', label: 'Flipbook', icon: 'book' }, { value: 'html5', label: 'HTML5', icon: 'puzzle' }]} />
      </div>

      {/* Quick select-all toolbar */}
      <Card className="p-3 pl-4 flex items-center justify-between gap-3 flex-wrap">
        <div className="flex items-center gap-3">
          <TriBox state={allGlobal} onClick={() => setAllUnits(allGlobal !== 'all')} />
          <span className="text-[13.5px] text-ink font-medium">
            {totalSel > 0
              ? <>{unitsTouched} {unitsTouched === 1 ? 'unidad' : 'unidades'} · {totalSel} {word}</>
              : <span className="text-muted">Selecciona unidades, páginas o bloques</span>}
          </span>
        </div>
        <SelectAllPair allOn={allGlobal === 'all'} hasSelection={totalSel > 0}
          onSelectAll={() => setAllUnits(true)} onClear={() => setAllUnits(false)} />
      </Card>

      <div className="flex items-start gap-3 px-4 py-3 rounded-xl bg-primary-50/60 border border-primary-100 text-[13px] text-primary-800">
        <Icon name="info" size={18} className="shrink-0 mt-px text-primary-600" />
        {type === 'flipbook'
          ? 'Despliega una unidad para ver las páginas. Puedes leer el contenido exacto de cada página antes de elegirla con el botón “Ver”.'
          : 'Marca unidades completas con su casilla, o despliega una unidad para elegir bloques de contenido concretos.'}
      </div>

      <div className="space-y-3">
        {UNITS.map(u => (
          <UnitRow key={u.id} unit={u} type={type}
            expanded={expanded === u.id} onExpand={() => setExpanded(e => e === u.id ? null : u.id)}
            pageSel={pageSel} togglePage={togglePage} toggleAllPages={toggleAllPages}
            blockSel={blockSel} toggleBlock={toggleBlock} toggleAllBlocks={toggleAllBlocks}
            setUnitAll={setUnitAll} onPreview={(uid, p) => setPreview({ unitId: uid, page: p })} />
        ))}
      </div>

      {preview && pv && (
        <PagePreviewModal unit={pv} page={preview.page}
          selected={(pageSel[pv.id] || []).includes(preview.page)}
          onToggle={() => togglePage(pv.id, preview.page)}
          onClose={() => setPreview(null)}
          hasPrev={pvIdx > 0} hasNext={pvIdx < pvPages.length - 1}
          onPrev={() => setPreview({ unitId: pv.id, page: pvPages[pvIdx - 1] })}
          onNext={() => setPreview({ unitId: pv.id, page: pvPages[pvIdx + 1] })} />
      )}
    </div>
  );
}

window.ContentStep = ContentStep;
