/* story.jsx — Level 0 narrative renderer.
   A clean long-scroll story page: cover + alternating portrait/era panels +
   "the key idea" callout + a bridge to the matching technical chapter.
   Etched-portrait SVGs are generated from initials (no external images). */

const { useEffect: _se, useState: _ss } = React;

/* Etched circuit-style portrait medallion from initials. */
function EtchedPortrait({ initials, seed = 0, size = 180 }) {
  // deterministic little trace pattern around a monogram
  const pins = 7;
  const r = size / 2;
  const cx = r, cy = r;
  const ticks = Array.from({ length: pins * 2 }, (_, i) => {
    const a = (i / (pins * 2)) * Math.PI * 2 + seed;
    const r1 = r - 10, r2 = r - 2;
    return { x1: cx + Math.cos(a) * r1, y1: cy + Math.sin(a) * r1,
             x2: cx + Math.cos(a) * r2, y2: cy + Math.sin(a) * r2 };
  });
  return (
    <svg viewBox={`0 0 ${size} ${size}`} width={size} height={size} className="etched-portrait">
      <defs>
        <radialGradient id={`ep${seed}`} cx="50%" cy="42%" r="60%">
          <stop offset="0%" stopColor="var(--bg-card)" />
          <stop offset="100%" stopColor="var(--bg-deeper)" />
        </radialGradient>
      </defs>
      <circle cx={cx} cy={cy} r={r - 3} fill={`url(#ep${seed})`} stroke="var(--current)" strokeWidth="2" />
      <circle cx={cx} cy={cy} r={r - 12} fill="none" stroke="var(--rule-strong)" strokeWidth="1" />
      {ticks.map((t, i) => (
        <line key={i} x1={t.x1} y1={t.y1} x2={t.x2} y2={t.y2}
              stroke="var(--current)" strokeWidth="1.5" opacity={i % 2 ? 0.4 : 0.85} />
      ))}
      {/* faux silhouette: shoulders + head */}
      <g opacity="0.18" fill="var(--ink)">
        <circle cx={cx} cy={cy - 14} r={r * 0.28} />
        <path d={`M ${cx - r * 0.42} ${cy + r * 0.5}
                  Q ${cx} ${cy + r * 0.02} ${cx + r * 0.42} ${cy + r * 0.5} Z`} />
      </g>
      <text x={cx} y={cy + 8} textAnchor="middle" fontFamily="'Newsreader', serif"
            fontStyle="italic" fontSize={size * 0.3} fill="var(--ink)">{initials}</text>
    </svg>
  );
}

/* A circular portrait medallion: drop a real photo of the scientist (persists),
   framed by an etched circuit ring. Falls back to an inviting empty state. */
function PortraitMedallion({ slotId, name, initials, size = 168 }) {
  const pins = 7, r = size / 2, cx = r, cy = r;
  const ticks = Array.from({ length: pins * 2 }, (_, i) => {
    const a = (i / (pins * 2)) * Math.PI * 2;
    const r1 = r - 7, r2 = r - 1;
    return { x1: cx + Math.cos(a) * r1, y1: cy + Math.sin(a) * r1,
             x2: cx + Math.cos(a) * r2, y2: cy + Math.sin(a) * r2 };
  });
  const inset = 13;
  const last = name.split(" ").slice(-1)[0];
  return (
    <div className="portrait-medallion" style={{ width: size, height: size }}>
      {React.createElement("image-slot", {
        id: slotId, shape: "circle", framebias: 10,
        placeholder: `Drop a portrait of ${last}`,
        style: { position: "absolute", left: inset, top: inset,
                 width: size - inset * 2, height: size - inset * 2 },
      })}
      <svg className="portrait-ring" viewBox={`0 0 ${size} ${size}`} width={size} height={size} aria-hidden="true">
        <circle cx={cx} cy={cy} r={r - 3} fill="none" stroke="var(--current)" strokeWidth="2" />
        <circle cx={cx} cy={cy} r={r - inset + 3} fill="none" stroke="var(--rule-strong)" strokeWidth="1" opacity="0.7" />
        {ticks.map((t, i) => (
          <line key={i} x1={t.x1} y1={t.y1} x2={t.x2} y2={t.y2}
                stroke="var(--current)" strokeWidth="1.5" opacity={i % 2 ? 0.4 : 0.85} />
        ))}
      </svg>
    </div>
  );
}

/* One story page. `story` = {
   n, kicker, title, sub, lede(adult/kids),
   panels: [{ initials, seed, name, years, heading, body(adult/kids) }],
   idea: { adult, kids }, bridge: { href, label, blurb } } */
function StoryPage({ story }) {
  const [t, setTweak] = useTweaks({ theme: "paper", audience: "adult" });
  useCrossChapterPersistence(t, setTweak);
  useEffect(() => { document.body.setAttribute("data-theme", t.theme); }, [t.theme]);
  const kids = t.audience === "kids";
  const pick = (v) => (typeof v === "object" && v !== null && ("adult" in v || "kids" in v))
    ? (kids ? v.kids : v.adult) : v;

  // where this story sits in the Level 0 sequence → what comes next
  const L0 = (typeof L0_CHAPTERS !== "undefined") ? L0_CHAPTERS : [];
  const sIdx = L0.findIndex((c) => c.n === story.n);
  const nextStory = (sIdx >= 0 && sIdx < L0.length - 1) ? L0[sIdx + 1] : null;
  const isLastStory = sIdx === L0.length - 1;

  const navItems = [
    { id: "cover", label: "Cover" },
    ...story.panels.map((p, i) => ({ id: `p${i}`, label: p.name.split(" ").slice(-1)[0] })),
    { id: "idea", label: kids ? "Big idea" : "The idea" },
    { id: "bridge", label: "Next" },
  ];

  return (
    <>
      <ChapterStartMarker chapterN={story.n} />
      <ProgressBar />
      <TopBar currentN={story.n} chapterLabel={`Level 0 · ${story.title}`}
              audience={t.audience} setAudience={(v) => setTweak("audience", v)} />
      <ChapterNav items={navItems} />

      <main>
        <section className="cover-page" id="cover" data-screen-label={`${story.n} Cover`}>
          <div className="hero-grid"></div>
          <div className="cover-inner">
            <div style={{ display: "flex", alignItems: "baseline", gap: 16, marginBottom: 28 }}>
              <span className="eyebrow" style={{ color: "var(--current)" }}>Level 0 · The Story</span>
              <span className="eyebrow" style={{ color: "var(--ink-faint)" }}>·</span>
              <span className="eyebrow">{story.kicker}</span>
            </div>
            <h1 className="serif cover-title">{story.title}</h1>
            <div className="eyebrow" style={{ marginTop: 36, marginBottom: 16, color: "var(--current)" }}>
              {story.sub}
            </div>
            <div className="cover-lede">{pick(story.lede)}</div>
            <div className="cover-cta">
              <a href="#p0" className="arrow-link"><span>Read the story</span><span className="arrow-glyph">↓</span></a>
            </div>
          </div>
        </section>

        {story.panels.map((p, i) => (
          <section key={i} className="section story-panel" id={`p${i}`}
                   data-screen-label={p.name}
                   style={i % 2 ? { background: "var(--bg-deeper)" } : null}>
            <div className="marker">§ 0{i + 1} · {p.years}</div>
            <div className="section-inner">
              <div className="story-grid" data-flip={i % 2 ? "1" : "0"}>
                <div className="story-portrait">
                  <PortraitMedallion slotId={`portrait-${story.n}-${i}`}
                                     name={p.name} initials={p.initials} />
                  <div className="story-name">{p.name}</div>
                  <div className="story-years">{p.years}</div>
                </div>
                <div className="story-text">
                  <h2 className="serif">{p.heading}</h2>
                  <div className="lede" style={{ marginTop: 6 }}>{pick(p.body)}</div>
                </div>
              </div>
            </div>
          </section>
        ))}

        <section className="section" id="idea">
          <div className="marker">§ the key idea</div>
          <div className="section-inner" style={{ maxWidth: 820 }}>
            <div className="story-idea">
              <div className="eyebrow" style={{ color: "var(--current)", marginBottom: 12 }}>What it gave us</div>
              <p className="story-idea-text">{pick(story.idea)}</p>
            </div>
          </div>
        </section>

        <section className="section" id="bridge" style={{ background: "var(--bg-deeper)", paddingBottom: "12vh" }}>
          <div className="marker">§ where to next</div>
          <div className="section-inner">
            <div className="story-next">
              {/* primary: continue the narrative */}
              {nextStory ? (
                <a href={nextStory.href} className="story-next-card primary">
                  <div className="snc-kick">Continue the story →</div>
                  <div className="snc-num">{nextStory.n}</div>
                  <h3 className="serif">{nextStory.t}</h3>
                  <p>{nextStory.sub}</p>
                  <div className="snc-portrait">
                    <EtchedPortrait initials={story.panels[0].initials} seed={9} size={92} />
                  </div>
                </a>
              ) : (
                <a href="index.html" className="story-next-card primary">
                  <div className="snc-kick">That's the whole story →</div>
                  <div className="snc-num">★</div>
                  <h3 className="serif">The story is done.</h3>
                  <p>From Volta's pile to the transistor — you've read the history. Now go build it.</p>
                </a>
              )}

              {/* secondary: jump into the matching theory chapter */}
              <a href={story.bridge.href} className="story-next-card">
                <div className="snc-kick" style={{ color: "var(--water)" }}>See it work →</div>
                <h3 className="serif">{story.bridge.label}</h3>
                <p>{story.bridge.blurb}</p>
              </a>
            </div>

            <div className="story-next-foot">
              <a href="map.html">← All stories &amp; course map</a>
              {nextStory && <a href={story.bridge.href}>Skip to the theory →</a>}
              {isLastStory && <a href="chapter1.html">Start Level 1 · The Theory →</a>}
            </div>
          </div>
        </section>
      </main>

      <TweaksPanel title="Tweaks">
        <CommonTweaks t={t} setTweak={setTweak} />
      </TweaksPanel>
      <GlossaryFab />
    </>
  );
}

Object.assign(window, { StoryPage, EtchedPortrait, PortraitMedallion });
