/* homestory.jsx — the storytelling front page: one sticky SVG loop that the
   scroll narrates. Beat by beat the water loop becomes a copper circuit, grows
   parts, becomes a real breadboard, and ends as the blinking beacon. Reuses the
   chapters' .lesson / .beat / .lesson-sticky scaffolding from styles.css.
   Names hs*. Exports HomeStory. */

const { useState: hsUseState } = React;

/* one dot pool riding the loop via SMIL; colour comes from CSS by mode */
function hsDots(path, n, dur) {
  return Array.from({ length: n }, (_, i) => (
    <circle key={i} className="hs-dot" r="5" stroke="rgba(0,0,0,0.3)" strokeWidth="0.6">
      <animateMotion dur={dur + "s"} repeatCount="indefinite" path={path} begin={(-i * dur / n) + "s"} />
    </circle>
  ));
}

function HsScene({ mode }) {
  // the loop: rounded rect, clockwise, starting under the source device
  const LOOP = "M110 240 L110 136 Q110 110 136 110 L384 110 Q410 110 410 136 L410 444 Q410 470 384 470 L136 470 Q110 470 110 444 Z";
  const on = (m) => (Array.isArray(m) ? m.includes(mode) : m === mode);
  const L = (visible, cls, children) => (
    <g className={"hs-layer" + (cls ? " " + cls : "")} style={{ opacity: visible ? 1 : 0 }}>{children}</g>
  );
  const water = mode === "water";
  const mono = "IBM Plex Mono, monospace";

  return (
    <svg className="hs" data-mode={mode} viewBox="0 0 520 600" width="100%" height="600" style={{ display: "block" }}>
      {/* ── the loop itself: water pipe under, copper over ── */}
      {L(water, "", <path d={LOOP} fill="none" stroke="#5aa7d6" strokeWidth="7" strokeLinejoin="round" opacity="0.9" />)}
      {L(!water, "", <path d={LOOP} fill="none" stroke="#b8731f" strokeWidth="3.6" strokeLinejoin="round" />)}

      {/* ── left: pump ↔ battery (device sits on the wire, y 240–340) ── */}
      {L(water, "",
        <g>
          <rect x="82" y="246" width="56" height="90" rx="8" fill="var(--bg-deeper)" stroke="#5aa7d6" strokeWidth="2.4" />
          <path d="M88 272 q7 -6 14 0 t14 0 t14 0" fill="none" stroke="#5aa7d6" strokeWidth="2.2" />
          <path d="M88 288 q7 -6 14 0 t14 0 t14 0" fill="none" stroke="#5aa7d6" strokeWidth="2.2" opacity="0.6" />
          <text x="110" y="322" textAnchor="middle" fontFamily={mono} fontSize="12" fill="var(--ink-soft)">PUMP</text>
        </g>)}
      {L(!water, "",
        <g>
          <rect x="92" y="252" width="36" height="78" rx="4" fill="var(--bg-card)" stroke="none" />
          <line x1="88" y1="272" x2="132" y2="272" stroke="var(--ink)" strokeWidth="4" />
          <line x1="97" y1="286" x2="123" y2="286" stroke="var(--ink)" strokeWidth="2.6" />
          <line x1="88" y1="300" x2="132" y2="300" stroke="var(--ink)" strokeWidth="4" />
          <line x1="97" y1="314" x2="123" y2="314" stroke="var(--ink)" strokeWidth="2.6" />
          <text x="110" y="248" textAnchor="middle" fontFamily={mono} fontSize="13" fill="var(--current)" fontWeight="600">9 V</text>
        </g>)}

      {/* ── right: pinch ↔ resistor (y 250–330 on x=410) ── */}
      {L(water, "",
        <g>
          <polygon points="398,252 410,290 398,328" fill="var(--bg-card)" stroke="#5aa7d6" strokeWidth="2" />
          <polygon points="422,252 410,290 422,328" fill="var(--bg-card)" stroke="#5aa7d6" strokeWidth="2" />
          <text x="434" y="294" fontFamily={mono} fontSize="12" fill="var(--ink-soft)">PINCH</text>
        </g>)}
      {L(!water, "",
        <g>
          <rect x="398" y="250" width="24" height="80" fill="var(--bg-card)" stroke="none" />
          <path d="M410 250 L410 258 L399 264 L421 276 L399 288 L421 300 L399 312 L421 318 L410 324 L410 330" fill="none" stroke="var(--ink)" strokeWidth="2.8" strokeLinejoin="round" />
          <text x="430" y="294" fontFamily={mono} fontSize="12.5" fill="var(--ink)" fontWeight="600">330 Ω</text>
        </g>)}

      {/* ── the labels that swap — the whole trick of the course ── */}
      {L(water, "",
        <g fontFamily={mono} fontSize="13" fill="#3f83b8" fontWeight="600">
          <text x="66" y="290" textAnchor="end">PRESSURE</text>
          <text x="260" y="94" textAnchor="middle">FLOW →</text>
        </g>)}
      {L(on(["circuit", "parts"]), "",
        <g fontFamily={mono} fontSize="13" fill="var(--current)" fontWeight="600">
          <text x="66" y="290" textAnchor="end">VOLTAGE</text>
          <text x="260" y="94" textAnchor="middle">CURRENT →</text>
        </g>)}

      {/* ── the parts, arriving one story-beat later ── */}
      {L(on(["parts", "build", "beacon"]), "",
        <g>
          {/* capacitor on the top run */}
          <rect x="246" y="96" width="28" height="28" fill="var(--bg-card)" stroke="none" />
          <line x1="252" y1="94" x2="252" y2="126" stroke="var(--ink)" strokeWidth="3.4" />
          <line x1="268" y1="94" x2="268" y2="126" stroke="var(--ink)" strokeWidth="3.4" />
          <text x="260" y="146" textAnchor="middle" fontFamily={mono} fontSize="11.5" fill="var(--ink-faint)">capacitor</text>
          {/* switch on the bottom run */}
          <rect x="234" y="456" width="52" height="28" fill="var(--bg-card)" stroke="none" />
          <circle cx="240" cy="470" r="4" fill="var(--ink)" />
          <circle cx="280" cy="470" r="4" fill="var(--ink)" />
          <line x1="240" y1="470" x2="276" y2="452" stroke="var(--ink)" strokeWidth="2.8" strokeLinecap="round" />
          <text x="260" y="500" textAnchor="middle" fontFamily={mono} fontSize="11.5" fill="var(--ink-faint)">switch</text>
          {/* LED on the top-right run */}
          <rect x="330" y="96" width="30" height="28" fill="var(--bg-card)" stroke="none" />
          <polygon points="334,98 356,98 345,120" fill="none" stroke="#d23f34" strokeWidth="2.4" strokeLinejoin="round" />
          <line x1="334" y1="122" x2="356" y2="122" stroke="#d23f34" strokeWidth="2.6" />
          <line x1="358" y1="92" x2="366" y2="84" stroke="#e0a32e" strokeWidth="2" strokeLinecap="round" className={mode === "beacon" ? "hs-blink" : ""} />
          <line x1="364" y1="100" x2="374" y2="96" stroke="#e0a32e" strokeWidth="2" strokeLinecap="round" className={mode === "beacon" ? "hs-blink" : ""} />
          <text x="345" y="146" textAnchor="middle" fontFamily={mono} fontSize="11.5" fill="var(--ink-faint)">LED</text>
        </g>)}

      {/* ── interior: build mode shows the same circuit on a mini board ── */}
      {L(mode === "build", "",
        <g>
          <rect x="152" y="200" width="216" height="160" rx="10" fill="#e8e0cf" stroke="#c9bda3" strokeWidth="1.5" />
          <line x1="168" y1="224" x2="352" y2="224" stroke="#c0392b" strokeWidth="2.2" opacity="0.85" />
          <line x1="168" y1="336" x2="352" y2="336" stroke="#2f6db0" strokeWidth="2.2" opacity="0.85" />
          {Array.from({ length: 9 }, (_, i) => <circle key={"t" + i} cx={176 + i * 21} cy="224" r="2.2" fill="#3a3327" opacity="0.5" />)}
          {Array.from({ length: 9 }, (_, i) => <circle key={"b" + i} cx={176 + i * 21} cy="336" r="2.2" fill="#3a3327" opacity="0.5" />)}
          {Array.from({ length: 9 }, (_, i) => <circle key={"m" + i} cx={176 + i * 21} cy="280" r="2.2" fill="#3a3327" opacity="0.35" />)}
          {/* resistor + LED bridging the rails, like L2-01 */}
          <line x1="218" y1="224" x2="218" y2="244" stroke="var(--ink-soft)" strokeWidth="2" />
          <rect x="210" y="244" width="16" height="34" rx="5" fill="#d8c6a0" stroke="#b9a279" />
          {["#8a5a2b", "#111", "#b8731f"].map((c, i) => <rect key={i} x="210" y={250 + i * 8} width="16" height="3.6" fill={c} />)}
          <line x1="218" y1="278" x2="218" y2="280" stroke="var(--ink-soft)" strokeWidth="2" />
          <path d="M218 280 Q260 264 302 280" fill="none" stroke="var(--ink)" strokeWidth="2.6" strokeLinecap="round" />
          <line x1="302" y1="280" x2="302" y2="296" stroke="var(--ink-soft)" strokeWidth="2" />
          <circle cx="302" cy="308" r="11" fill="rgba(255,90,77,0.85)" stroke="#a04437" strokeWidth="1.4" />
          <line x1="302" y1="319" x2="302" y2="336" stroke="var(--ink-soft)" strokeWidth="2" />
          <text x="260" y="382" textAnchor="middle" fontFamily={mono} fontSize="12" fill="var(--ink-soft)">the same loop, on a real board</text>
        </g>)}

      {/* ── interior: the beacon finale ── */}
      {L(mode === "beacon", "",
        <g>
          <line x1="260" y1="270" x2="260" y2="368" stroke="var(--ink-soft)" strokeWidth="4" />
          <line x1="222" y1="382" x2="298" y2="382" stroke="var(--ink-soft)" strokeWidth="4" strokeLinecap="round" />
          <line x1="238" y1="382" x2="260" y2="352" stroke="var(--ink-soft)" strokeWidth="2.6" />
          <line x1="282" y1="382" x2="260" y2="352" stroke="var(--ink-soft)" strokeWidth="2.6" />
          <circle className="hs-blink" cx="260" cy="246" r="20" fill="var(--current)" />
          <circle cx="260" cy="246" r="20" fill="none" stroke="var(--current-deep)" strokeWidth="2" />
          <circle className="hs-ring" cx="260" cy="246" r="34" fill="none" stroke="var(--current)" strokeWidth="1.6" />
          <text x="260" y="416" textAnchor="middle" fontFamily={mono} fontSize="12" fill="var(--ink-soft)">blinking at the rate YOU specced</text>
        </g>)}

      {/* ── the charges, always circulating ── */}
      <g>{hsDots(LOOP, 9, 8)}</g>

      {/* footer caption inside the stage */}
      {L(on(["water", "circuit"]), "",
        <text x="260" y="560" textAnchor="middle" fontFamily={mono} fontSize="12.5" fill="var(--ink-faint)">
          {water ? "one loop of water, pushed round and round" : "same loop — the dots are charge now"}
        </text>)}
    </svg>
  );
}

/* ── the beats ── */
function HsBeat({ id, marker, title, children, onView, first }) {
  const ref = useInViewCallback(onView);
  return (
    <div className={"beat" + (first ? " beat-cover" : "")} id={id} data-screen-label={title} ref={ref}>
      <div className="beat-marker">{marker}</div>
      {children}
    </div>
  );
}

const HS_STAGE_LABEL = {
  water: "WATER · pressure pushes flow through a pinch",
  circuit: "THE SAME LOOP · copper edition",
  parts: "THE PARTS · each chapter adds one",
  build: "THE BUILD · diagram becomes board",
  beacon: "THE BEACON · your final build",
};

function HomeStory({ kids, resumeHref, ctaLabel }) {
  const [mode, setMode] = hsUseState("water");
  // reset to the first beat when the user scrolls back above the story —
  // beat 1's trigger band never re-fires once you're up in the hero.
  const secRef = React.useRef(null);
  React.useEffect(() => {
    const onScroll = () => {
      const el = secRef.current;
      if (el && el.getBoundingClientRect().top > window.innerHeight * 0.33) {
        setMode("water");
      }
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  return (
    <section className="lesson hs-lesson" data-mode={mode} ref={secRef}>
      <aside className="lesson-sticky" data-single="1">
        <div className="vis-block">
          <div className="stage-label">{HS_STAGE_LABEL[mode]}</div>
          <HsScene mode={mode} />
        </div>
      </aside>
      <div className="lesson-scroll">
        <HsBeat id="hs-water" marker="§ 01 · it starts with water" title="01 Water" onView={() => setMode("water")}>
          <h2 className="serif">You already<br /><em>understand this</em>.</h2>
          <p className="lede">
            {kids
              ? <>Ever squeezed a hose? Push, flow, pinch — you can feel all three. Electricity works exactly the same way, just too small to see.</>
              : <>You've felt electricity every time you've used a hose: pressure pushes, flow moves, a pinch fights back. That intuition is real physics — and it's the whole foundation.</>}
          </p>
          <p className="marg">Watch the loop: water, pushed round and round.</p>
        </HsBeat>
        <HsBeat id="hs-circuit" marker="§ 02 · the one trick" title="02 The trick" onView={() => setMode("circuit")}>
          <h2 className="serif">Now swap<br />the <em>labels</em>.</h2>
          <p className="lede">
            {kids
              ? <>The pump becomes a battery. The pipe becomes copper. The pinch becomes a resistor. Nothing else changed — look, the loop is the same!</>
              : <>Pump → battery. Pipe → copper. Pinch → resistor. Pressure is <em>voltage</em>, flow is <em>current</em> — the same loop, relabelled. Every chapter in this course teaches with that translation.</>}
          </p>
        </HsBeat>
        <HsBeat id="hs-parts" marker="§ 03 · collect the parts" title="03 Parts" onView={() => setMode("parts")}>
          <h2 className="serif">Ten chapters,<br /><em>one new power each</em>.</h2>
          <p className="lede">
            {kids
              ? <>A gate you can open and shut. A bucket that stores charge. A one-way door that glows. Chapter by chapter, the loop grows new tricks.</>
              : <>A switch. A capacitor that stores charge and keeps time. An LED. Then the punchline — a valve electricity flips by itself, the transistor. Each idea arrives as something you can watch move.</>}
          </p>
        </HsBeat>
        <HsBeat id="hs-build" marker="§ 04 · then build it" title="04 Build" onView={() => setMode("build")}>
          <h2 className="serif">Then build it<br /><em>for real</em>.</h2>
          <p className="lede">
            {kids
              ? <>The drawing becomes a real breadboard with real parts. Every idea you learn, you wire up and light up yourself.</>
              : <>Level 2 walks every idea onto a real breadboard — reading the schematic, picking the values, wiring it, debugging it. The diagram and the board are the same circuit; you'll hold both in your head.</>}
          </p>
        </HsBeat>
        <HsBeat id="hs-beacon" marker="§ 05 · the finale" title="05 Beacon" onView={() => setMode("beacon")}>
          <h2 className="serif">And leave with<br />a <em>beacon</em>.</h2>
          <p className="lede">
            {kids
              ? <>At the end you assemble the whole thing: a signal beacon that blinks on its own — because you built it to.</>
              : <>The course caps with a device: a flashing signal beacon you specced, sized, and assembled — blinking at the rate you designed. Below is the whole trail.</>}
          </p>
          <div className="home-cta-row" style={{ marginTop: 26 }}>
            <a href={resumeHref} className="cta cta-primary">{ctaLabel} →</a>
            <a href="#course" className="cta cta-secondary">See the whole course ↓</a>
          </div>
        </HsBeat>
      </div>
    </section>
  );
}

Object.assign(window, { HomeStory });
