// ───────────────────────── Flipbook · páginas con contenido real ─────────────────────────
// Each page is rendered once at a fixed 360×480 "sheet" and scaled, so the
// thumbnail and the large preview are pixel-for-pixel the same page (WYSIWYG).

const PAGE_DATA = {
  u1: { color: '#3a4fa0', sections: [
    { h: 'El universo y las galaxias', p: [
      'El universo es todo lo que existe: materia, energía, espacio y tiempo. Se formó hace unos 13 800 millones de años en un acontecimiento llamado el Big Bang.',
      'Las galaxias son enormes agrupaciones de estrellas, gas y polvo unidas por la gravedad. El Sol forma parte de la Vía Láctea.' ] },
    { h: 'El sistema solar', p: [
      'El sistema solar está formado por el Sol y los cuerpos que giran a su alrededor: ocho planetas, sus satélites, asteroides y cometas.',
      'Los planetas describen órbitas elípticas. Los interiores son rocosos y los exteriores, gaseosos.' ] },
  ] },
  u2: { color: '#a06a32', sections: [
    { h: 'Estructura de la geosfera', p: [
      'La geosfera es la parte sólida de la Tierra. Se divide en corteza, manto y núcleo, capas con distinta composición y temperatura.',
      'La corteza es la capa más externa y delgada, sobre la que se asientan los continentes y los océanos.' ] },
    { h: 'Minerales y rocas', p: [
      'Un mineral es una sustancia sólida, natural e inorgánica con una composición química definida, como el cuarzo o el feldespato.',
      'Las rocas son agregados de minerales. Según su origen son magmáticas, sedimentarias o metamórficas.' ] },
  ] },
  u3: { color: '#2f7fb0', sections: [
    { h: 'La atmósfera', p: [
      'La atmósfera es la capa de gases que rodea la Tierra. Está compuesta sobre todo por nitrógeno (78 %) y oxígeno (21 %).',
      'Nos protege de la radiación solar, hace posible la vida y regula la temperatura del planeta.' ] },
    { h: 'La hidrosfera y el ciclo del agua', p: [
      'La hidrosfera es el conjunto del agua del planeta: océanos, ríos, lagos, glaciares y aguas subterráneas.',
      'El agua circula entre la superficie y la atmósfera mediante la evaporación, la condensación y las precipitaciones.' ] },
  ] },
  u4: { color: '#0a8aa0', sections: [
    { h: '¿Qué es la célula?', p: [
      'La célula es la unidad más pequeña capaz de realizar las funciones vitales: nutrición, relación y reproducción.',
      'Según la teoría celular, todos los seres vivos están formados por células y toda célula procede de otra anterior.' ] },
    { h: 'Células procariotas y eucariotas', p: [
      'Las células procariotas no tienen el núcleo definido; su material genético está disperso en el citoplasma, como en las bacterias.',
      'Las células eucariotas poseen un núcleo rodeado de membrana y orgánulos como las mitocondrias o el aparato de Golgi.' ] },
  ] },
  u5: { color: '#3f8f3b', sections: [
    { h: 'Características de los seres vivos', p: [
      'Todos los seres vivos están formados por células, intercambian materia y energía con el medio y son capaces de reproducirse.',
      'Realizan tres funciones vitales: nutrición, relación y reproducción.' ] },
    { h: 'La clasificación: los cinco reinos', p: [
      'La biodiversidad es la variedad de seres vivos que habitan la Tierra. Para estudiarlos se clasifican en grupos.',
      'Se distinguen cinco reinos: moneras, protoctistas, hongos, plantas y animales.' ] },
  ] },
  u6: { color: '#c8823a', sections: [
    { h: 'Animales vertebrados', p: [
      'Los animales vertebrados tienen un esqueleto interno con columna vertebral. Se agrupan en peces, anfibios, reptiles, aves y mamíferos.',
      'Presentan simetría bilateral y un sistema nervioso desarrollado.' ] },
    { h: 'Animales invertebrados', p: [
      'Los invertebrados carecen de columna vertebral y son la mayoría de las especies animales conocidas.',
      'Incluyen grupos como los artrópodos, los moluscos, los gusanos o las medusas.' ] },
  ] },
};

function pageContentFor(unit, page) {
  const data = PAGE_DATA[unit.id] || PAGE_DATA.u1;
  const sec = data.sections[page % data.sections.length];
  const figure = page % 2 === 0;
  return { ...sec, figure, color: data.color, figN: `${unit.n}.${(page % 4) + 1}` };
}

const SHEET_W = 360, SHEET_H = 480;

function PageSheet({ unit, page }) {
  const c = pageContentFor(unit, page);
  return (
    <div style={{ width: SHEET_W, height: SHEET_H }} className="bg-white relative flex flex-col font-sans">
      <div className="flex items-center justify-between px-7 pt-6 pb-2.5 shrink-0" style={{ borderBottom: `2px solid ${c.color}` }}>
        <span style={{ color: c.color }} className="text-[12px] font-extrabold uppercase tracking-wide">Unidad {unit.n}</span>
        <span className="text-[11px] text-[#9a9aa3] truncate ml-3">{unit.title}</span>
      </div>
      <div className="px-7 pt-5 pb-2 flex-1 flex flex-col gap-3 overflow-hidden">
        <h3 className="text-[20px] font-extrabold text-[#2b2b2b] leading-tight">{c.h}</h3>
        {c.figure && (
          <figure className="rounded-lg overflow-hidden shrink-0" style={{ height: 138 }}>
            <div className="w-full h-[112px]" style={{ background: `url(${unit.img}) center/cover` }} />
            <figcaption className="text-[10px] text-[#9a9aa3] pt-1 italic">Fig. {c.figN} · {c.h}</figcaption>
          </figure>
        )}
        {c.p.map((t, i) => (
          <p key={i} className="text-[12.5px] leading-[1.55] text-[#555]" style={{ textAlign: 'justify' }}>{t}</p>
        ))}
      </div>
      <div className="px-7 pb-5 pt-1 flex items-center justify-between shrink-0">
        <span className="text-[10px] text-[#c2c2cc]">Biología y Geología · 1.º ESO</span>
        <span className="text-[12px] font-semibold" style={{ color: c.color }}>{page}</span>
      </div>
    </div>
  );
}

function ScaledSheet({ unit, page, scale }) {
  return (
    <div style={{ width: SHEET_W * scale, height: SHEET_H * scale }} className="shrink-0">
      <div style={{ width: SHEET_W, height: SHEET_H, transform: `scale(${scale})`, transformOrigin: 'top left' }}>
        <PageSheet unit={unit} page={page} />
      </div>
    </div>
  );
}

const THUMB_W = 64;

// Schematic thumbnail — NOT a page imitation. The hero is the page number;
// a clear "Ver" button opens the full-screen viewer.
function PageThumb({ unit, page, selected, onToggle, onPreview }) {
  return (
    <div className="relative group shrink-0" style={{ width: THUMB_W }}>
      <div role="button" tabIndex={0} onClick={onToggle}
        className={cx('relative rounded-lg border-2 cursor-pointer transition-all flex items-center justify-center aspect-square overflow-hidden',
          selected ? 'border-primary bg-primary-50/50 shadow-card' : 'border-line bg-white hover:border-primary-300 hover:bg-canvas/40')}>
        {/* selection checkbox */}
        <span className={cx('absolute top-1 right-1 w-4 h-4 rounded-[4px] border-2 flex items-center justify-center transition-all z-10',
          selected ? 'bg-primary border-primary' : 'bg-white border-[#cdcdd6] group-hover:border-primary-300')}>
          {selected && <Icon name="check" size={10} strokeWidth={3.4} className="text-white" />}
        </span>
        {/* page number */}
        <span className="text-[15px] font-bold text-ink tabular-nums leading-none">{page}</span>
        {/* Ver button — solo al pasar el ratón */}
        <button onClick={(e) => { e.stopPropagation(); onPreview(); }}
          className="absolute inset-x-0 bottom-0 h-5 flex items-center justify-center gap-0.5 bg-slate2/85 text-white text-[10px] font-semibold opacity-0 group-hover:opacity-100 transition-opacity">
          <Icon name="eye" size={11} /> Ver
        </button>
      </div>
    </div>
  );
}

function PagePreviewModal({ unit, page, selected, onToggle, onClose, onPrev, onNext, hasPrev, hasNext }) {
  const areaRef = React.useRef(null);
  const [scale, setScale] = React.useState(1.4);

  React.useLayoutEffect(() => {
    const compute = () => {
      const el = areaRef.current;
      if (!el) return;
      const availW = el.clientWidth - 140; // deja sitio a las flechas
      const availH = el.clientHeight - 36;
      setScale(Math.max(0.6, Math.min(availW / SHEET_W, availH / SHEET_H)));
    };
    compute();
    window.addEventListener('resize', compute);
    return () => window.removeEventListener('resize', compute);
  }, [page]);

  React.useEffect(() => {
    const h = (e) => {
      if (e.key === 'Escape') onClose();
      else if (e.key === 'ArrowLeft' && hasPrev) onPrev();
      else if (e.key === 'ArrowRight' && hasNext) onNext();
    };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [hasPrev, hasNext, onClose, onPrev, onNext]);

  return ReactDOM.createPortal((
    <div className="fixed inset-0 z-[60] bg-[#1b1e2b] flex flex-col anim-fade-in">
      {/* Barra superior */}
      <header className="flex items-center justify-between gap-4 px-5 h-14 bg-white/[0.04] border-b border-white/10 shrink-0">
        <div className="min-w-0 text-white">
          <p className="text-[14px] font-bold truncate">Unidad {unit.n} · {unit.title}</p>
          <p className="text-[12.5px] text-white/60">Página {page}</p>
        </div>
        <button onClick={onClose} title="Cerrar (Esc)"
          className="w-10 h-10 rounded-lg flex items-center justify-center text-white/70 hover:text-white hover:bg-white/10 transition-colors">
          <Icon name="x" size={22} />
        </button>
      </header>

      {/* Visor */}
      <div ref={areaRef} className="relative flex-1 flex items-center justify-center overflow-auto p-6">
        <button onClick={onPrev} disabled={!hasPrev} title="Anterior (←)"
          className="absolute left-5 z-10 w-12 h-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center disabled:opacity-25 disabled:pointer-events-none transition-colors">
          <Icon name="chevron-left" size={26} />
        </button>
        <div className="rounded-xl overflow-hidden shadow-pop ring-1 ring-black/30">
          <ScaledSheet unit={unit} page={page} scale={scale} />
        </div>
        <button onClick={onNext} disabled={!hasNext} title="Siguiente (→)"
          className="absolute right-5 z-10 w-12 h-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center disabled:opacity-25 disabled:pointer-events-none transition-colors">
          <Icon name="chevron-right" size={26} />
        </button>
      </div>

      {/* Barra inferior */}
      <footer className="flex items-center justify-between gap-3 px-5 h-16 bg-white border-t border-line shrink-0">
        <span className="text-[12.5px] text-muted hidden sm:block">Usa ← → para navegar · Esc para cerrar</span>
        <div className="flex items-center gap-2 ml-auto">
          <Button variant="ghost" onClick={onClose}>Cerrar</Button>
          <Button variant={selected ? 'softprim' : 'primary'} icon={selected ? 'check' : 'plus'} onClick={onToggle}>
            {selected ? 'Página incluida' : 'Incluir esta página'}
          </Button>
        </div>
      </footer>
    </div>
  ), document.body);
}

Object.assign(window, { PAGE_DATA, pageContentFor, PageSheet, ScaledSheet, PageThumb, PagePreviewModal });
