// Sections for "VI. Bestiário" page — grimório / sketchbook spreads.
// Data lives in bestiario-data.jsx (exposed as window.BESTIARY).
const BESTIARY = window.BESTIARY;


// ---------- Page Hero ----------
function BestiaryHero({ intensity }) {
  return (
    <section className="chapter-hero bestiary-hero">
      <div className="chapter-hero-bg" />
      <window.EmberCanvas intensity={intensity} />

      <div className="chapter-hero-inner reveal">
        <div className="chapter-eyebrow">
          <span className="line" />
          <span className="eyebrow">Capítulo VI · As Criaturas</span>
          <span className="line" />
        </div>

        <h1 className="chapter-title">
          O <span className="em">Bestiário</span><br />
          O Legado do Fogo
        </h1>

        <p className="chapter-lede">
          Registro ilustrado das criaturas conhecidas que habitam — e ameaçam — o Grande Continente. Cada espécime foi observado em campo, capturado em esboço e descrito em <em>linguagens antigas</em> antes de ser arquivado neste volume.
        </p>

        <p className="chapter-sub">
          Folheie o grimório com cautela. Algumas destas páginas foram lacradas por décadas — e por bons motivos. O que se segue não é um inventário: é um aviso.
        </p>

        <div className="chapter-breadcrumbs">
          <a href="index.html">Início</a>
          <span className="sep">/</span>
          <a href="index.html#mundo">O Mundo</a>
          <span className="sep">/</span>
          <span className="current">Bestiário</span>
        </div>
      </div>

      <div className="scroll-hint">
        <span>Abra o grimório</span>
        <span className="line" />
      </div>
    </section>
  );
}

// ---------- Index of creatures ----------
function BestiaryIndex() {
  return (
    <section className="bestiary-index">
      <div className="atlas-rule" />
      <div className="bestiary-index-head">
        <span className="eyebrow">Index Bestiarum</span>
        <span className="index-count">{BESTIARY.length} espécimes catalogados</span>
      </div>
      <div className="bestiary-index-grid">
        {BESTIARY.map((b, i) => (
          <a key={b.id} href={"#bestiary-book"} className="bestiary-index-card reveal" style={{ transitionDelay: (i * 50) + "ms" }}
            onClick={(e) => {
              e.preventDefault();
              window.dispatchEvent(new CustomEvent("bestiary:goto", { detail: { target: i } }));
              const el = document.getElementById("bestiary-book");
              if (el) {
                const y = window.scrollY + el.getBoundingClientRect().top - 80;
                window.scrollTo({ top: y, behavior: "smooth" });
              }
            }}
          >
            <span className="idx-num">{b.numeral}</span>
            <span className="idx-name">{b.name}</span>
            <span className="idx-epithet">{b.epithet}</span>
          </a>
        ))}
      </div>
      <div className="atlas-rule" />
    </section>
  );
}

// ---------- Slot primitive ----------
function ArtSlot({ shape = "tall", label, dropLabel = "ilustração", image, alt, fit = "cover" }) {
  if (image) {
    return (
      <div className={"art-slot art-slot-" + shape + " has-image"}>
        <img src={image} alt={alt || ""} className="art-slot-img" loading="lazy" style={{ objectFit: fit }} />
        <div className="art-slot-frame" />
        {label && <span className="art-slot-label">{label}</span>}
      </div>
    );
  }
  return (
    <div className={"art-slot art-slot-" + shape}>
      <div className="art-slot-pattern" />
      <div className="art-slot-frame" />
      <div className="art-slot-inner">
        <span className="art-slot-mark">⌬</span>
        <span className="art-slot-drop">[ {dropLabel} ]</span>
      </div>
      {label && <span className="art-slot-label">{label}</span>}
    </div>
  );
}

// ---------- Page halves (extracted so we can flip them independently) ----------
function CreatureLeftPage({ entry }) {
  const { figures, scene, sceneCaption } = entry;
  const figureCount = figures ? figures.length : 0;
  return (
    <section className="page page-left">
      <div className="page-aging" aria-hidden="true" />
      <div className="page-corners" aria-hidden="true">
        <span className="corner tl" /><span className="corner tr" />
        <span className="corner bl" /><span className="corner br" />
      </div>

      <header className="creature-head">
        <h2 className="creature-name">{entry.name}</h2>
        <div className="creature-meta">
          <div className="meta-row">
            <span className="meta-runes runes-elvish">{entry.elvish}</span>
            <span className="meta-lat">{entry.elvishLat}</span>
          </div>
          <div className="meta-row">
            <span className="meta-runes runes-dwarvish">{entry.dwarvish}</span>
            <span className="meta-lat">{entry.dwarvishLat}</span>
          </div>
        </div>
      </header>

      <p className="creature-class">{entry.classification}</p>

      <div className="creature-intro">
        {entry.intro.map((line, i) => <span key={i}>{line}</span>)}
      </div>

      {scene ? (
        <figure className="creature-scene">
          <div className="creature-scene-frame">
            <img src={scene} alt={entry.name + " — cenário"} loading="lazy" />
            <div className="creature-scene-overlay" aria-hidden="true" />
          </div>
          {sceneCaption && <figcaption className="creature-scene-caption">{sceneCaption}</figcaption>}
        </figure>
      ) : (
        <div className={"creature-figures fig-count-" + figureCount}>
          {figures && figures.map((f, i) => (
            <div key={i} className="figure-block">
              <ArtSlot shape={f.aspect === "wide" ? "wide" : "tall"} dropLabel={`espécime · ${f.label.toLowerCase()}`} />
              <span className="figure-caption">{f.label}</span>
            </div>
          ))}
        </div>
      )}
    </section>
  );
}

function CreatureRightPage({ entry }) {
  const { anatomy } = entry;
  return (
    <section className="page page-right">
      <div className="page-aging" aria-hidden="true" />
      <div className="page-corners" aria-hidden="true">
        <span className="corner tl" /><span className="corner tr" />
        <span className="corner bl" /><span className="corner br" />
      </div>

      <div className="anatomy-layout">
        <div className="anatomy-main">
          <span className="hand-note top-note">{anatomy.mainLabel}</span>
          <ArtSlot shape="square" dropLabel="esboço · crânio" image={anatomy.mainImage} alt={anatomy.mainLabel} fit={anatomy.mainFit || "cover"} />
        </div>

        <div className="anatomy-detail">
          <ArtSlot shape="mini" dropLabel="olho" image={anatomy.detail.image} alt={anatomy.detail.label} fit={anatomy.detail.fit || "cover"} />
          <span className="hand-note">{anatomy.detail.caption}</span>
        </div>

        <div className="anatomy-sample">
          <ArtSlot shape="bottle" dropLabel="frasco" image={anatomy.sample.image} alt={anatomy.sample.label} fit={anatomy.sample.fit || "cover"} />
          <span className="hand-note">{anatomy.sample.caption}</span>
        </div>

        <div className="anatomy-main-note">
          <span className="hand-note">{anatomy.mainCaption}</span>
        </div>

        <div className="anatomy-sub">
          <ArtSlot shape="tag" dropLabel="amostra" image={anatomy.sub.image} alt={anatomy.sub.label} fit={anatomy.sub.fit || "cover"} />
          <span className="hand-note small">{anatomy.sub.label}</span>
          <span className="hand-note small dim">{anatomy.sub.caption}</span>
        </div>

        <div className="anatomy-variants">
          <span className="hand-note variants-intro">{anatomy.variantsNote}</span>
          <div className="variants-row">
            {anatomy.variants.map((v) => (
              <div key={v.name} className="variant">
                <ArtSlot shape="thumb" dropLabel="esboço" image={v.image} alt={v.name} />
                <span className="hand-note tiny">{v.name}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- Book container: stacked spreads, small side arrows ----------
function BestiarySpread({ entry, index, total }) {
  return (
    <article className="bestiary-spread" id={"spread-" + entry.id}>
      <div className="spread-folio">
        <span>{entry.numeral}</span>
        <span className="of">— FOLIO {String(index + 1).padStart(2, "0")} / {String(total).padStart(2, "0")} —</span>
        <span>{entry.name}</span>
      </div>

      <div className="spread-pages">
        <div className="spread-binding" aria-hidden="true" />
        <CreatureLeftPage entry={entry} />
        <CreatureRightPage entry={entry} />
        <div className="spread-construction" aria-hidden="true">
          <span className="spread-construction-text">Em Construção</span>
        </div>
      </div>
    </article>
  );
}

function BestiaryBook() {
  const total = BESTIARY.length;
  const [index, setIndex] = React.useState(0);
  const [animating, setAnimating] = React.useState(false);
  const animTimer = React.useRef(null);

  const go = React.useCallback((target) => {
    const clamped = Math.max(0, Math.min(total - 1, target));
    if (clamped === index || animating) return;
    setIndex(clamped);
    setAnimating(true);
    if (animTimer.current) clearTimeout(animTimer.current);
    animTimer.current = setTimeout(() => setAnimating(false), 620);
  }, [index, total, animating]);

  React.useEffect(() => () => {
    if (animTimer.current) clearTimeout(animTimer.current);
  }, []);

  // keyboard nav when the book is on screen
  React.useEffect(() => {
    const onKey = (e) => {
      if (e.target && (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA")) return;
      const book = document.getElementById("bestiary-book");
      if (!book) return;
      const r = book.getBoundingClientRect();
      const visible = r.bottom > 100 && r.top < window.innerHeight - 100;
      if (!visible) return;
      if (e.key === "ArrowRight") { e.preventDefault(); go(index + 1); }
      else if (e.key === "ArrowLeft") { e.preventDefault(); go(index - 1); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [go, index]);

  // jump from index cards
  React.useEffect(() => {
    const onJump = (e) => {
      const target = e.detail?.target;
      if (typeof target === "number") {
        go(target);
        const el = document.getElementById("bestiary-book");
        if (el) {
          const y = window.scrollY + el.getBoundingClientRect().top - 70;
          window.scrollTo({ top: y, behavior: "smooth" });
        }
      }
    };
    window.addEventListener("bestiary:goto", onJump);
    return () => window.removeEventListener("bestiary:goto", onJump);
  }, [go]);

  return (
    <section className="bestiary-book" id="bestiary-book">
      <div className="book-margin-tag">Liber Bestiarum · MMXXIV</div>

      <div className="book-viewport">
        <div
          className="book-track"
          style={{ transform: `translateX(${-index * 100}%)` }}
        >
          {BESTIARY.map((entry, i) => (
            <div className="book-slide" key={entry.id}>
              <BestiarySpread entry={entry} index={i} total={total} />
            </div>
          ))}
        </div>
      </div>

      {/* Floating side arrows — small, do not overlap pages */}
      <div className="folio-rail folio-rail-left" aria-hidden="true">
        <button
          type="button"
          className="folio-arrow"
          onClick={() => go(index - 1)}
          disabled={index <= 0 || animating}
          aria-label="Folio anterior"
        >
          <span className="folio-arrow-glyph">‹</span>
        </button>
      </div>
      <div className="folio-rail folio-rail-right" aria-hidden="true">
        <button
          type="button"
          className="folio-arrow"
          onClick={() => go(index + 1)}
          disabled={index >= total - 1 || animating}
          aria-label="Próximo folio"
        >
          <span className="folio-arrow-glyph">›</span>
        </button>
      </div>
    </section>
  );
}

// ---------- Outro ----------
function BestiaryOutro() {
  return (
    <section className="chapter-outro bestiary-outro">
      <div className="outro-rule" />
      <p className="outro-quote reveal">
        “Conhecer a criatura é metade da espada. A outra metade — apenas a coragem forja.”
      </p>
      <div className="outro-attr reveal">
        <span className="line" />
        <span>Liber Bestiarum · Epílogo</span>
        <span className="line" />
      </div>

      <div className="outro-actions reveal">
        <a href="O_Grande_Continente.html" className="btn btn-ghost">
          <span className="arrow">←</span> Voltar ao Continente
        </a>
        <a href="Chamado.html" className="btn btn-primary">
          Atender o chamado <span className="arrow">→</span>
        </a>
      </div>
    </section>
  );
}

Object.assign(window, { BestiaryHero, BestiaryIndex, BestiaryBook, BestiaryOutro });
