/* chapter.jsx — Chapter 1: The Flow
   Uses CoverPage (full-bleed) + LessonScrollyteller (sticky animations).
   Helpers from shared.jsx via window. */

const { useState, useEffect, useRef } = React;

/* ─── BEATS (live inside the lesson grid, paired w/ sticky visuals) ───── */

function BigIdeaBeat({ onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="begin" data-screen-label="02 The analogy" ref={ref}>
      <div className="beat-marker">§ 01 · the map</div>
      {kids ? (
        <>
          <h2 className="serif">Water and electricity<br/>are <em>twins</em>.</h2>
          <p className="lede">
            A wire is a pipe. A battery is a barrel of water held up high.
            Pinching the pipe is just like adding a resistor to a wire.
          </p>
          <p>
            Anything water does, electricity does too — you just can't see it.
            So we'll look at the water and trust that the wire is doing the same.
          </p>
        </>
      ) : (
        <>
          <h2 className="serif">An electron is a <em>very</em> tiny drop of water.</h2>
          <p className="lede">
            Not literally. But the math is the same, the intuition is the same,
            and once you see the resemblance you'll never un-see it.
          </p>
          <p>
            A wire is a pipe. A battery is a <em>barrel</em> of water held up high.
            A resistor is a pinch in the pipe. The thing we care about — the thing
            that does <em>work</em> at the other end — is the <em>flow</em>.
          </p>
        </>
      )}
      <div className="pull">
        "Voltage pushes. Current flows. Resistance gets in the way."
      </div>

      <div style={{ marginTop: 28, display: "grid", gridTemplateColumns: "repeat(2, minmax(0, 1fr))", gap: 12 }}>
        {[
          { water: kids ? "Water push" : "Water pressure", elec: kids ? "Volts" : "Voltage", sym: "V", accent: "water" },
          { water: kids ? "Water speed" : "Flow rate",     elec: kids ? "Amps"  : "Current", sym: "I", accent: "current" },
          { water: kids ? "Pinch in pipe" : "Narrow pipe", elec: kids ? "Ohms"  : "Resistance", sym: "R", accent: "" },
          { water: kids ? "Open the tap" : "Open spigot",  elec: kids ? "Switch on" : "Closed circuit", sym: "—", accent: "" },
        ].map((m) => (
          <div key={m.sym + m.elec} className="card" style={{ background: "transparent", padding: "14px 16px" }}>
            <div className="eyebrow" style={{ marginBottom: 8 }}>{m.water}</div>
            <div className="serif" style={{ fontSize: 22, fontStyle: "italic", display: "flex", alignItems: "baseline", gap: 10 }}>
              <span>→ {m.elec}</span>
              {m.sym !== "—" && (
                <span className="mono" style={{ fontSize: 14, color: m.accent === "water" ? "var(--water)" : m.accent === "current" ? "var(--current)" : "var(--ink-faint)" }}>
                  {m.sym}
                </span>
              )}
            </div>
          </div>
        ))}
      </div>

      <div className="card" style={{ marginTop: 16, background: "transparent", borderColor: "var(--rule)" }}>
        <div className="eyebrow" style={{ marginBottom: 8 }}>{kids ? "wait — where does the water go?" : "one honest note about the picture"}</div>
        <p style={{ margin: 0, fontSize: 15.5, color: "var(--ink-soft)" }}>
          {kids
            ? <>We let the water splash out of the pipe so you can <em>see</em> it move. But a real circuit is a <em>loop</em> — look at the wires in the ELECTRICITY picture (on a phone, tap the CIRCUIT tab above the animation). The battery is like a pump: it scoops the water back up to the top of the barrel, again and again. The water never runs out, and that's why the electrons just keep circling around.</>
            : <>The animation lets the water spill from the pipe so the flow is easy to watch — but a real circuit is a <em>closed loop</em>: see the ELECTRICITY panel below the water scene (on a phone, flip to it with the CIRCUIT tab). Picture the battery as a <em>pump</em>: it catches the spent water at the bottom and lifts it back up to the barrel, over and over. The water is never used up — only its <em>pressure</em> is spent crossing the pinch. Charge behaves the same way: the same electrons circle the loop forever, and the battery just keeps re-energizing them.</>}
        </p>
      </div>
    </div>
  );
}

function VoltageBeat({ v, setV, onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="voltage" data-screen-label="03 Voltage" ref={ref}>
      <div className="beat-marker">§ 02 · the push</div>
      <div className="chip water" style={{ marginBottom: 16 }}>V · volts</div>
      <h2 className="serif"><em>Voltage</em> is the push.</h2>
      {kids ? (
        <>
          <p className="lede">
            The barrel is at <span className="mono" style={{ color: "var(--water)" }}>{fmt(v, 1)} V</span> right
            now. The taller the water column, the harder it pushes down on
            the pipe.
          </p>
          <p>
            A tiny AA battery is a <span className="mono">1.5 V</span> barrel.
            A wall outlet is a giant <span className="mono">120 V</span> tower —
            don't stick your finger in it.
          </p>
        </>
      ) : (
        <>
          <p className="lede">
            Think of a barrel held up high. The taller the water column, the
            harder it presses down on whatever's at the spigot. That{" "}
            <em>pressure</em> is voltage.
          </p>
          <p>
            A AA battery is a <span className="mono">1.5 V</span> barrel.
            A car battery is a <span className="mono">12 V</span> reservoir.
            Same idea — different ceiling.
          </p>
          <div className="marg" style={{ marginTop: 12 }}>
            <em>Aside.</em> "Volt" is named after Alessandro Volta, who in 1799
            stacked discs of copper and zinc with brine-soaked cardboard and
            got electricity to come out.
          </div>
        </>
      )}
      <div className="rule">try it · fill the barrel →</div>
      <Slider name="Voltage · push" value={v} min={0} max={12} step={0.5}
              unit="V" accent="water" onChange={setV}
              hint={kids ? "Pull right for more push." : "Watch the barrel fill — that's the pressure building."} />
    </div>
  );
}

function CurrentBeat({ v, r, onView, kids }) {
  const ref = useInViewCallback(onView);
  const I = v / r;
  return (
    <div className="beat" id="current" data-screen-label="04 Current" ref={ref}>
      <div className="beat-marker">§ 03 · the flow</div>
      <div className="chip current" style={{ marginBottom: 16 }}>I · amperes</div>
      <h2 className="serif"><em>Current</em> is what comes out.</h2>
      {kids ? (
        <>
          <p className="lede">
            Right now, <span className="mono" style={{ color: "var(--current)" }}>{fmt(I, 2)} A</span> of
            water is rushing through the pipe. "A" means <em>amperes</em>, or{" "}
            <em>amps</em> for short — the count of how fast it flows.
          </p>
          <p>
            More push (V), more flow. Tighter pinch (R), less flow.
            You don't drag a "current" slider — current is what <em>happens</em>{" "}
            when you mess with the other two.
          </p>
          <p>
            And here's how to SEE it: the wavy streaks inside the pipe <em>are</em>{" "}
            the current. Crank the push way up and they sprint. Tighten the pinch
            and they slow to a crawl — the same water, just barely creeping along.
            Faster streaks = more water passing every second = more current. Try it!
          </p>
          <div className="pull">Current is the <em>answer</em>.</div>
        </>
      ) : (
        <>
          <p className="lede">
            Stand under the spigot. How fast is the water actually <em>moving
            through</em>? That's current.
          </p>
          <p>
            In a wire, it's the count of electrons passing a point each second.
            One ampere ≈ <span className="mono">6.24 × 10¹⁸</span> electrons per
            second. (Yes. Per second.)
          </p>
          <p>
            You never set current directly. You choose the pressure and you
            choose the resistance — the current is simply whatever flow those
            two allow.
          </p>
          <p>
            The animation makes this literal: the drifting streaks in the pipe
            move at the water's speed, and in a pipe of fixed size, speed and
            flow are the same thing. Drag V up and watch them sprint; drag R up
            and watch the same streaks slow to a crawl. When the streaks barely
            creep, barely any charge is passing — <em>that</em> is low current.
          </p>
          <div className="pull">Current is an <em>answer</em>, not a knob.</div>
          <div className="card" style={{ marginTop: 18, background: "transparent" }}>
            <div className="eyebrow" style={{ marginBottom: 8 }}>right now</div>
            <div style={{ display: "flex", alignItems: "baseline", gap: 18, flexWrap: "wrap" }}>
              <div className="eq" style={{ fontSize: 36 }}>
                <span className="num" style={{ color: "var(--current)" }}>{fmt(I, 2)}</span>
                <span className="op" style={{ fontSize: 18, marginLeft: 8 }}>A</span>
              </div>
              <div className="marg">
                = {fmt(v, 1)} V ÷ {fmt(r, 1)} Ω.
              </div>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

function ResistanceBeat({ r, setR, onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="resistance" data-screen-label="05 Resistance" ref={ref}>
      <div className="beat-marker">§ 04 · the squeeze</div>
      <div className="chip" style={{ marginBottom: 16 }}>R · ohms</div>
      <h2 className="serif"><em>Resistance</em> is the squeeze.</h2>
      {kids ? (
        <>
          <p className="lede">
            The pipe is pinched to <span className="mono">{fmt(r, 1)} Ω</span> right
            now. Ω is the Greek letter <em>omega</em> — that's the unit for
            squeeze.
          </p>
          <p>
            Bigger Ω, tighter pinch, less water gets through. A toaster's
            wire has lots of Ω, and that's <em>why it gets hot</em> — squeezing
            flow turns into heat.
          </p>
          <p>
            Look at the pipe's color: it's <span style={{ color: "var(--water)" }}>deep</span> (lots of push) <em>before</em> the
            pinch, and pale <em>after</em> it. The pinch is where the push gets used up.
          </p>
        </>
      ) : (
        <>
          <p className="lede">
            Pinch the pipe. Less water gets through, even though the barrel
            hasn't moved. In a circuit, that pinch is a <em>resistor</em>.
          </p>
          <p>
            Every wire has a little. Every component has its own. A toaster
            filament has a lot — and on purpose, because squeezing flow is how
            we make heat (and light, and motion).
          </p>
          <div className="marg" style={{ marginTop: 12 }}>
            Named for Georg Ohm, who in 1827 wrote down the relationship we're
            about to meet. Nobody believed him for ten years.
          </div>
          <div className="marg" style={{ marginTop: 10 }}>
            Notice the tint along the pipe: <span style={{ color: "var(--water)" }}>deep</span> (high pressure) before
            the pinch, pale after it. The flow <em>rate</em> is the same on both sides — what the
            pinch spends is the <em>push</em>.
          </div>
        </>
      )}
      <div className="rule">try it · tighten the pinch</div>
      <Slider name="Resistance · squeeze" value={r} min={0.5} max={10} step={0.1}
              unit="Ω" accent="" onChange={setR}
              hint={kids ? "Pull right to squeeze harder." : "Watch the pipe choke down — and the flow with it."} />
    </div>
  );
}

/* New predict-then-reveal beat — sits BEFORE Ohm's Law */
function PredictBeat({ onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="predict" data-screen-label="06 Predict" ref={ref}>
      <div className="beat-marker">§ 05 · check your gut</div>
      <h2 className="serif">Before you scroll —<br/><em>a question</em>.</h2>
      <p className="lede">
        You've seen push, flow, and squeeze in motion. Without scrolling
        down to the answer, what's your prediction?
      </p>

      <PredictReveal
        question={kids
          ? "If you DOUBLE the push (V) but keep the pinch (R) the same, what happens to the flow (I)?"
          : "Double the voltage but keep the resistance fixed. What happens to the current?"}
        options={[
          "It doubles",
          "It halves",
          "It stays the same",
          "It quadruples",
        ]}
        correct={0}
        explanation={kids
          ? "Push twice as hard on the same pinch, twice as much water comes out per second. The relationship is straight-line — that's the magic of Ohm's law on the next screen."
          : "Current scales linearly with voltage when R is held constant: I = V / R, so 2V → 2I. The relationship is one-to-one — that's the heart of Ohm's law, on the next screen."}
        accent="water"
      />

      <PredictReveal
        question={kids
          ? "Keep the push the same, but make the pinch TWICE as tight. What happens to the flow?"
          : "Now hold V fixed and double R. What happens to I?"}
        options={[
          "It doubles",
          "It halves",
          "It stays the same",
          "It quadruples",
        ]}
        correct={1}
        explanation={kids
          ? "Tighter pinch with the same push means less water gets through. Double the pinch → half the flow."
          : "I = V / R, so doubling R halves I. Resistance and current are inversely related when voltage is held."}
        accent="current"
      />
    </div>
  );
}

function OhmsLawBeat({ v, r, onView, kids }) {
  const ref = useInViewCallback(onView);
  const I = v / r;
  if (kids) {
    return (
      <div className="beat" id="ohms-law" data-screen-label="07 Three friends" ref={ref}>
        <div className="beat-marker">§ 06 · the three friends</div>
        <h2 className="serif">V, I, and R<br/>are <em>friends</em>.</h2>
        <p className="lede">
          When you change one, the others change too. That's the secret of
          how everything electric works.
        </p>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, minmax(0, 1fr))", gap: 12, marginTop: 24 }}>
          {[
            { sym: "V", color: "var(--water)",   name: "Volts", desc: "How hard the push." },
            { sym: "I", color: "var(--current)", name: "Amps",  desc: "How fast the flow." },
            { sym: "R", color: "var(--ink)",     name: "Ohms",  desc: "How tight the pinch." },
          ].map(t => (
            <div key={t.sym} className="card" style={{ background: "transparent", padding: "18px 14px", textAlign: "center" }}>
              <div className="serif" style={{ fontSize: 72, lineHeight: 1, fontStyle: "italic", color: t.color }}>{t.sym}</div>
              <div className="eyebrow" style={{ marginTop: 12 }}>{t.name}</div>
              <div className="marg" style={{ margin: "8px auto 0", textAlign: "center" }}>{t.desc}</div>
            </div>
          ))}
        </div>
        <div className="card" style={{ marginTop: 26, background: "transparent" }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>right now</div>
          <p style={{ margin: 0, fontSize: 18 }}>
            Barrel: <span className="mono" style={{ color: "var(--water)" }}>{fmt(v, 1)} V</span>.
            Pinch: <span className="mono">{fmt(r, 1)} Ω</span>.
            Flow: <span className="mono" style={{ color: "var(--current)" }}>{fmt(I, 2)} A</span>.
          </p>
          <p style={{ marginTop: 8, color: "var(--ink-soft)" }}>
            Pump up the barrel → flow gets faster.<br/>
            Squeeze the pipe tighter → flow gets slower.<br/>
            That's it. That's the whole trick.
          </p>
        </div>
      </div>
    );
  }
  return (
    <div className="beat" id="ohms-law" data-screen-label="07 Ohm's Law" ref={ref}>
      <div className="beat-marker">§ 06 · the law</div>
      <h2 className="serif">One equation,<br/>three names.</h2>
      <p className="lede">
        Ohm noticed something obvious-in-hindsight: the push, the flow, and
        the squeeze are <em>locked together</em> by a single relationship.
      </p>
      <div style={{ margin: "32px 0 28px" }}>
        <div className="eq" style={{ fontSize: "clamp(56px, 7vw, 96px)" }}>
          <span className="V">V</span>
          <span className="op">=</span>
          <span className="I">I</span>
          <span className="R">R</span>
        </div>
      </div>
      <div style={{ display: "flex", flexWrap: "wrap", gap: "8px 28px", fontFamily: "'IBM Plex Mono', monospace", fontSize: 12, letterSpacing: "0.12em", color: "var(--ink-soft)", textTransform: "uppercase", marginBottom: 28 }}>
        <span><span style={{ color: "var(--water)" }}>V</span>  volts · push</span>
        <span><span style={{ color: "var(--current)" }}>I</span>  amperes · flow</span>
        <span><span style={{ color: "var(--ink)" }}>R</span>  ohms · squeeze</span>
      </div>
      <p>Read it any of three ways. Same fact, different hat:</p>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3, minmax(0, 1fr))", gap: 12, marginTop: 16 }}>
        {[
          { eq: <><span className="V">V</span><span className="op">=</span><span className="I">I</span><span className="R">R</span></>, hint: "Find the push." },
          { eq: <><span className="I">I</span><span className="op">=</span><span className="frac"><span className="top V">V</span><span className="bar"></span><span className="bot R">R</span></span></>, hint: "Find the flow." },
          { eq: <><span className="R">R</span><span className="op">=</span><span className="frac"><span className="top V">V</span><span className="bar"></span><span className="bot I">I</span></span></>, hint: "Find the squeeze." },
        ].map((x, i) => (
          <div key={i} className="card" style={{ textAlign: "center", padding: "20px 12px", background: "transparent" }}>
            <div className="eq" style={{ fontSize: 34, justifyContent: "center" }}>{x.eq}</div>
            <div className="marg" style={{ marginTop: 10, textAlign: "center", margin: "10px auto 0" }}>{x.hint}</div>
          </div>
        ))}
      </div>
      <div className="card" style={{ marginTop: 28, background: "transparent" }}>
        <div className="eyebrow" style={{ marginBottom: 10 }}>current bookkeeping</div>
        <div className="eq" style={{ fontSize: 32 }}>
          <span className="num" style={{ color: "var(--water)" }}>{fmt(v, 1)}</span>
          <span className="op" style={{ fontSize: 18 }}>V</span>
          <span className="op">=</span>
          <span className="num" style={{ color: "var(--current)" }}>{fmt(I, 2)}</span>
          <span className="op" style={{ fontSize: 18 }}>A</span>
          <span className="op">×</span>
          <span className="num">{fmt(r, 1)}</span>
          <span className="op" style={{ fontSize: 18 }}>Ω</span>
        </div>
      </div>
    </div>
  );
}

function PlaygroundBeat({ v, r, setV, setR, onView, kids }) {
  const ref = useInViewCallback(onView);
  const I = v / r;
  const P = v * I;
  const tone = useToneFollow();
  const idle = React.useRef(null);
  // "hear the current": pitch tracks I, loudness tracks power; fades after idle
  const sing = (nv, nr) => {
    const cur = nv / nr;
    tone.set(Math.min(1, cur / 24), Math.min(1, (nv * cur) / 60));
    if (idle.current) clearTimeout(idle.current);
    idle.current = setTimeout(() => tone.stop(), 280);
  };
  const onV = (x) => { setV(x); sing(x, r); };
  const onR = (x) => { setR(x); sing(v, x); };
  return (
    <div className="beat" id="playground" data-screen-label="08 Playground" ref={ref}>
      <div className="beat-marker">§ 07 · all knobs unlocked</div>
      <h2 className="serif">Now <em>you</em><br/>turn the knobs.</h2>
      <p className="lede">
        {kids
          ? "Drag both sliders. Make the bulb glow as bright as you can."
          : "Push harder. Squeeze tighter. Both at once. The bookkeeping always balances, and the bulb glows in proportion to power — voltage times current."
        }
      </p>
      <SonifyHint />
      <div style={{ marginTop: 24, display: "flex", flexDirection: "column", gap: 6 }}>
        <Slider name="Voltage · push" value={v} min={0} max={12} step={0.5}
                unit="V" accent="water" onChange={onV} />
        <Slider name="Resistance · squeeze" value={r} min={0.5} max={10} step={0.1}
                unit="Ω" accent="" onChange={onR} />
      </div>

      {kids ? (
        <div className="card" style={{ marginTop: 22, background: "transparent" }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>power · how bright the bulb is</div>
          <div className="serif" style={{ fontSize: 32, fontStyle: "italic" }}>
            <span className="mono" style={{ fontStyle: "normal" }}>{fmt(P, 1)}</span> watts of glow
          </div>
          <div className="marg" style={{ marginTop: 10 }}>
            Power is how much real <em>stuff</em> is happening — light, heat,
            motion. Next chapter: more on power.
          </div>
        </div>
      ) : (
        <div className="card" style={{ marginTop: 22, background: "transparent" }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>power · what the bulb feels</div>
          <div className="eq" style={{ fontSize: 36 }}>
            <span style={{ color: "var(--ink)" }}>P</span>
            <span className="op">=</span>
            <span className="V">V</span>
            <span className="op">×</span>
            <span className="I">I</span>
            <span className="op" style={{ marginLeft: 18 }}>=</span>
            <span className="num">{fmt(P, 1)}</span>
            <span className="op" style={{ fontSize: 22 }}>watts</span>
          </div>
          <div className="marg" style={{ marginTop: 10 }}>
            Watts is the answer to "<em>how much actual work is happening?</em>" —
            heat, light, motion, all of it. We'll dig in next chapter.
          </div>
        </div>
      )}

      <div className="rule">presets</div>
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
        {[
          { label: "AA + LED-ish", v: 1.5, r: 7.5 },
          { label: "9V, normal load", v: 9, r: 3 },
          { label: "Tiny push, fat pipe", v: 2, r: 0.5 },
          { label: "Big push, tight pinch", v: 12, r: 10 },
        ].map(p => (
          <button key={p.label}
                  onClick={() => { setV(p.v); setR(p.r); }}
                  style={{
                    appearance: "none",
                    border: "1px solid var(--rule-strong)",
                    background: "transparent",
                    padding: "8px 14px",
                    borderRadius: 999,
                    fontFamily: "'IBM Plex Mono', monospace",
                    fontSize: 11,
                    letterSpacing: "0.06em",
                    color: "var(--ink-soft)",
                    cursor: "pointer",
                  }}>
            {p.label}
          </button>
        ))}
      </div>
    </div>
  );
}

/* ─── LessonScrollyteller ─────────────────────────────────────────────── */
function LessonScrollyteller({ showCircuit, kids }) {
  const [v, setV] = useState(6);
  const [r, setR] = useState(3);
  const [mode, setMode] = useState("begin");
  const I = v / r;
  const P = v * I;
  const visHeight = showCircuit ? 340 : 540;

  return (
    <section className="lesson">
      <div className="lesson-scroll">
        <BigIdeaBeat onView={() => setMode("begin")} kids={kids} />
        <VoltageBeat v={v} setV={setV} onView={() => setMode("voltage")} kids={kids} />
        <CurrentBeat v={v} r={r} onView={() => setMode("current")} kids={kids} />
        <ResistanceBeat r={r} setR={setR} onView={() => setMode("resistance")} kids={kids} />
        <PredictBeat onView={() => setMode("predict")} kids={kids} />
        <OhmsLawBeat v={v} r={r} onView={() => setMode("ohms-law")} kids={kids} />
        <PlaygroundBeat v={v} r={r} setV={setV} setR={setR} onView={() => setMode("playground")} kids={kids} />
      </div>

      <aside className="lesson-sticky" data-single={showCircuit ? "0" : "1"}>
        {showCircuit && <VisTabs labels={["WATER", "CIRCUIT"]} />}
        <div className="vis-block">
          <div className="stage-label">WATER · pressure → flow</div>
          <WaterScene voltage={v} resistance={r} current={I} height={visHeight} />
        </div>
        {showCircuit && (
          <div className="vis-block">
            <div className="stage-label">ELECTRICITY · battery → resistor → lamp</div>
            <CircuitScene voltage={v} resistance={r} current={I} height={visHeight} />
          </div>
        )}
        <div className="vis-readout">
          <div className="ro-v">
            <span className="ro-name">{kids ? "Push" : "Voltage"}</span>
            <span className="ro-val">{fmt(v, 1)}<span className="ro-unit">V</span></span>
          </div>
          <div className="ro-r">
            <span className="ro-name">{kids ? "Squeeze" : "Resistance"}</span>
            <span className="ro-val">{fmt(r, 1)}<span className="ro-unit">Ω</span></span>
          </div>
          <div className="ro-i">
            <span className="ro-name">{kids ? "Flow" : "Current"}</span>
            <span className="ro-val">{fmt(I, 2)}<span className="ro-unit">A</span></span>
          </div>
          <div className="ro-p">
            <span className="ro-name">Power</span>
            <span className="ro-val">{fmt(P, 1)}<span className="ro-unit">W</span></span>
          </div>
        </div>
      </aside>
    </section>
  );
}

/* ─── LoopSection — the closed-loop "what actually flows" view ─────────── */
function LoopSection({ kids }) {
  const [v, setV] = useState(6);
  const [r, setR] = useState(3);
  const [stats, setStats] = useState({ gA: 0, gB: 0 });
  const onStats = React.useCallback((s) => setStats(s), []);
  const ref = useInViewCallback(() => {});
  const I = r ? v / r : 0;
  const gA = stats.gA, gB = stats.gB;
  const consMatch = Math.abs(gA - gB) <= Math.max(1.2, 0.18 * Math.max(gA, gB));

  return (
    <section className="section" id="loop" data-screen-label="09 The loop" ref={ref}
             style={{ background: "var(--bg-deeper)" }}>
      <div className="marker">§ the real picture · one closed loop</div>
      <div className="section-inner" style={{ maxWidth: 980 }}>
        <h2 className="serif" style={{ marginBottom: 14 }}>
          {kids ? <>Follow one drop<br/><em>around the loop.</em></> : <>Follow one charge<br/><em>around the loop.</em></>}
        </h2>
        <p className="lab-lede">
          {kids
            ? <>The barrel-and-pipe let the water splash out so you could see it. A <b>real</b> circuit is a <b>loop</b> that never spills. Each dot is a bit of charge, and they go round forever — <b>none get used up</b>. Watch the <b>colour</b>: a dot leaves the battery <span className="fl-bright">bright</span> (full of push) and comes back <span className="fl-dim">pale</span> (push spent), and the battery fills it up again.</>
            : <>Each dot is a particle of charge, and they ride the loop forever — <b>none are ever used up</b>. What changes is the <b>colour</b>: a charge leaves the battery <span className="fl-bright">bright</span>, loaded with energy. Crossing the pinch it hands that energy over — as heat — and coasts back <span className="fl-dim">pale</span> and empty, until the battery reloads it for another lap.</>}
        </p>
        <p className="fl-explain">
          <span><b className="fl-bright">{kids ? "“Full of push”" : "“Full of push”"}</b> = the charge is carrying the energy the battery just gave it.</span>
          <span><b className="fl-dim">“Push spent”</b> = it handed that energy to the resistor and coasts back empty for a refill.</span>
          <span>The charge is never consumed — <b>only its energy</b> is spent and renewed.</span>
        </p>
        <FactCard eyebrow={kids ? "where do the charges come from?" : "where do the charges come from?"}>
          <p>
            They’re <b>already there.</b> A wire is packed wall-to-wall with free electrons before you connect
            anything — like a pipe that’s <b>already full of water</b>. The battery doesn’t <em>supply</em> the
            charges; it just <b>pushes the ones already in the wire</b>, and the whole loop starts shuffling at once.
          </p>
          <p>
            So a <b>bigger battery doesn’t mean more electrons.</b> The water picture can mislead here — a taller
            barrel looks like “more water,” but a bigger battery only pushes <b>harder</b> (more voltage) or
            <b> longer</b> (more stored energy). The number of charges in the wire never changes.
          </p>
        </FactCard>

        <FactCard eyebrow={kids ? "why does the squeeze slow things down?" : "what IS resistance, physically?"}>
          <p>
            {kids
              ? <>Look inside the pinch: it's <b>packed with stuff!</b> The dots have to weave past every little atom of the material. Turn the squeeze up and the atoms pack in <b>tighter</b> — more bumping, slower flow, and every bump makes a little <b>heat</b>.</>
              : <>Zoom into the pinch and you'll see it's a <b>material</b> — an ordered lattice of atoms the electrons must weave through. Raise the resistance and the lattice packs denser — more collisions, less flow. Each collision hands energy to the lattice, which is exactly why <b>resistance makes heat</b>. Watch the wisps rise off the pinch: every bit of push the battery pours in leaves the loop right there.</>}
          </p>
        </FactCard>

        <div style={{ marginTop: 22 }}>
          <LoopScene v={v} r={r} kids={kids} onStats={onStats} />
        </div>

        <div className="lab-readouts">
          <div className="ro">
            <span className="ro-name">{kids ? "Push" : "Push · voltage"}</span>
            <span className="ro-val" style={{ color: "var(--water)" }}>{v.toFixed(0)}<i>V</i></span>
          </div>
          <div className="ro">
            <span className="ro-name">{kids ? "Pinch" : "Pinch · resistance"}</span>
            <span className="ro-val">{r.toFixed(0)}<i>Ω</i></span>
          </div>
          <div className="ro">
            <span className="ro-name">{kids ? "Flow = push ÷ pinch" : "Flow · current = V ÷ R"}</span>
            <span className="ro-val" style={{ color: "var(--current)" }}>{I.toFixed(2)}<i>A</i></span>
          </div>
          <div className="ro">
            <span className="ro-name">Gate A = Gate B?</span>
            <span className="ro-val" style={{ fontSize: 19, color: consMatch ? "var(--water)" : "var(--ink)" }}>
              {gA.toFixed(0)} <span style={{ color: "var(--ink-faint)" }}>≈</span> {gB.toFixed(0)}
              <i style={{ display: "block", marginTop: 2 }}>{consMatch ? "conserved ✓" : "settling…"}</i>
            </span>
          </div>
        </div>

        <div className="lab-controls">
          <label className="lab-slider">
            <span className="ls-top"><span>Push <i>(voltage)</i></span><span className="ls-v">{v} V</span></span>
            <input type="range" min="0" max="14" step="1" value={v} onChange={e => setV(+e.target.value)} className="range range-water" />
            <span className="ls-hint">{kids ? "More push → the whole loop flows faster. At 0 nothing moves." : "More push → the whole loop flows faster. At 0 V nothing moves."}</span>
          </label>
          <label className="lab-slider">
            <span className="ls-top"><span>Pinch <i>(resistance)</i></span><span className="ls-v">{r} Ω</span></span>
            <input type="range" min="1" max="10" step="1" value={r} onChange={e => setR(+e.target.value)} className="range range-current" />
            <span className="ls-hint">{kids ? "Tighter pinch → more atoms packed in the way → less flow everywhere." : "Higher R packs the lattice denser — more collisions, less flow through the whole loop."}</span>
          </label>
        </div>

        <p className="lab-foot">
          <b>The two gates always read the same.</b> Whatever flows past Gate&nbsp;A flows past Gate&nbsp;B — once the
          loop settles, the charge isn’t consumed on the way, it just circulates. The <b>Flow</b> readout is the
          current itself, <b>I = V ÷ R</b>: more push raises it, a tighter pinch lowers it.
          <span className="fl-note"> The faint glow at the pinch is heat — energy the charges drop there. How much, and the V×I tug-of-war behind it, is Chapter 3.</span>
        </p>
      </div>
    </section>
  );
}

/* ─── Quiz question banks ─────────────────────────────────────────────── */

const ADULT_QUIZ = [
  {
    q: "In the water analogy, what does voltage correspond to?", kind: "concept",
    options: ["The flow rate of water", "The water pressure / push", "The width of the pipe", "The temperature of the water"],
    correct: 1,
    explain: "Voltage is the push — the pressure behind the flow. Flow rate is current; pipe width is resistance.",
  },
  {
    q: "Ohm's law is written V = I × R. Solved for current, that's:", kind: "math",
    options: ["I = V × R", "I = R ÷ V", "I = V ÷ R", "I = V − R"],
    correct: 2,
    explain: "Divide both sides by R: I = V / R. More push or less squeeze both raise the current.",
  },
  {
    q: "You hold resistance fixed and double the voltage. The current…", kind: "math",
    options: ["doubles", "halves", "stays the same", "quadruples"],
    correct: 0,
    explain: "With R fixed, I = V/R is linear in V. Double V → double I.",
  },
  {
    q: "A 12 V source pushes current through a 4 Ω resistor. What's the current?", kind: "math",
    options: ["48 A", "3 A", "0.33 A", "16 A"],
    correct: 1,
    explain: "I = V/R = 12 / 4 = 3 A. (48 would be V×R, a common slip.)",
  },
  {
    q: "Why is current called 'an answer, not a knob'?", kind: "concept",
    options: [
      "Because you can never measure it",
      "Because it's fixed by the wire's color",
      "Because it's whatever voltage and resistance together produce",
      "Because it only exists in water, not wires",
    ],
    correct: 2,
    explain: "You set V (the push) and R (the squeeze). Current is the result: I = V/R. You don't dial it directly.",
  },
  {
    q: "Resistance is measured in…", kind: "concept",
    options: ["volts (V)", "amperes (A)", "ohms (Ω)", "watts (W)"],
    correct: 2,
    explain: "Resistance is in ohms (Ω). Volts measure push, amps measure flow, watts measure power.",
  },
  {
    q: "A 9 V battery drives 3 A through a load. The load's resistance is…", kind: "math",
    options: ["27 Ω", "3 Ω", "12 Ω", "6 Ω"],
    correct: 1,
    explain: "R = V / I = 9 / 3 = 3 Ω.",
  },
  {
    q: "Which change would LOWER the current, with everything else fixed?", kind: "concept",
    options: ["Raise the voltage", "Increase the resistance", "Add a second battery", "Shorten the wire"],
    correct: 1,
    explain: "I = V/R — a bigger squeeze (R) means less flow. Raising V would do the opposite.",
  },
  {
    q: "Where do the charges that flow in a wire come from?", kind: "concept",
    options: [
      "The battery manufactures them and injects them into the wire",
      "They're already in the wire — the battery just pushes them",
      "They come from the air around the wire",
      "They're created by the resistor as it heats up",
    ],
    correct: 1,
    explain: "A wire is packed wall-to-wall with free electrons before you connect anything. The battery doesn't supply charges; it pushes the ones already there, and the whole loop starts shuffling at once.",
  },
  {
    q: "As a charge goes around the loop, what actually gets used up?", kind: "concept",
    options: [
      "The charge itself — electrons are consumed by the bulb",
      "Nothing — circuits don't use anything up",
      "The charge's energy — the charge itself survives and comes back for a refill",
      "The wire, which slowly dissolves",
    ],
    correct: 2,
    explain: "Charge is conserved — the same charges circulate forever. What's spent is the ENERGY each charge carries: delivered to the resistor, then topped up again at the battery.",
  },
  {
    q: "A bigger battery (more voltage) means…", kind: "concept",
    options: [
      "more electrons in the wire",
      "a harder push on the same electrons",
      "faster-moving electrons only, with less current",
      "thicker wire",
    ],
    correct: 1,
    explain: "The number of charges in the wire never changes. A bigger battery pushes the same charges harder — more voltage, not more electrons.",
  },
  {
    q: "Why does a real circuit have to be a closed loop?", kind: "concept",
    options: [
      "So the charges can splash out at the end",
      "It doesn't — a one-way wire works fine",
      "Because charges aren't consumed — they must circulate back to the battery",
      "To keep the wire from overheating",
    ],
    correct: 2,
    explain: "Nothing gets spilled or consumed — the same charges go round and round. Break the loop anywhere and the whole flow stops.",
  },
  {
    q: "A charge leaves the battery 'bright' and returns 'pale.' What faded?", kind: "concept",
    options: [
      "Its electric charge",
      "Its size",
      "Its speed",
      "Its energy — handed to the resistor along the way",
    ],
    correct: 3,
    explain: "Bright = carrying fresh energy from the battery; pale = energy delivered. The charge itself is unchanged — the battery refills it and around it goes again.",
  },
];

const KIDS_QUIZ = [
  {
    q: "Voltage is like… what, in the water world?", kind: "concept",
    options: ["How fast the water flows", "How hard the water pushes", "How wide the pipe is", "How cold the water is"],
    correct: 1,
    explain: "Voltage is the push! A taller barrel pushes harder.",
  },
  {
    q: "What is current?", kind: "concept",
    options: ["How hard it pushes", "How tight the pinch is", "How fast the water actually flows", "The color of the wire"],
    correct: 2,
    explain: "Current is the flow — how much water is actually rushing through.",
  },
  {
    q: "You push HARDER (more voltage) but keep the same pinch. The flow…", kind: "concept",
    options: ["gets bigger", "gets smaller", "stops completely", "stays exactly the same"],
    correct: 0,
    explain: "More push on the same pinch = more flow. Push harder, more comes out!",
  },
  {
    q: "You squeeze the pipe TIGHTER but push the same. The flow…", kind: "concept",
    options: ["gets bigger", "gets smaller", "gets hotter", "turns blue"],
    correct: 1,
    explain: "A tighter pinch lets less through. Tighter squeeze = less flow.",
  },
  {
    q: "What are the three friends from this chapter?", kind: "concept",
    options: [
      "Red, green, and blue",
      "Push (V), flow (I), and squeeze (R)",
      "Hot, cold, and warm",
      "Up, down, and sideways",
    ],
    correct: 1,
    explain: "V is the push, I is the flow, R is the squeeze. Change one and the others follow!",
  },
  {
    q: "Ohms (Ω) measure…", kind: "concept",
    options: ["how hard the push is", "how tight the pinch is", "how fast it flows", "how heavy it is"],
    correct: 1,
    explain: "Ohms tell you how tight the squeeze is. Bigger Ω = tighter pinch = less flow.",
  },
  {
    q: "You can't drag a 'flow' slider directly because flow…", kind: "concept",
    options: ["doesn't exist", "comes FROM the push and the pinch", "is always the same", "is too fast"],
    correct: 1,
    explain: "Flow is the answer! Set the push and the pinch, and the flow comes out of those two.",
  },
  {
    q: "Where do the tiny charges in a wire come from?", kind: "concept",
    options: [
      "The battery makes new ones",
      "They're already inside the wire, waiting",
      "They fall in from the air",
      "You have to pour them in",
    ],
    correct: 1,
    explain: "The wire is already FULL of tiny charges — like a pipe already full of water. The battery just gives them a push!",
  },
  {
    q: "Do the charges get used up as they go around?", kind: "concept",
    options: [
      "Yes — the bulb eats them",
      "No — the same ones go around forever; only their push gets spent",
      "Only the blue ones get used up",
      "Yes — that's why batteries die",
    ],
    correct: 1,
    explain: "The charges never get used up! They hand over their energy, come back tired, and the battery fills them up again.",
  },
  {
    q: "Why does the wire have to make a full loop back to the battery?", kind: "concept",
    options: [
      "So the charges can come back for a refill",
      "To make the wire longer",
      "It doesn't — half a loop works too",
      "To keep the battery warm",
    ],
    correct: 0,
    explain: "The charges go round and round — if you break the loop anywhere, everything stops.",
  },
];

/* ─── App ───────────────────────────────────────────────────────────── */

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "paper",
  "showCircuit": true,
  "audience": "adult"
}/*EDITMODE-END*/;

/* ─── tiny pinch toy for the cover — first interaction in five seconds ── */
function CoverPinchDemo({ kids }) {
  const [r, setR] = useState(3);
  const open = 1 - (r - 0.5) / 11.5;            // 1 wide open … ~0 pinched
  const I = 12 / r;
  const W = 340, py = 46, bh = 16;
  const nh = bh * (0.14 + 0.86 * open);          // half-height of the opening
  const gXa = 130, gXb = 185;
  const reach = 14 + I * 7.5;
  const jetW = 1.5 + I * 0.55;
  return (
    <div className="card" style={{ maxWidth: 420, padding: "16px 20px 14px" }}>
      <div className="eyebrow" style={{ marginBottom: 4 }}>
        {kids ? "try it right now" : "before you scroll — try it"}
      </div>
      <svg viewBox={`0 0 ${W} 96`} width="100%" style={{ display: "block" }} aria-hidden="true">
        {/* water: full before the pinch, gate-level after */}
        <rect x={12} y={py - bh} width={gXa + 18 - 12} height={bh * 2} fill="var(--water)" opacity="0.8" />
        <polygon points={`${gXa + 18},${py - bh} ${gXb - 18},${py + bh - 2 * nh} ${gXb - 18},${py + bh} ${gXa + 18},${py + bh}`}
                 fill="var(--water)" opacity="0.8" />
        <rect x={gXb - 18} y={py + bh - 2 * nh} width={296 - gXb + 18} height={2 * nh} fill="var(--water)" opacity="0.8" />
        {/* pinch wedges */}
        <polygon points={`${gXa},${py - bh} ${gXb},${py - bh} ${(gXa + gXb) / 2},${py + bh - 2 * nh}`}
                 fill="var(--bg-deeper)" stroke="var(--ink)" strokeWidth="2" strokeLinejoin="round" />
        {/* pipe walls */}
        <line x1="12" y1={py - bh} x2="296" y2={py - bh} stroke="var(--ink)" strokeWidth="2.2" />
        <line x1="12" y1={py + bh} x2="296" y2={py + bh} stroke="var(--ink)" strokeWidth="2.2" />
        <line x1="296" y1={py - bh - 1} x2="296" y2={py + bh + 1} stroke="var(--ink)" strokeWidth="2.6" strokeLinecap="round" />
        {/* jet out the end */}
        <path d={`M 296 ${py + bh - nh} Q ${296 + reach * 0.6} ${py + bh - nh + 2}, ${296 + reach} ${py + bh + 26}`}
              fill="none" stroke="var(--water)" strokeWidth={jetW * 2} strokeLinecap="round" opacity="0.85" />
        <text x={(gXa + gXb) / 2} y={py - bh - 8} textAnchor="middle"
              fontFamily="IBM Plex Mono, monospace" fontSize="11" letterSpacing="0.1em" fill="var(--ink-faint)">
          {kids ? "THE SQUEEZE" : "YOUR FIRST RESISTOR"}
        </text>
      </svg>
      <input type="range" className="range" min="0.5" max="12" step="0.1" value={r}
             onChange={(e) => setR(+e.target.value)} style={{ width: "100%" }}
             aria-label="Pinch tightness" />
      <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "IBM Plex Mono, monospace", fontSize: 11, color: "var(--ink-soft)", marginTop: 4 }}>
        <span>{kids ? "← squeeze it" : "← pinch tighter"}</span>
        <span style={{ color: "var(--current-deep)" }}>{kids ? `flow: ${I.toFixed(1)}` : `I = ${I.toFixed(1)} A`}</span>
      </div>
    </div>
  );
}

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useCrossChapterPersistence(t, setTweak);
  useEffect(() => { document.body.setAttribute("data-theme", t.theme); }, [t.theme]);

  const kids = t.audience === "kids";
  const navItems = [
    { id: "cover", label: "Cover" },
    { id: "begin", label: "The map" },
    { id: "voltage", label: "Voltage" },
    { id: "current", label: "Current" },
    { id: "resistance", label: "Resistance" },
    { id: "predict", label: "Predict" },
    { id: "ohms-law", label: kids ? "Three friends" : "Ohm's Law" },
    { id: "playground", label: "Playground" },
    { id: "loop", label: kids ? "The loop" : "The loop" },
    { id: "practice", label: "Practice" },
    { id: "quiz", label: "Quiz" },
    { id: "bench", label: kids ? "Build it!" : "The bench" },
    { id: "whats-next", label: "What's next" },
  ];

  return (
    <>
      <ChapterStartMarker chapterN="01" />
      <ProgressBar />
      <TopBar currentN="01" chapterLabel="Ch. 01 — The Flow"
              audience={t.audience}
              setAudience={(v) => setTweak("audience", v)} />
      <ChapterNav items={navItems} />

      <main>
        <CoverPage chapterN="01"
                   chapterTitle={<>Fath<span style={{ color: "var(--current)" }}>ohm</span>.</>}
                   chapterSub="Chapter 1 · The Flow"
                   kids={kids}
                   lede={kids
                     ? <>Electricity is invisible. Water isn't. So let's start with water — it does almost exactly the same thing, and you can <em>see</em> it happen.</>
                     : <>Before transistors, before computers, before any of the clever stuff — there is a thing that <em>flows</em>, and a thing that <em>pushes</em> it, and a thing that <em>gets in the way</em>. Learn those three and you've cracked the door to electronics.</>
                   }>
          <CoverPinchDemo kids={kids} />
          <div className="marg" style={{ marginTop: 14 }}>
            Scroll, slide, fiddle. You can't break it. (That comes in Chapter 4.)
          </div>
        </CoverPage>

        <LessonScrollyteller showCircuit={t.showCircuit} kids={kids} />

        <LoopSection kids={kids} />

        <CheckpointQuiz kids={kids} label="Loop check" pick={3}
          title={kids ? "Did the loop make sense?" : "Prove the loop, before you move on."}
          questions={[
            {
              q: kids ? "Do the water drops ever get used up as they go around?"
                      : "As a charge goes all the way around the loop, what actually gets used up?",
              options: [
                kids ? "No — they go around forever, only their push gets spent" : "Nothing — the charge itself is conserved; only the energy it carries is spent and refilled",
                kids ? "Yes — the bulb eats a few every lap" : "The charge itself — some electrons are consumed by the resistor",
                kids ? "Yes — they evaporate" : "The wire — it's slowly used up",
                kids ? "The battery — it disappears" : "Nothing is ever spent, anywhere",
              ],
              correct: 0,
              explain: kids ? "The drops go around and around forever! They just get refilled with fresh push at the battery each lap."
                            : "Charge is conserved — the same charges circulate forever. What's spent (and refilled) each lap is the energy each charge carries, not the charge itself.",
            },
            {
              q: kids ? "Why does the pipe have to be a full circle, with no gaps?"
                      : "Why must a working circuit be a closed loop?",
              options: [
                kids ? "So the drops can get back to the pump for a refill" : "Because charge is conserved — it must circulate back to the battery to be recharged, not spill out",
                kids ? "So it looks neat" : "So the wire doesn't get too hot",
                kids ? "It doesn't — any old pipe works" : "It doesn't, actually — an open-ended wire works fine",
                kids ? "To make it longer" : "To increase the resistance",
              ],
              correct: 0,
              explain: kids ? "Nothing spills out! The same drops go round and round — break the loop anywhere and it all stops."
                            : "Nothing is consumed or spilled — the same charges must return to the battery to be recharged. Break the loop anywhere and the whole flow stops instantly.",
            },
            {
              q: kids ? "Inside the pinch, why does the flow slow down and make heat?"
                      : "Physically, what IS resistance — and why does it make heat?",
              options: [
                kids ? "It's packed with tiny bits the drops have to bump past — each bump makes a little heat" : "The material is an ordered lattice of atoms; charges collide with it, and each collision hands over energy as heat",
                kids ? "The pipe gets narrower forever" : "The wire runs out of electrons",
                kids ? "The water gets colder" : "Charge is destroyed on contact",
                kids ? "Nothing — it just happens" : "It's just an empirical rule with no physical cause",
              ],
              correct: 0,
              explain: kids ? "Zoom in and the pinch is full of little atoms! Every bump the drops take on the way through turns into a bit of heat."
                            : "A resistor is a material whose lattice the charges must weave through. Raise R and the lattice packs denser — more collisions, less flow, and every collision sheds energy as heat.",
            },
          ]} />

        <CheckpointQuiz kids={kids} label="Checkpoint 1" pick={2}
          title={kids ? "Quick check!" : "Did it stick?"}
          questions={[
            {
              q: kids ? "Your barrel has drained to half its height. The flow through the pipe…"
                      : "The barrel drains to half its height (half the voltage). The flow through the pipe…",
              options: ["drops to about half", "doubles", "stays exactly the same", "stops completely"],
              correct: 0,
              explain: kids ? "Flow follows push. Half the height means half the push, so half the flow."
                            : "Flow follows push: I = V/R. Halve the height (V) at the same pinch (R) and the flow halves with it.",
            },
            {
              q: "You tighten the pinch but don't touch the barrel. What happens?",
              options: ["Less flow — and the water level after the pinch drops lower", "More flow", "The barrel refills itself", "Nothing at all"],
              correct: 0,
              explain: kids ? "A tighter squeeze lets less water through, and past the squeeze there's less push left — the level sits lower."
                            : "More R at the same V means less I — and the pinch eats more of the push, so the downstream level (remaining voltage) drops.",
            },
            {
              q: "Where is the flow biggest in a single pipe with one pinch in the middle?",
              options: ["It's the same everywhere along the pipe", "Before the pinch", "After the pinch", "Inside the pinch only"],
              correct: 0,
              explain: kids ? "The same water passes every point each second — it can't pile up inside the pipe! Flow is equal all along it."
                            : "Current is the same at every point of a series path — charge can't accumulate in the wire. What changes along the pipe is the push left, not the flow.",
            },
            {
              q: "You want double the flow, but the barrel can't be filled any higher. What do you do?",
              options: ["Open the pinch twice as wide — half the resistance", "Tighten the pinch", "Make the pipe longer", "Wait for the water to speed up on its own"],
              correct: 0,
              explain: kids ? "Same push ÷ half the squeeze = double the flow. The pinch is the other knob you can turn."
                            : "I = V/R has two knobs. If V is stuck, halving R doubles I. (Lengthening the pipe ADDS resistance — wrong direction.)",
            },
          ]} />

        <PracticeProblems
          chapterN="01"
          kids={kids}
          problems={[
            (rng) => {
              const v = rng.int(6, 24, 2), r = rng.pick([2, 3, 4, 5, 6, 8]);
              return {
                q: { adult: `A ${v} V battery drives a ${r} Ω resistor. What current flows?`,
                     kids: `The push is ${v} and the pinch is ${r}. Flow = push ÷ pinch. What's the flow?` },
                unit: "A", answer: +(v / r).toFixed(3), tol: 0.04,
                hint: { adult: "Ohm's law solved for current: I = V ÷ R.",
                        kids: "Divide the push by the pinch." },
                solution: { adult: `I = V ÷ R = ${v} V ÷ ${r} Ω = ${+(v / r).toFixed(2)} A.`,
                            kids: `Flow = ${v} ÷ ${r} = ${+(v / r).toFixed(2)}.` },
              };
            },
            (rng) => {
              const i = rng.pick([1, 2, 2.5, 4, 5]), v = rng.int(10, 30, 5);
              return {
                q: { adult: `What resistance lets exactly ${i} A flow from a ${v} V supply?`,
                     kids: `Push is ${v}, and you want a flow of ${i}. Pinch = push ÷ flow. What pinch?` },
                unit: "Ω", answer: +(v / i).toFixed(3), tol: 0.04,
                hint: { adult: "Rearrange to R = V ÷ I.",
                        kids: "Divide the push by the flow you want." },
                solution: { adult: `R = V ÷ I = ${v} V ÷ ${i} A = ${+(v / i).toFixed(2)} Ω.`,
                            kids: `Pinch = ${v} ÷ ${i} = ${+(v / i).toFixed(2)}.` },
              };
            },
            (rng) => {
              const i = rng.pick([0.25, 0.5, 0.75, 1.5, 2]), r = rng.int(4, 18, 2);
              return {
                q: { adult: `How much voltage sits across a ${r} Ω resistor carrying ${i} A?`,
                     kids: `Flow is ${i} through a pinch of ${r}. Push = flow × pinch. What push?` },
                unit: "V", answer: +(i * r).toFixed(3), tol: 0.04,
                hint: { adult: "Ohm's law in its original form: V = I × R.",
                        kids: "Multiply the flow by the pinch." },
                solution: { adult: `V = I × R = ${i} A × ${r} Ω = ${+(i * r).toFixed(2)} V.`,
                            kids: `Push = ${i} × ${r} = ${+(i * r).toFixed(2)}.` },
              };
            },
          ]}
        />

        <CheckpointQuiz kids={kids} label="Checkpoint 2" pick={2}
          title={kids ? "Spot it in real life!" : "Out in the wild."}
          intro={kids ? "Same ideas — hiding in things around your house." : "The same law, dressed in everyday clothes."}
          questions={[
            {
              q: "A flashlight slowly dims as its battery runs down. In water terms, what's happening?",
              options: ["The barrel's level is dropping — less push, so less flow through the bulb", "The pipe is getting longer", "The bulb is drinking up the electricity", "The pinch is loosening"],
              correct: 0,
              explain: kids ? "A tired battery is a barrel running low. Less height, less push, less flow — so the bulb gets dim."
                            : "A depleting battery sags in voltage. Same bulb resistance, lower V → lower I → dimmer filament. Pure Ohm's law.",
            },
            {
              q: "A lamp dimmer knob works like…",
              options: ["a pinch you tighten and loosen", "a taller barrel", "a second barrel", "a wider pipe that never changes"],
              correct: 0,
              explain: kids ? "Turning the knob squeezes the pipe tighter or looser — less or more flow to the bulb."
                            : "A dimmer varies resistance (or its modern equivalent), throttling current to the bulb — a hand-adjustable pinch.",
            },
            {
              q: "Your car cranks weakly on a freezing morning. The water version?",
              options: ["Cold shrinks the barrel's push — lower level, weaker flow to the starter", "The pipes froze solid — zero flow ever", "The starter became thirstier overnight", "Cold water flows faster"],
              correct: 0,
              explain: kids ? "Cold makes the battery push weaker — like a barrel that's lost some height. The starter motor only gets a dribble."
                            : "Cold chemistry can't hold the terminal voltage under load — the push sags, so the starter draws less current than it needs.",
            },
            {
              q: "A reading lamp and a tiny night-light plug into the SAME outlet — same push. Why does the night-light glow dimmer?",
              options: ["It has a much tighter pinch inside — more resistance, so less flow", "The outlet gives it less push", "Electricity prefers bigger bulbs", "Its wires are longer"],
              correct: 0,
              explain: kids ? "Same push for both! The night-light is built with a tighter squeeze, so it sips a tiny flow on purpose."
                            : "Both see the same mains voltage. The night-light's element has far higher resistance, so it draws far less current — by design.",
            },
          ]} />

        <ChapterQuiz
          chapterN="01"
          title={kids ? "Quick quiz!" : "Check your understanding."}
          intro={kids
            ? "Five quick questions. Don't worry — you can try as many times as you like."
            : "Five questions on Ohm's law and the water analogy. 70% to pass; retry as often as you like."}
          questions={kids ? KIDS_QUIZ : ADULT_QUIZ}
          pick={5}
        />

        <WhatsNext
          currentN="01"
          kids={kids}
          summary={kids
            ? <>You know how electricity works. Most grown-ups don't even know this!</>
            : <>You now know more about electricity than 95% of the people who flip a light switch today. Next: two resistors instead of one.</>
          }
          nextHref="chapter2.html"
          nextLabel="Chapter 2 · Branching"
        />
      </main>

      <TweaksPanel title="Tweaks">
        <CommonTweaks t={t} setTweak={setTweak}
          animationToggles={[{ key: "showCircuit", label: "Show circuit" }]} />
      </TweaksPanel>
      <GlossaryFab />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
