/* chapter2.jsx — Chapter 2: Series & Parallel
   Same scrollytelling structure as chapter 1, with topology-switching visuals.
   Helpers (fmt, useInViewCallback, Slider, ProgressBar, TopBar, ChapterNav,
   CommonTweaks, useCrossChapterPersistence) come from shared.jsx via window. */

const { useState, useEffect, useRef } = React;

/* ─── Beats ─────────────────────────────────────────────────────────────── */

function BigIdeaBeat({ onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="big-idea" data-screen-label="02 The two shapes" ref={ref}>
      <div className="beat-marker">§ 02 · the two shapes</div>
      {kids ? (
        <>
          <h2 className="serif">Same parts. <em>Different shape</em>.</h2>
          <p className="lede">
            Imagine two pinches in a pipe. You can put them <em>one after
            the other</em>, or <em>side by side</em>. The flow turns out
            very different.
          </p>
        </>
      ) : (
        <>
          <h2 className="serif">Same parts, <em>different shape</em>.</h2>
          <p className="lede">
            Take two resistors. You can string them like beads on a thread —
            <em>series</em>. Or branch them like a fork in the road —
            <em>parallel</em>. The math is different, and the <em>behavior</em> is wildly different.
          </p>
        </>
      )}
      <div className="pull">
        Series adds up. Parallel splits apart.
      </div>

      <div style={{ marginTop: 26, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <div className="card" style={{ background: "transparent", padding: "20px" }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Series · one road</div>
          <div className="serif" style={{ fontSize: 22, fontStyle: "italic", lineHeight: 1.2 }}>
            Same flow. <em>Different</em> push at each pinch.
          </div>
          <div className="marg" style={{ marginTop: 10 }}>
            Resistances <em>add</em>: R = R₁ + R₂
          </div>
        </div>
        <div className="card" style={{ background: "transparent", padding: "20px" }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>Parallel · two roads</div>
          <div className="serif" style={{ fontSize: 22, fontStyle: "italic", lineHeight: 1.2 }}>
            Same push. <em>Different</em> flow in each branch.
          </div>
          <div className="marg" style={{ marginTop: 10 }}>
            Currents <em>add</em>: I = I₁ + I₂
          </div>
        </div>
      </div>

      <div className="card" style={{ marginTop: 18, background: "transparent", borderColor: "var(--rule)" }}>
        <div className="eyebrow" style={{ marginBottom: 8 }}>a note on labels</div>
        <p style={{ margin: 0, fontSize: 15.5, color: "var(--ink-soft)" }}>
          {kids
            ? <>From here on you'll see little numbers, like <span className="mono">R₁</span> and <span className="mono">R₂</span>. When there are two of the same part, we give each a tiny number to tell them apart — <span className="mono">R₁</span> is the first pinch, <span className="mono">R₂</span> the second. The flow through each gets a matching tag: <span className="mono">I₁</span>, <span className="mono">I₂</span>. That's all the little number means — a name tag.</>
            : <>One quick convention before we dig in: when a circuit has more than one of the same part, we tag each with a small subscript number. <span className="mono">R₁</span> and <span className="mono">R₂</span> are simply the first and second resistor; <span className="mono">I₁</span> and <span className="mono">I₂</span> are the current flowing through each. Nothing mathematical — just a way to keep two of the same thing straight.</>}
        </p>
      </div>

      {!kids && (
        <p className="note" style={{ marginTop: 24 }}>
          Real circuits mix and match. We'll learn both rules and use them
          for the rest of the series.
        </p>
      )}
    </div>
  );
}

function SeriesBeat({ v, r1, r2, setR1, setR2, onView, kids }) {
  const ref = useInViewCallback(onView);
  const I = v / (r1 + r2);
  return (
    <div className="beat" id="series" data-screen-label="03 Series" ref={ref}>
      <div className="beat-marker">§ 03 · one road · series</div>
      <div className="chip" style={{ marginBottom: 16, color: "var(--water)", borderColor: "var(--water)" }}>SERIES</div>
      <h2 className="serif">One pipe.<br/><em>Two pinches</em>.</h2>
      {kids ? (
        <>
          <p className="lede">
            Put two pinches in the <em>same pipe</em>, one after the other. The
            water has to squeeze through <em>both</em>.
          </p>
          <p>
            All the water goes through all the pinches — so the flow is the same
            everywhere. Right now it's <span className="mono" style={{ color: "var(--current)" }}>{fmt(I, 2)} A</span>.
          </p>
          <p>
            Each pinch uses up a little of the push as the water squeezes
            through. So the barrel's push gets <em>shared</em> between the two
            pinches — by the end of the pipe, it's all been spent.
          </p>
          <p>
            Tighten <em>either</em> pinch and the whole flow slows down.
          </p>
        </>
      ) : (
        <>
          <p className="lede">
            Drop two resistors into a single loop, one after another — two
            pinches in the <em>same</em> pipe.
          </p>
          <p>
            Picture the water reaching the first pinch, squeezing through, then
            running straight into the second. Whatever gets through one <em>must</em> get through the other — there's nowhere else to go, and
            water can't pile up in the pipe. So the <em>flow is identical</em> at
            every point in the loop.
          </p>
          <p>
            But each pinch <em>costs</em> push. The water spends some of its
            pressure forcing through the first narrowing, then more through the
            second — and by the time it loops back, the whole push has been used
            up, divided between the two. Two narrowings in a row are also harder
            to pass than either one alone, so the shared flow runs <em>slower</em> than it would with a single pinch.
          </p>
          <p>
            Put plainly: the resistances simply <em>add</em>.
          </p>
          <div className="eq" style={{ fontSize: 36, margin: "14px 0 20px" }}>
            <span className="R">R<sub style={{ fontSize: "0.55em" }}>total</sub></span>
            <span className="op">=</span>
            <span className="R">R<sub style={{ fontSize: "0.55em" }}>1</sub></span>
            <span className="op">+</span>
            <span className="R">R<sub style={{ fontSize: "0.55em" }}>2</sub></span>
          </div>
          <EqEase kids={kids} />
          <p>
            And the flow follows Ohm's law as before, just with the bigger total
            resistance:
          </p>
          <div className="card" style={{ background: "transparent", padding: "14px 18px", marginTop: 8 }}>
            <div className="eq" style={{ fontSize: 24 }}>
              <span className="I">I</span><span className="op">=</span>
              <span className="frac">
                <span className="V">V</span>
                <span className="bar"></span>
                <span>R₁ + R₂</span>
              </span>
              <span className="op" style={{ marginLeft: 18 }}>=</span>
              <span className="num">{fmt(I, 2)}</span>
              <span className="op" style={{ fontSize: 16 }}>A</span>
            </div>
          </div>
        </>
      )}

      <div className="rule">try it · adjust each pinch</div>
      <Slider name="R₁ · first pinch" value={r1} min={0.5} max={10} step={0.1}
              unit="Ω" accent="" onChange={setR1} />
      <Slider name="R₂ · second pinch" value={r2} min={0.5} max={10} step={0.1}
              unit="Ω" accent="" onChange={setR2} />
      <div className="branch-readout">
        <span>same flow everywhere</span>
        <span className="mono">I = {fmt(v,1)}V ÷ ({fmt(r1,1)}+{fmt(r2,1)})Ω = <b style={{ color: "var(--current)" }}>{fmt(I, 2)} A</b></span>
      </div>
      {!kids && (
        <div className="branch-readout">
          <span>push used at each pinch</span>
          <span className="mono">V₁ = {fmt(I*r1,1)}V · V₂ = {fmt(I*r2,1)}V <span style={{ color: "var(--ink-faint)" }}>(adds to {fmt(v,1)}V)</span></span>
        </div>
      )}
      <div className="marg" style={{ marginTop: 12 }}>
        {kids
          ? "See the water level step down at each pinch? That's the push being used up. The bulb is dim if either pinch is tight — both pinches matter."
          : <>Each resistor uses up — <em>“drops”</em> — part of the push; the two drops always add back to the full {fmt(v,1)} V. Watch the water level in the pipe step down at each pinch (the <span className="mono">% push left</span> labels) — the bigger pinch takes the bigger step. The flow itself stays the same all the way round.</>}
      </div>
      <div className="card" style={{ background: "transparent", padding: "18px 20px 8px", marginTop: 16 }}>
        <div className="eyebrow" style={{ marginBottom: 4 }}>{kids ? "why it's called a “drop”" : "why engineers say a resistor “drops” voltage"}</div>
        <p style={{ margin: "0 0 4px", fontSize: 15, color: "var(--ink-soft)" }}>
          {kids
            ? <>Think of the pinches as <em>waterfalls</em>. In series, one stream tumbles over two falls in a row — the two falls stack up to the whole cliff.</>
            : <>Make height literal: <em>voltage is the cliff</em>. In series one stream goes over two falls in a row — same stream (same <span className="mono">I</span>), and the two fall heights stack to the full cliff. Your sliders move the ledge.</>}
        </p>
        <WaterfallScene v={v} r1={r1} r2={r2} topology="series" kids={kids} />
      </div>
      <div className="card" style={{ background: "transparent", padding: "14px 18px", marginTop: 16, borderColor: "var(--current-soft)" }}>
        <div className="eyebrow" style={{ marginBottom: 6, color: "var(--current)" }}>{kids ? "the rule to remember" : "rule of thumb"}</div>
        <p style={{ margin: 0, fontSize: 16 }}>
          {kids
            ? <>More pinch = less flow. <strong>Every</strong> time. Tighten either pinch and the whole loop slows down.</>
            : <>In series, every ohm you add slows the <em>whole</em> loop: <span className="mono">resistance up → current down</span>. Drag either slider up and watch <span className="mono">I</span> fall — it never goes the other way.</>}
        </p>
      </div>
    </div>
  );
}

function ParallelBeat({ v, r1, r2, setR1, setR2, onView, kids }) {
  const ref = useInViewCallback(onView);
  const I1 = v / r1, I2 = v / r2, Itot = I1 + I2;
  return (
    <div className="beat" id="parallel" data-screen-label="04 Parallel" ref={ref}>
      <div className="beat-marker">§ 04 · two roads · parallel</div>
      <div className="chip" style={{ marginBottom: 16, color: "var(--current)", borderColor: "var(--current)" }}>PARALLEL</div>
      <h2 className="serif">Two pipes.<br/><em>Same push</em>.</h2>
      {kids ? (
        <>
          <p className="lede">
            Now split the pipe into two. Each branch has its own pinch and its
            own flow.
          </p>
          <p>
            Each branch gets the <em>full</em> push from the barrel — they don't
            share. Right now branch 1 has <span className="mono" style={{ color: "var(--current)" }}>{fmt(I1, 2)} A</span>,
            branch 2 has <span className="mono" style={{ color: "var(--current)" }}>{fmt(I2, 2)} A</span>,
            and the total coming out is <span className="mono">{fmt(Itot, 2)} A</span>.
          </p>
          <p>
            If you close one branch (huge pinch), the other branch <em>keeps
            going</em>. Pretty clever, right?
          </p>
        </>
      ) : (
        <>
          <p className="lede">
            Now fork the pipe: the water reaches a junction and can take <em>either</em> branch.
          </p>
          <p>
            Both branches start and end at the same two points, so each one
            feels the <em>same</em> full pressure from the barrel — they don't
            share the push the way two pinches in a line do. What differs is the <em>flow</em>: a loose branch lets plenty through, a tight one only a
            trickle. Add up what each branch carries and you get the total
            leaving the barrel — so the currents <em>add</em>:
          </p>
          <div className="eq" style={{ fontSize: 30, margin: "14px 0 20px" }}>
            <span className="I">I<sub style={{ fontSize: "0.55em" }}>total</sub></span>
            <span className="op">=</span>
            <span className="I">I<sub style={{ fontSize: "0.55em" }}>1</sub></span>
            <span className="op">+</span>
            <span className="I">I<sub style={{ fontSize: "0.55em" }}>2</sub></span>
            <span className="op" style={{ marginLeft: 8 }}>=</span>
            <span className="frac">
              <span className="V">V</span>
              <span className="bar"></span>
              <span>R₁</span>
            </span>
            <span className="op">+</span>
            <span className="frac">
              <span className="V">V</span>
              <span className="bar"></span>
              <span>R₂</span>
            </span>
          </div>
          <p>
            Here's the twist — opening a second branch doesn't change the first
            one at all, yet <em>more</em> total water now flows. More lanes means
            easier passage, so the combined resistance is <em>less</em> than
            either branch alone:
          </p>
          <div className="eq" style={{ fontSize: 26, margin: "10px 0" }}>
            <span className="frac">
              <span>1</span>
              <span className="bar"></span>
              <span className="R">R<sub style={{ fontSize: "0.55em" }}>total</sub></span>
            </span>
            <span className="op">=</span>
            <span className="frac">
              <span>1</span>
              <span className="bar"></span>
              <span>R₁</span>
            </span>
            <span className="op">+</span>
            <span className="frac">
              <span>1</span>
              <span className="bar"></span>
              <span>R₂</span>
            </span>
          </div>
          <div className="marg" style={{ marginTop: 4 }}>
            For <em>two</em> resistors this is the same as the tidy
            <span className="mono"> R = (R₁·R₂) ÷ (R₁+R₂)</span> shortcut you'll see in
            the rules below — just rearranged.
          </div>
          <div className="marg" style={{ marginTop: 12 }}>
            If a branch opens (a bulb burns out), only that branch dies. The
            others keep going. This is why your house's lights are wired in
            parallel — and why old-style Christmas lights, wired in series,{" "}
            <em>all</em> went dark when one bulb died.
          </div>
        </>
      )}
      <div className="card" style={{ background: "transparent", padding: "18px 20px 8px", marginTop: 20 }}>
        <div className="eyebrow" style={{ marginBottom: 4 }}>{kids ? "the waterfall, again" : "the waterfall picture, flipped"}</div>
        <p style={{ margin: "0 0 4px", fontSize: 15, color: "var(--ink-soft)" }}>
          {kids
            ? <>Now the two falls sit <em>side by side</em> off the same cliff. Each one falls the whole way down — and the two streams add up.</>
            : <>Same cliff, two spouts. Each branch falls the <em>full</em> height (full <span className="mono">V</span> across each) — what adds now is the <em>water</em>, not the height. Series stacks falls; parallel stacks streams.</>}
        </p>
        <WaterfallScene v={v} r1={r1} r2={r2} topology="parallel" kids={kids} />
      </div>

      <div className="rule">try it · each branch is independent</div>
      <Slider name="R₁ · top branch" value={r1} min={0.5} max={10} step={0.1}
              unit="Ω" accent="" onChange={setR1} />
      <div className="branch-readout">
        <span>branch 1 flow</span>
        <span className="mono">I₁ = {fmt(v,1)}V ÷ {fmt(r1,1)}Ω = <b style={{ color: "var(--current)" }}>{fmt(I1, 2)} A</b></span>
      </div>
      <Slider name="R₂ · bottom branch" value={r2} min={0.5} max={10} step={0.1}
              unit="Ω" accent="" onChange={setR2} />
      <div className="branch-readout">
        <span>branch 2 flow</span>
        <span className="mono">I₂ = {fmt(v,1)}V ÷ {fmt(r2,1)}Ω = <b style={{ color: "var(--current)" }}>{fmt(I2, 2)} A</b></span>
      </div>

      <div className="total-calc">
        <div className="eyebrow" style={{ marginBottom: 8 }}>{kids ? "add the branches" : "total current, live"}</div>
        <div className="eq" style={{ fontSize: 22, flexWrap: "wrap" }}>
          <span className="I">I<sub style={{ fontSize: "0.55em" }}>total</sub></span>
          <span className="op">=</span>
          <span className="I">{fmt(I1, 2)}</span>
          <span className="op">+</span>
          <span className="I">{fmt(I2, 2)}</span>
          <span className="op">=</span>
          <span style={{ color: "var(--current)", fontWeight: 600 }}>{fmt(Itot, 2)}</span>
          <span className="op" style={{ fontSize: 14 }}>A</span>
        </div>
        <div className="marg" style={{ marginTop: 6 }}>
          {kids ? "Both branches pour into the same exit — so their flows add up."
                : "Each branch's current adds into the shared return path. Change either R and watch the total track it."}
        </div>
      </div>
      <div className="card" style={{ background: "transparent", padding: "14px 18px", marginTop: 16, borderColor: "var(--current-soft)" }}>
        <div className="eyebrow" style={{ marginBottom: 6, color: "var(--current)" }}>{kids ? "the rule to remember" : "rule of thumb"}</div>
        <p style={{ margin: 0, fontSize: 16 }}>
          {kids
            ? <>Inside each branch it's the same old rule — more pinch, less flow. But <strong>adding</strong> a branch is a new road for the water, so the <strong>total</strong> flow goes UP!</>
            : <>Within any one branch, the rule holds: <span className="mono">resistance up → current down</span>. But <em>adding</em> a branch lowers the <em>total</em> resistance — more roads → more total flow. Same law, opposite feel.</>}
        </p>
      </div>
    </div>
  );
}

function PredictBeatCh2({ onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="predict" data-screen-label="05 Predict" ref={ref}>
      <div className="beat-marker">§ 04½ · check your gut</div>
      <h2 className="serif">Two bulbs.<br/><em>Which is brighter?</em></h2>
      <p className="lede">
        Same battery, same two resistors. Wired one way vs. the other.
        What does your gut say?
      </p>

      <PredictReveal
        question={kids
          ? "You wire two same-sized resistors in SERIES. Then the same two in PARALLEL. Which arrangement has MORE total flow?"
          : "Two equal resistors, same battery, series vs parallel. Which configuration draws more total current?"
        }
        options={[
          "Series — flow piles up through both",
          "Parallel — two paths means easier flow",
          "Same — same parts, same current",
          "Depends on which resistor",
        ]}
        correct={1}
        explanation={kids
          ? "Parallel gives the water two roads to take instead of one. More road = more water gets through. Series makes the water cross two pinches in a row — slower."
          : "Two R-ohm resistors in series → 2R total. Same two in parallel → R/2 total. Parallel total resistance is one-fourth of series, so parallel current is 4× the series current with equal-R parts."
        }
        accent="current"
      />

      <PredictReveal
        question={kids
          ? "You have a string of 4 bulbs wired in SERIES. One bulb burns out. What happens to the others?"
          : "Four bulbs in series. One filament breaks (open circuit). The others?"
        }
        options={[
          "They burn brighter to compensate",
          "Three stay on, one is dark",
          "All four go dark",
          "They flicker randomly",
        ]}
        correct={2}
        explanation={kids
          ? "Series is a single loop. Break it anywhere and the whole flow stops. That's why old Christmas lights all died together when one bulb went bad."
          : "In a series loop there's exactly one path for current. Break it and I = 0 everywhere. Hence the misery of pre-1970s Christmas lights. Modern strings use parallel branches so one dead bulb doesn't kill the rest."
        }
        accent="water"
      />
    </div>
  );
}

function RulesBeat({ v, r1, r2, onView, kids }) {
  const ref = useInViewCallback(onView);
  const I_s = v / (r1 + r2);
  const I_p = v / r1 + v / r2;
  if (kids) {
    return (
      <div className="beat" id="rules" data-screen-label="05 Two rules" ref={ref}>
        <div className="beat-marker">§ 05 · two rules to remember</div>
        <h2 className="serif">Two rules,<br/>and you're done.</h2>
        <p className="lede">
          Both shapes use the same V, I, and R from Chapter 1. Just two new
          rules tell you how things combine.
        </p>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginTop: 24 }}>
          <div className="card" style={{ background: "transparent", padding: "20px" }}>
            <div className="eyebrow" style={{ marginBottom: 12, color: "var(--water)" }}>Series · one road</div>
            <p style={{ margin: 0, fontSize: 17 }}>
              Same <em>flow</em> through everything.<br/>
              Push <em>splits up</em> across the pinches.<br/>
              Squeezes <em>add</em>.
            </p>
          </div>
          <div className="card" style={{ background: "transparent", padding: "20px" }}>
            <div className="eyebrow" style={{ marginBottom: 12, color: "var(--current)" }}>Parallel · two roads</div>
            <p style={{ margin: 0, fontSize: 17 }}>
              Same <em>push</em> across each branch.<br/>
              Flow <em>splits up</em> between branches.<br/>
              Flows <em>add</em>.
            </p>
          </div>
        </div>
        <div className="card" style={{ background: "transparent", marginTop: 24, padding: "18px 20px" }}>
          <div className="eyebrow" style={{ marginBottom: 10 }}>same V & Rs · different totals</div>
          <p style={{ margin: 0, fontSize: 18 }}>
            With <span className="mono" style={{ color: "var(--water)" }}>{fmt(v, 1)} V</span>,
            <span className="mono"> R₁={fmt(r1, 1)}Ω</span>, <span className="mono">R₂={fmt(r2, 1)}Ω</span>:
          </p>
          <p style={{ marginTop: 10, fontSize: 17 }}>
            <em>Series</em> total flow: <span className="mono" style={{ color: "var(--current)" }}>{fmt(I_s, 2)} A</span><br/>
            <em>Parallel</em> total flow: <span className="mono" style={{ color: "var(--current)" }}>{fmt(I_p, 2)} A</span>
          </p>
          <p style={{ marginTop: 10, color: "var(--ink-soft)" }}>
            Same parts. <em>Way</em> different result.
          </p>
        </div>
      </div>
    );
  }
  return (
    <div className="beat" id="rules" data-screen-label="05 The rules" ref={ref}>
      <div className="beat-marker">§ 05 · the rules</div>
      <h2 className="serif">Two shapes, <em>two rules</em>.</h2>
      <p className="lede">
        These two relationships will follow you through every circuit you ever
        analyze. Memorize them once — they don't change.
      </p>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 26 }}>
        <div className="card" style={{ background: "transparent", padding: "22px" }}>
          <div className="eyebrow" style={{ marginBottom: 14, color: "var(--water)" }}>Series</div>
          <div className="eq" style={{ fontSize: 28 }}>
            <span className="R">R</span>
            <span className="op">=</span>
            <span className="R">R₁</span>
            <span className="op">+</span>
            <span className="R">R₂</span>
          </div>
          <div className="marg" style={{ marginTop: 14 }}>
            Resistances add. Same current everywhere. Voltage divides
            across each resistor in proportion to its R.
          </div>
        </div>
        <div className="card" style={{ background: "transparent", padding: "22px" }}>
          <div className="eyebrow" style={{ marginBottom: 14, color: "var(--current)" }}>Parallel</div>
          <div className="eq" style={{ fontSize: 24 }}>
            <span className="frac">
              <span>1</span>
              <span className="bar"></span>
              <span className="R">R</span>
            </span>
            <span className="op">=</span>
            <span className="frac">
              <span>1</span>
              <span className="bar"></span>
              <span>R₁</span>
            </span>
            <span className="op">+</span>
            <span className="frac">
              <span>1</span>
              <span className="bar"></span>
              <span>R₂</span>
            </span>
          </div>
          <div className="marg" style={{ marginTop: 14 }}>
            Currents add. Same voltage across each branch. Total resistance
            is <em>less</em> than the smallest single branch.
          </div>
          <div style={{ marginTop: 14, paddingTop: 12, borderTop: "1px dotted var(--rule)" }}>
            <div className="eyebrow" style={{ marginBottom: 8 }}>handy shortcut · two resistors</div>
            <div className="eq" style={{ fontSize: 20 }}>
              <span className="R">R</span>
              <span className="op">=</span>
              <span className="frac">
                <span>R₁ · R₂</span>
                <span className="bar"></span>
                <span>R₁ + R₂</span>
              </span>
            </div>
            <div className="marg" style={{ marginTop: 8 }}>
              Same rule as above, just solved for R — and <em>only</em> for two resistors at
              a time. Two <em>equal</em> ones → exactly <em>half</em>:
              <span className="mono"> 6 Ω ∥ 6 Ω = 36 ÷ 12 = 3 Ω</span>.
            </div>
          </div>
        </div>
      </div>

      <div className="card" style={{ background: "transparent", marginTop: 28, padding: "20px 22px" }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>same parts, different totals</div>
        <div className="eq" style={{ fontSize: 22 }}>
          <span style={{ color: "var(--ink-soft)" }}>series:</span>
          <span className="num" style={{ color: "var(--current)", marginLeft: 14 }}>{fmt(I_s, 2)}</span>
          <span className="op" style={{ fontSize: 14 }}>A</span>
          <span className="op" style={{ marginLeft: 28 }}>·</span>
          <span style={{ color: "var(--ink-soft)" }}>parallel:</span>
          <span className="num" style={{ color: "var(--current)", marginLeft: 14 }}>{fmt(I_p, 2)}</span>
          <span className="op" style={{ fontSize: 14 }}>A</span>
        </div>
        <div className="marg" style={{ marginTop: 10 }}>
          V = {fmt(v, 1)} V, R₁ = {fmt(r1, 1)} Ω, R₂ = {fmt(r2, 1)} Ω. Same components,
          dramatically different flow.
        </div>
      </div>
    </div>
  );
}

function PlaygroundBeat({ v, setV, r1, setR1, r2, setR2, topology, setTopology, onView, kids }) {
  const ref = useInViewCallback(onView);
  const I_s = v / (r1 + r2);
  const I_p = v / r1 + v / r2;
  const I = topology === "series" ? I_s : I_p;
  const tone = useToneFollow();
  const idle = React.useRef(null);
  // hear the current — parallel will sing higher than series for the same parts
  const sing = (nv, nr1, nr2, topo) => {
    const cur = topo === "series" ? nv / (nr1 + nr2) : nv / nr1 + nv / nr2;
    tone.set(Math.min(1, cur / 24), Math.min(1, cur / 12));
    if (idle.current) clearTimeout(idle.current);
    idle.current = setTimeout(() => tone.stop(), 300);
  };
  const onV = (x) => { setV(x); sing(x, r1, r2, topology); };
  const onR1 = (x) => { setR1(x); sing(v, x, r2, topology); };
  const onR2 = (x) => { setR2(x); sing(v, r1, x, topology); };
  const onTopo = (t) => { setTopology(t); sing(v, r1, r2, t); };
  return (
    <div className="beat" id="playground" data-screen-label="06 Playground" ref={ref}>
      <div className="beat-marker">§ 06 · all knobs unlocked</div>
      <h2 className="serif">Pick your <em>shape</em>.</h2>
      <p className="lede">
        {kids
          ? <>Flip between the two and see what happens. Same parts. Different shape.</>
          : <>Toggle topology, drag the sliders. The visualizations on the right reconfigure.</>
        }
      </p>
      <SonifyHint text="Sound's on — flip series↔parallel and listen: parallel sings higher (more current)." />

      <div style={{ marginTop: 22, display: "flex", gap: 8 }}>
        {[
          { value: "series",   label: "Series" },
          { value: "parallel", label: "Parallel" },
        ].map(o => (
          <button key={o.value} onClick={() => onTopo(o.value)}
                  style={{
                    appearance: "none",
                    border: `1.5px solid ${topology === o.value ? "var(--current)" : "var(--rule-strong)"}`,
                    background: topology === o.value ? "var(--current)" : "transparent",
                    color: topology === o.value ? "var(--bg-card)" : "var(--ink)",
                    padding: "10px 22px",
                    borderRadius: 999,
                    fontFamily: "'IBM Plex Mono', monospace",
                    fontSize: 12,
                    letterSpacing: "0.14em",
                    textTransform: "uppercase",
                    cursor: "pointer",
                    fontWeight: 500,
                  }}>
            {o.label}
          </button>
        ))}
      </div>

      <div style={{ marginTop: 26, 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="R₁ · first" value={r1} min={0.5} max={10} step={0.1}
                unit="Ω" accent="" onChange={onR1} />
        <Slider name="R₂ · second" value={r2} min={0.5} max={10} step={0.1}
                unit="Ω" accent="" onChange={onR2} />
      </div>

      <div className="card" style={{ background: "transparent", marginTop: 22, padding: "18px 20px" }}>
        <div className="eyebrow" style={{ marginBottom: 10 }}>
          {kids ? "right now" : `${topology === "series" ? "series" : "parallel"} · total flow`}
        </div>
        {kids ? (
          <p style={{ margin: 0, fontSize: 18 }}>
            <span className="mono" style={{ color: "var(--current)" }}>{fmt(I, 2)} A</span> flowing.
            That's <span className="mono">{fmt(v * I, 1)} W</span> of glow.
          </p>
        ) : topology === "parallel" ? (
          <>
            <div className="eq" style={{ fontSize: 22, flexWrap: "wrap" }}>
              <span className="I">I</span><span className="op">=</span>
              <span style={{ fontSize: 15 }}>{fmt(v,1)}÷{fmt(r1,1)}</span>
              <span className="op">+</span>
              <span style={{ fontSize: 15 }}>{fmt(v,1)}÷{fmt(r2,1)}</span>
              <span className="op">=</span>
              <span className="num" style={{ color: "var(--current)" }}>{fmt(I, 2)}</span>
              <span className="op" style={{ fontSize: 14 }}>A</span>
            </div>
            <div className="marg" style={{ marginTop: 6 }}>
              I₁ ({fmt(v/r1,2)} A) + I₂ ({fmt(v/r2,2)} A) · P = {fmt(v*I,1)} W
            </div>
          </>
        ) : (
          <>
            <div className="eq" style={{ fontSize: 22, flexWrap: "wrap" }}>
              <span className="I">I</span><span className="op">=</span>
              <span style={{ fontSize: 15 }}>{fmt(v,1)} ÷ ({fmt(r1,1)}+{fmt(r2,1)})</span>
              <span className="op">=</span>
              <span className="num" style={{ color: "var(--current)" }}>{fmt(I, 2)}</span>
              <span className="op" style={{ fontSize: 14 }}>A</span>
            </div>
            <div className="marg" style={{ marginTop: 6 }}>
              Series: resistances add → R = {fmt(r1+r2,1)} Ω · P = {fmt(v*I,1)} W
            </div>
          </>
        )}
      </div>

      <div className="rule">presets</div>
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
        {[
          { label: "Equal pinches", v: 9, r1: 3, r2: 3 },
          { label: "Wildly different", v: 9, r1: 1, r2: 9 },
          { label: "One open (∞ pinch)", v: 9, r1: 3, r2: 10 },
          { label: "Both wide", v: 9, r1: 0.5, r2: 0.5 },
        ].map(p => (
          <button key={p.label}
                  onClick={() => { setV(p.v); setR1(p.r1); setR2(p.r2); }}
                  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>
  );
}

/* ─── Sticky visuals — switches topology by mode ──────────────────────── */
function StickyVisuals({ v, r1, r2, topology, showCircuit, visHeight, kids }) {
  return (
    <>
      <div className="vis-block">
        <div className="stage-label">
          WATER · {topology === "series" ? "two pinches in line" : "two branches in parallel"}
        </div>
        {topology === "series"
          ? <SeriesWater voltage={v} r1={r1} r2={r2} height={visHeight} />
          : <ParallelWater voltage={v} r1={r1} r2={r2} height={visHeight} />}
      </div>
      {showCircuit && (
        <div className="vis-block">
          <div className="stage-label">
            THE LOOP · {topology === "series" ? "charge through two pinches" : "charge splits, then rejoins"}
          </div>
          <LoopScene2 v={v} r1={r1} r2={r2} topology={topology} kids={kids} height={visHeight} />
        </div>
      )}
    </>
  );
}

/* ─── LessonScrollyteller ─────────────────────────────────────────────── */
/* readout strip under a section's visual — computed for that section's topology */
function VisReadout({ v, r1, r2, topology, kids }) {
  const Itot = topology === "series" ? v / (r1 + r2) : (v / r1 + v / r2);
  const Req = topology === "series" ? (r1 + r2) : (r1 * r2) / (r1 + r2);
  const P = v * Itot;
  return (
    <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">{topology === "series" ? "R total · series" : "R total · parallel"}</span>
        <span className="ro-val">{fmt(Req, 1)}<span className="ro-unit">Ω</span></span>
      </div>
      <div className="ro-i">
        <span className="ro-name">{kids ? "Flow" : "Total I"}</span>
        <span className="ro-val">{fmt(Itot, 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>
  );
}

/* ─── LessonScrollyteller ─────────────────────────────────────────────────
   Restructured: each interactive section owns its OWN sticky visual, fixed to
   that section's topology. No scroll-driven topology guessing — the diagram is
   always physically beside the text it illustrates. */
function LessonScrollyteller({ showCircuit, kids }) {
  const [v, setV] = useState(9);
  const [r1, setR1] = useState(3);
  const [r2, setR2] = useState(6);
  const [topology, setTopology] = useState("series"); // Playground only (user toggle)
  const [mode, setMode] = useState("cover");           // nav highlight only
  const visHeight = showCircuit ? 330 : 530;

  const stickyFor = (topo) => (
    <aside className="lesson-sticky" data-single={showCircuit ? "0" : "1"}>
        {showCircuit && <VisTabs labels={["WATER", "CIRCUIT"]} />}
      <StickyVisuals v={v} r1={r1} r2={r2} topology={topo}
                     showCircuit={showCircuit} visHeight={visHeight} kids={kids} />
      <VisReadout v={v} r1={r1} r2={r2} topology={topo} kids={kids} />
    </aside>
  );

  return (
    <div className="lesson-stack">
      {/* Big idea — full-width intro, no visual */}
      <div className="lesson-solo">
        <BigIdeaBeat onView={() => setMode("map")} kids={kids} />
      </div>

      {/* SERIES — its own series-only visual */}
      <section className="lesson" data-mode="series">
        <div className="lesson-scroll">
          <SeriesBeat v={v} r1={r1} r2={r2} setR1={setR1} setR2={setR2}
                      onView={() => setMode("series")} kids={kids} />
        </div>
        {stickyFor("series")}
      </section>

      {/* PARALLEL — its own parallel-only visual */}
      <section className="lesson" data-mode="parallel">
        <div className="lesson-scroll">
          <ParallelBeat v={v} r1={r1} r2={r2} setR1={setR1} setR2={setR2}
                        onView={() => setMode("parallel")} kids={kids} />
        </div>
        {stickyFor("parallel")}
      </section>

      {/* Predict + Rules — full-width text */}
      <div className="lesson-solo">
        <PredictBeatCh2 onView={() => setMode("predict")} kids={kids} />
      </div>
      <div className="lesson-solo">
        <RulesBeat v={v} r1={r1} r2={r2} onView={() => setMode("rules")} kids={kids} />
      </div>

      {/* Playground — the ONE place topology switches, and the user drives it */}
      <section className="lesson" data-mode="playground">
        <div className="lesson-scroll">
          <PlaygroundBeat v={v} setV={setV} r1={r1} setR1={setR1} r2={r2} setR2={setR2}
                          topology={topology} setTopology={setTopology}
                          onView={() => setMode("playground")} kids={kids} />
        </div>
        {stickyFor(topology)}
      </section>
    </div>
  );
}

/* ─── Worked example: Christmas lights ────────────────────────────────── */
function PotDividerSection({ kids }) {
  return (
    <section className="section" id="pot" data-screen-label="08 The knob">
      <div className="marker">§ 08 · the knob · an adjustable pinch</div>
      <div className="section-inner">
        <h2 className="serif">{kids ? <>The knob that<br/><em>turns the squeeze.</em></> : <>Meet the knob:<br/>the <em>adjustable</em> resistor.</>}</h2>
        <p className="lede" style={{ maxWidth: "46em" }}>
          {kids
            ? <>Every volume dial, dimmer, and joystick hides the same part: a <b>potentiometer</b>. It’s just a pinch you can <b>change by turning a knob</b> — the very slider you’ve been dragging this whole time, made real. Turn it one way, more flow (brighter). Turn it back, less flow (dimmer).</>
            : <>Every volume dial, dimmer, and joystick is the same part — a <b>potentiometer</b>: a resistor whose value you set by turning a knob. It’s the resistance slider you’ve been dragging, made physical. Wired across the supply, its middle tap (the <em>wiper</em>) is an <b>adjustable voltage divider</b> — dial any fraction of the voltage you like.</>}
        </p>
        <p className="lede" style={{ maxWidth: "46em", color: "var(--ink-soft)" }}>
          {kids
            ? <>Try it: open <b>The Workbench</b>, load the <b>“Dimmer”</b> example, and drag the knob to fade the light up and down.</>
            : <>Try it hands-on: in <b>The Workbench</b> (Lights bench) load the <b>“Dimmer”</b> example and drag the knob — watch the LED current, brightness, and the charge flow respond in real time.</>}
        </p>
        <a className="wn-link" href="sandbox.html" style={{ display: "inline-block", marginTop: 8 }}>Open the Workbench →</a>
      </div>
    </section>
  );
}

function WorkedExampleSection({ kids }) {
  if (kids) return null;
  return (
    <section className="section" id="example" data-screen-label="07 Christmas lights">
      <div className="marker">§ 07 · why Christmas lights die together</div>
      <div className="section-inner">
        <div className="two-col">
          <div>
            <h2 className="serif">A practical story:<br/><em>Christmas lights</em>.</h2>
            <p className="lede">
              Old strings of Christmas lights were wired in <em>series</em>.
              Twenty tiny bulbs, end-to-end, plugged into a wall outlet. They
              worked beautifully — until one bulb burned out.
            </p>
            <p>
              <em>All</em> of them went dark. The series loop was broken; current
              had no way to flow through the surviving bulbs. You had to test
              every single bulb to find the dead one.
            </p>
            <p>
              Modern strings (and your house's lights) wire each bulb in{" "}
              <em>parallel</em>. One bulb dies, its branch opens, but the
              other branches keep their own voltage and keep glowing.
            </p>
          </div>
          <div>
            <div className="card" style={{ padding: "24px 26px" }}>
              <div className="eyebrow" style={{ marginBottom: 12 }}>series voltage budget</div>
              <p style={{ margin: 0 }}>
                20 bulbs, 120 V outlet. Each bulb drops:
              </p>
              <div className="mono" style={{ fontSize: 17, marginTop: 8 }}>
                V<sub>bulb</sub> = 120 V / 20 = <span style={{ color: "var(--water)" }}>6 V each</span>
              </div>

              <div className="eyebrow" style={{ marginTop: 22, marginBottom: 12 }}>parallel voltage budget</div>
              <p style={{ margin: 0 }}>
                Each bulb wired across the full 120 V outlet. Each gets:
              </p>
              <div className="mono" style={{ fontSize: 17, marginTop: 8 }}>
                V<sub>bulb</sub> = <span style={{ color: "var(--water)" }}>120 V</span>
              </div>
              <p className="marg" style={{ marginTop: 14 }}>
                That's why parallel bulbs are physically bigger — they're built
                to handle the full line voltage.
              </p>

              <div className="eyebrow" style={{ marginTop: 22, marginBottom: 12 }}>the trade-off</div>
              <p style={{ margin: 0 }}>
                Series: cheap, but fragile. Parallel: robust, but each part
                needs to handle full voltage. <em>Engineering is choosing</em>.
              </p>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

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

const ADULT_QUIZ = [
  {
    q: "Two resistors in SERIES. How does the total resistance compare to each one?", kind: "concept",
    options: ["Larger than either", "Smaller than either", "Equal to the bigger one", "Always zero"],
    correct: 0,
    explain: "In series, resistances add: R = R₁ + R₂. The total is always bigger than either part.",
  },
  {
    q: "Two resistors in PARALLEL. The total resistance is…", kind: "concept",
    options: ["Larger than either", "Smaller than either", "The average of the two", "Always 1 Ω"],
    correct: 1,
    explain: "More paths means easier flow. Parallel total is always less than the smallest branch.",
  },
  {
    q: "In a series loop, the current through R₁ versus R₂ is…", kind: "concept",
    options: ["Bigger through R₁", "Bigger through R₂", "The same through both", "Zero through both"],
    correct: 2,
    explain: "One path, one current. The same current flows through everything in a series loop.",
  },
  {
    q: "Two 6 Ω resistors in parallel give a total resistance of…", kind: "math",
    options: ["12 Ω", "6 Ω", "3 Ω", "0 Ω"],
    correct: 2,
    explain: "Equal parallel resistors halve: 6 Ω ∥ 6 Ω = 3 Ω.",
  },
  {
    q: "Why did old series-wired Christmas lights all die when one bulb failed?", kind: "concept",
    options: [
      "The others overheated",
      "One open break stops the single shared current path",
      "The voltage doubled",
      "They were never really in series",
    ],
    correct: 1,
    explain: "A series loop has one path. Break it anywhere and current stops everywhere.",
  },
  {
    q: "Three 3 Ω resistors in series total…", kind: "math",
    options: ["1 Ω", "3 Ω", "9 Ω", "27 Ω"],
    correct: 2,
    explain: "Series adds: 3 + 3 + 3 = 9 Ω.",
  },
  {
    q: "In a parallel circuit, the voltage across each branch is…", kind: "concept",
    options: ["split between them", "the same full voltage for each", "always zero", "doubled"],
    correct: 1,
    explain: "Each parallel branch sees the full source voltage — that's the defining feature.",
  },
  {
    q: "A 2 Ω and a 4 Ω resistor in parallel. Using product-over-sum, the total is…", kind: "math",
    options: ["6 Ω", "3 Ω", "1.33 Ω", "8 Ω"],
    correct: 2,
    explain: "(R₁·R₂)/(R₁+R₂) = (2·4)/(2+4) = 8/6 ≈ 1.33 Ω — less than the smaller branch (2 Ω).",
  },
  {
    q: "9 V across two parallel branches, R₁ = 3 Ω and R₂ = 9 Ω. The TOTAL current is…", kind: "math",
    options: ["1 A", "3 A", "4 A", "0.75 A"],
    correct: 2,
    explain: "I₁ = 9/3 = 3 A, I₂ = 9/9 = 1 A. Currents add: I_total = 3 + 1 = 4 A.",
  },
  {
    q: "In a series loop, which resistor takes the bigger share of the voltage?",
    kind: "concept",
    options: ["The smaller resistance", "The bigger resistance", "They always split it evenly", "Whichever is closer to the battery"],
    correct: 1,
    explain: "Voltage divides in proportion to R — the bigger pinch takes the bigger step. (Same current through both, so V = I·R is larger where R is larger.)",
  },
  {
    q: "You open a SECOND parallel branch. What happens to the current in the first branch?",
    kind: "concept",
    options: ["It drops by half", "It doubles", "It doesn't change — but the total from the battery goes up", "It stops"],
    correct: 2,
    explain: "Each branch sees the full source voltage independently. Adding a branch doesn't touch the first one — it just adds its own current to the total.",
  },
  {
    q: "In a series pipe, whatever flows through the first pinch must also flow through the second, because…",
    kind: "concept",
    options: ["the pinches are identical", "water can't pile up or escape — there's only one path", "the second pinch pulls harder", "pressure is zero between them"],
    correct: 1,
    explain: "One path, nowhere to accumulate: the flow that gets through one pinch has no choice but to continue through the next. That's WHY series current is the same everywhere.",
  },
  {
    q: "A volume dial or light dimmer is, underneath, a…",
    kind: "concept",
    options: ["tiny battery", "capacitor", "potentiometer — a resistor you adjust with a knob", "coil of wire"],
    correct: 2,
    explain: "A potentiometer is the resistance slider made physical: turn the knob, change R, change the flow.",
  },
  {
    q: "The practical trade-off between the two wirings is…",
    kind: "concept",
    options: [
      "series is robust, parallel is fragile",
      "series is cheap but one failure kills all; parallel keeps parts independent but each must handle full voltage",
      "parallel uses less wire and less power",
      "there is no practical difference",
    ],
    correct: 1,
    explain: "Series: one shared path, cheap, fragile. Parallel: independent branches, robust — but every branch sees the full source voltage and must be built for it.",
  },
];

const KIDS_QUIZ = [
  {
    q: "Two pinches in the SAME pipe, one after the other. The water has to…", kind: "concept",
    options: ["pick just one", "squeeze through both", "skip them both", "go faster"],
    correct: 1,
    explain: "In a row (series), the water crosses both pinches — so both slow it down.",
  },
  {
    q: "Splitting the pipe into TWO branches (parallel) means…", kind: "concept",
    options: ["less total water gets through", "more total water gets through", "the water stops", "the water freezes"],
    correct: 1,
    explain: "Two roads instead of one! More ways through means more total flow.",
  },
  {
    q: "In a single loop (series), the flow is…", kind: "concept",
    options: ["different in different spots", "the same all the way around", "always zero", "only at the start"],
    correct: 1,
    explain: "One path, one flow. It's the same everywhere in the loop.",
  },
  {
    q: "Four bulbs in a row (series). One burns out. What happens?", kind: "concept",
    options: ["The others get brighter", "Three stay on", "All four go dark", "Nothing changes"],
    correct: 2,
    explain: "Break the single loop and the whole thing goes dark — the old Christmas-lights problem!",
  },
  {
    q: "Which arrangement keeps the OTHER bulbs glowing if one bulb dies?", kind: "concept",
    options: ["Series (one road)", "Parallel (many roads)", "Neither", "Both the same"],
    correct: 1,
    explain: "Parallel branches are independent — one dying doesn't stop the others.",
  },
  {
    q: "Putting pinches side by side (parallel) makes the TOTAL squeeze…", kind: "concept",
    options: ["tighter", "looser", "disappear", "freeze"],
    correct: 1,
    explain: "More roads = easier for water. The total squeeze actually gets looser!",
  },
  {
    q: "Your home's lights are wired in parallel so that…", kind: "concept",
    options: ["they all turn off together", "one burning out doesn't kill the rest", "they use less wire", "they look prettier"],
    correct: 1,
    explain: "Parallel keeps each light independent — one dies, the others stay on.",
  },
  {
    q: "Two branches side by side. How much push does each branch feel?",
    kind: "concept",
    options: ["They share it — half each", "Each feels the FULL push", "Only the first one gets push", "None"],
    correct: 1,
    explain: "Branches don't share the push! Each road gets the barrel's full pressure — what differs is how much flow each lets through.",
  },
  {
    q: "Two pinches in a row. Which one uses up more of the push?",
    kind: "concept",
    options: ["The tighter pinch", "The looser pinch", "They always use the same", "Neither uses any"],
    correct: 0,
    explain: "The tighter squeeze is harder to get through, so it eats the bigger share of the push.",
  },
  {
    q: "A volume knob on a speaker is secretly…",
    kind: "concept",
    options: ["a tiny drum", "a squeeze you can turn looser and tighter", "a battery", "a magnet"],
    correct: 1,
    explain: "It's a pinch with a knob! Turn it one way for more flow (louder), back for less (quieter).",
  },
];

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

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: "big-idea", label: "Two shapes" },
    { id: "series", label: "Series" },
    { id: "parallel", label: "Parallel" },
    { id: "predict", label: "Predict" },
    { id: "rules", label: kids ? "Two rules" : "The rules" },
    { id: "playground", label: "Playground" },
    ...(kids ? [] : [{ id: "example", label: "Example" }]),
    { id: "practice", label: "Practice" },
    { id: "quiz", label: "Quiz" },
    { id: "whats-next", label: "What's next" },
  ];
  return (
    <>
      <ChapterStartMarker chapterN="02" />
      <ProgressBar />
      <TopBar currentN="02" chapterLabel="Ch. 02 — The Branching"
              audience={t.audience}
              setAudience={(v) => setTweak("audience", v)} />
      <ChapterNav items={navItems} />
      <main>
        <CoverPage chapterN="02"
                   chapterTitle={<>The <em>Branching</em>.</>}
                   chapterSub="Chapter 2 · Series & parallel"
                   kids={kids}
                   lede={kids
                     ? <>Last chapter you had <em>one</em> pipe and <em>one</em> bulb. Now we'll hook up <em>more</em>. There are two ways to do it — and they behave very differently.</>
                     : <>Chapter 1 had a single resistor. Real circuits have hundreds. They're hooked together in exactly two flavors — <em>series</em> and <em>parallel</em> — and every clever thing in electronics is some recipe of the two.</>
                   } />
        <LessonScrollyteller showCircuit={t.showCircuit} kids={kids} />

        <CheckpointQuiz kids={kids} label="Checkpoint 1" pick={2}
          title={kids ? "Quick check!" : "Did it stick?"}
          questions={[
            {
              q: "Two pinches, one after another in the same pipe (series). The total resistance…",
              options: ["Adds up — the flow drops", "Cancels out", "Equals the smaller one", "Halves"],
              correct: 0,
              explain: kids ? "The water has to fight BOTH squeezes in a row. Two pinches are harder than one, so less flow."
                            : "Series resistances add: R = R₁ + R₂. The same current fights both, so total opposition grows and I falls.",
            },
            {
              q: "The same two pinches, but side-by-side (parallel). Compared to one pinch alone, total flow is…",
              options: ["Bigger — two paths pass more water", "Smaller", "Exactly the same", "Zero"],
              correct: 0,
              explain: kids ? "Two open doors let more people through than one. Each path flows like before, and the flows add up."
                            : "Each branch sees the full push and draws its own current; the totals add. More paths = less total resistance = more flow.",
            },
            {
              q: "In a series pipe, the water level steps DOWN after each pinch. What does that level stand for?",
              options: ["The push that's left (remaining voltage)", "The speed of the water", "The temperature", "The size of the barrel"],
              correct: 0,
              explain: kids ? "Each squeeze uses up some push. The level shows how much push is left to spend on the rest of the trip."
                            : "Each resistor drops part of the voltage; the level is what remains. By the end of the loop, all of it is spent — that's Kirchhoff's voltage law in water.",
            },
            {
              q: "One branch of a parallel pair gets blocked completely. The other branch…",
              options: ["Keeps flowing just like before", "Stops too", "Instantly doubles its flow", "Reverses direction"],
              correct: 0,
              explain: kids ? "Each path has its own door to the barrel. Blocking one doesn't change the push on the other."
                            : "Parallel branches each see the source voltage independently. Losing one branch only reduces the TOTAL draw — the survivor's current is unchanged.",
            },
          ]} />

        <WorkedExampleSection kids={kids} />

        <PotDividerSection kids={kids} />

        <CheckpointQuiz kids={kids} label="Checkpoint 2" pick={2}
          title={kids ? "Spot it in real life!" : "Out in the wild."}
          intro={kids ? "Series and parallel are hiding all over your house." : "Same two wirings, everyday consequences."}
          questions={[
            {
              q: "Old-style holiday lights: ONE bulb burns out and the whole string goes dark. How were they wired?",
              options: ["Series — one break cuts the only path", "Parallel — each bulb has its own path", "Half and half", "Wirelessly"],
              correct: 0,
              explain: kids ? "All the bulbs shared one single loop, like beads on one string. Snip anywhere and nothing flows."
                            : "A series string has exactly one current path; an open filament opens the entire loop. Modern strings add shunts or wire in parallel for this reason.",
            },
            {
              q: "Your house outlets are wired in parallel. Why is that the right choice?",
              options: ["Every device gets the full push, and switching one off doesn't kill the rest", "It saves copper wire", "It makes everything run dimmer and safer", "It isn't — series would be better"],
              correct: 0,
              explain: kids ? "Each plug gets its own path to the source — full push for everyone, and the toaster doesn't care if the TV turns off."
                            : "Parallel gives every load the full mains voltage and independence: any device can come or go without changing what the others see.",
            },
            {
              q: "You plug a second space heater into the same circuit. The total current from the breaker…",
              options: ["Goes up — a second path is now drawing flow", "Goes down", "Stays exactly the same", "Drops to zero"],
              correct: 0,
              explain: kids ? "Another open door means more total water moving. That's why too many heaters on one circuit trips the breaker!"
                            : "Parallel currents add: I_total = I₁ + I₂. That's precisely what a breaker watches for — total draw exceeding the wiring's safe limit.",
            },
            {
              q: "A string of 3 bulbs in series glows dim. To brighten them WITHOUT a bigger battery, you could…",
              options: ["Rewire them in parallel", "Add a fourth bulb in series", "Use thinner wire", "Swap the battery ends"],
              correct: 0,
              explain: kids ? "In parallel each bulb gets the FULL push instead of sharing it three ways — much brighter (but the barrel drains faster)."
                            : "In series each bulb gets ⅓ of the voltage. In parallel each sees all of it — full brightness, at the cost of triple the battery draw.",
            },
          ]} />

        <PracticeProblems chapterN="02" kids={kids} problems={[
          (rng) => {
            const a = rng.pick([2, 3, 4, 5, 6]), b = rng.pick([6, 8, 10, 12]);
            return {
              q: { adult: `Two resistors — ${a} Ω and ${b} Ω — are wired in series. What is their combined resistance?`,
                   kids: `Two pinches in a row: a ${a} and a ${b}. In a row you just add them. What's the total?` },
              unit: "Ω", answer: a + b,
              hint: "Series resistances simply add: R = R\u2081 + R\u2082.",
              solution: { adult: `In series, resistances add: ${a} Ω + ${b} Ω = ${a + b} Ω.`, kids: `Add them: ${a} + ${b} = ${a + b}.` } };
          },
          (rng) => {
            const a = rng.pick([2, 3, 4, 6]), b = rng.pick([3, 4, 6, 12]);
            const r = +((a * b) / (a + b)).toFixed(3);
            return {
              q: { adult: `A ${a} Ω and a ${b} Ω resistor are wired in parallel. What is the combined resistance?`,
                   kids: `Now a ${a} and a ${b} sit side by side (parallel). What's the combined pinch?` },
              unit: "Ω", answer: r, tol: 0.04,
              hint: "Product over sum: (R\u2081·R\u2082) ÷ (R\u2081+R\u2082).",
              solution: { adult: `Product over sum: (${a}·${b}) ÷ (${a}+${b}) = ${a * b} ÷ ${a + b} = ${r} Ω — less than either branch.`, kids: `Multiply, then divide by the sum: (${a}×${b}) ÷ (${a}+${b}) = ${a * b} ÷ ${a + b} = ${r}.` } };
          },
          (rng) => {
            const a = rng.pick([2, 3, 4, 5]), b = rng.pick([4, 5, 6, 7]), v = rng.int(6, 24, 2);
            const i = +(v / (a + b)).toFixed(3);
            return {
              q: { adult: `A ${v} V battery drives a ${a} Ω and a ${b} Ω resistor in series. What current flows?`,
                   kids: `${v} of push through a ${a} and a ${b} in a row. Flow = push ÷ total pinch. What's the flow?` },
              unit: "A", answer: i, tol: 0.04,
              hint: "Add the series resistors first, then I = V ÷ R.",
              solution: { adult: `Series total = ${a + b} Ω, so I = V ÷ R = ${v} V ÷ ${a + b} Ω = ${i} A.`, kids: `Total pinch = ${a} + ${b} = ${a + b}. Flow = ${v} ÷ ${a + b} = ${i}.` } };
          },
        ]} />

        <ChapterQuiz
          chapterN="02"
          title={kids ? "Quick quiz!" : "Check your understanding."}
          intro={kids
            ? "Five quick questions about one road vs. many roads. Try as often as you like."
            : "Five questions on series and parallel. 70% to pass; retry as often as you like."}
          questions={kids ? KIDS_QUIZ : ADULT_QUIZ}
          pick={5}
        />
        <WhatsNext
          currentN="02"
          kids={kids}
          summary={kids
            ? <>Series and parallel — every gadget you'll ever crack open uses both.</>
            : <>Series and parallel are the bread and butter. Every analog circuit is some recipe of these two.</>
          }
          prevHref="chapter1.html"
          prevLabel="Chapter 1"
          nextHref="chapter3.html"
          nextLabel="Chapter 3 · Power & Heat"
        />
      </main>
      <TweaksPanel title="Tweaks">
        <CommonTweaks t={t} setTweak={setTweak}
          animationToggles={[{ key: "showCircuit", label: "Show circuit" }]} />
      </TweaksPanel>
      <GlossaryFab />
    </>
  );
}

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