/* chapter4.jsx — Chapter 4: The Bucket (Capacitors) */

const { useState, useEffect, useRef } = React;

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

function BigIdeaBeat({ onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="begin" data-screen-label="01 The bucket" ref={ref}>
      <div className="beat-marker">§ 01 · the bucket</div>
      {kids ? (
        <>
          <h2 className="serif">A <em>capacitor</em><br/>is a tiny bucket.</h2>
          <p className="lede">
            Open the tap — the bucket fills up. Close the tap and open the
            drain — the bucket empties. The bucket can <em>hold</em> water
            for later.
          </p>
          <p>
            That's exactly what a capacitor does with electricity. It
            stores charge in a little internal "bucket" and gives it back
            when you ask.
          </p>
          <p>
            And the harder you push (more volts), the more it holds. A bigger
            bucket holds more too — so the charge stored is just how big the
            bucket is, times how hard you push.
          </p>
        </>
      ) : (
        <>
          <h2 className="serif">A capacitor stores<br/><em>charge</em>.</h2>
          <p className="lede">
            The first three chapters were about flow in steady state. A
            capacitor breaks that — it can <em>hold</em> charge, so what
            happens at this instant depends on what happened a moment ago.
          </p>
          <p>
            The water analogy is a bucket: open a pipe into it and the bucket
            fills up over time. Open a drain and it empties. Bigger bucket
            (bigger <span className="mono">C</span>) → more water held → slower
            to fill or drain.
          </p>
          <div className="marg" style={{ marginTop: 12 }}>
            Capacitance is measured in <span className="mono">farads (F)</span>.
            One farad is enormous — most real caps are measured in microfarads
            (µF) or picofarads (pF). Named for Michael Faraday.
          </div>
          <div className="marg" style={{ marginTop: 12 }}>
            Capacitance is really a <em>ratio</em>: how much charge the cap holds
            for every volt across it. That gives the defining equation
            <span className="mono"> <Eq>Q = C × V</Eq></span> — charge
            (coulombs) equals capacitance (farads) times voltage. So a
            <span className="mono"> 1 F</span> cap at <span className="mono">1 V</span>{" "}
            holds <span className="mono">1 coulomb</span>; a
            <span className="mono"> 470 µF</span> cap at
            <span className="mono"> 10 V</span> holds
            <span className="mono"> 470 µF × 10 V = 4.7 mC</span>.
          </div>
        </>
      )}
      <div className="pull">A capacitor is a memory of recent voltage.</div>
    </div>
  );
}

function ChargingBeat({ vIn, R, C, setMode, onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="charging" data-screen-label="02 Charging" ref={ref}>
      <div className="beat-marker">§ 02 · filling up</div>
      <div className="chip water" style={{ marginBottom: 16 }}>CHARGE MODE</div>
      <h2 className="serif"><em>Charging</em>:<br/>the tap is open.</h2>
      {kids ? (
        <>
          <p className="lede">
            Hit "Charge" and watch the bucket fill. It starts fast — lots of
            empty space, lots of room — and slowly tapers as it nears full.
          </p>
          <p>
            <em>Tighter</em> pinch on the pipe → slower fill.<br/>
            <em>Bigger</em> bucket → slower fill (more to fill up).
          </p>
        </>
      ) : (
        <>
          <p className="lede">
            Hook the cap across the battery through a resistor and the voltage
            on the cap climbs from zero toward the battery. The rate is fast
            at first (big voltage difference, big current) and slows as the
            cap fills up.
          </p>
          <p>
            The shape is an <em>exponential approach</em>:
          </p>
          <div className="eq" style={{ fontSize: 26, margin: "14px 0 18px" }}>
            V<sub style={{ fontSize: "0.55em" }}>cap</sub>(t)
            <span className="op">=</span>
            V<sub style={{ fontSize: "0.55em" }}>in</sub>
            <span className="op">·</span>
            <span style={{ fontStyle: "italic" }}>(1 − e<sup style={{ fontSize: "0.55em" }}>−t/τ</sup>)</span>
          </div>
          <p>
            where <span className="mono">τ = R·C</span> is the <em>time
            constant</em>. After one τ, the cap is at ~63% of V<sub>in</sub>.
            After 5τ, basically full.
          </p>
          <div className="card" style={{ background: "var(--bg-card)", borderLeft: "3px solid var(--water)", marginTop: 4 }}>
            <div className="eyebrow" style={{ marginBottom: 8, color: "var(--water)" }}>reading the equation in plain words</div>
            <p style={{ margin: 0, fontSize: 14.5, color: "var(--ink-soft)" }}>
              <b>V<sub>in</sub></b> is just the <em>supply</em> voltage — the "in" means
              voltage coming <em>in</em> from the battery (not anything "internal"). The cap
              can never charge past it.
            </p>
            <p style={{ margin: "8px 0 0", fontSize: 14.5, color: "var(--ink-soft)" }}>
              The <b>(1 − e<sup>−t/τ</sup>)</b> part is just "<em>how full, 0 to 1</em>." At the start
              t = 0, so e<sup>0</sup> = 1 and the bracket is 0 → empty. After a long time
              e<sup>−big</sup> → 0 and the bracket → 1 → full. τ sets how quickly you slide from
              0 to 1.
            </p>
            <p style={{ margin: "8px 0 0", fontSize: 13.5, color: "var(--ink-faint)" }}>
              Don't worry about the e for now — the takeaway is just "<em>fast at first, then
              eases in, finished after about 5 τ</em>." We'll revisit the exact curve later.
            </p>
          </div>
        </>
      )}
      <div className="rule">try it</div>
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
        <ModeButton mode="charge" current={null} setMode={setMode}>
          ▶ Charge
        </ModeButton>
        <ModeButton mode="hold" current={null} setMode={setMode}>
          ❚❚ Hold
        </ModeButton>
        <ModeButton mode="discharge" current={null} setMode={setMode}>
          ▼ Drain
        </ModeButton>
      </div>
    </div>
  );
}

function ModeButton({ mode, current, setMode, children }) {
  const active = current === mode;
  return (
    <button onClick={() => setMode(mode)}
            style={{
              appearance: "none",
              border: `1.5px solid ${active ? "var(--current)" : "var(--rule-strong)"}`,
              background: active ? "var(--current)" : "transparent",
              color: active ? "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,
            }}>
      {children}
    </button>
  );
}

function DischargingBeat({ mode, setMode, onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="discharging" data-screen-label="03 Discharging" ref={ref}>
      <div className="beat-marker">§ 03 · letting go</div>
      <div className="chip" style={{ marginBottom: 16, color: "var(--current)", borderColor: "var(--current)" }}>DISCHARGE MODE</div>
      <h2 className="serif"><em>Discharging</em>:<br/>the drain is open.</h2>
      {kids ? (
        <>
          <p className="lede">
            Hit "Drain" and watch the bucket empty. The water rushes out fast
            at first — lots of pressure pushing it — then slows as the bucket
            empties out.
          </p>
          <p>
            That stored water did <em>work</em> on the way out. In a real
            circuit, a capacitor discharging through a bulb makes the bulb
            glow briefly — even after you've unplugged the battery.
          </p>
          <p>
            And here's a fair question: why does the <em>pinch</em> change how
            fast it drains? Because the water leaving the bucket has to squeeze
            through the very same pinch it came in by! The circuit is one loop
            of pipe — there's no back door. Tight pinch: slow fill AND slow
            drain. Wide pinch: fast both ways.
          </p>
        </>
      ) : (
        <>
          <p className="lede">
            Disconnect the battery and connect the cap directly through a
            resistor. The cap acts <em>as if</em> it were the battery, dumping
            its stored charge back through the loop.
          </p>
          <div className="eq" style={{ fontSize: 26, margin: "14px 0 18px" }}>
            V<sub style={{ fontSize: "0.55em" }}>cap</sub>(t)
            <span className="op">=</span>
            V<sub style={{ fontSize: "0.55em" }}>0</sub>
            <span className="op">·</span>
            <span style={{ fontStyle: "italic" }}>e<sup style={{ fontSize: "0.55em" }}>−t/τ</sup></span>
          </div>
          <p>
            Same τ = RC. Same exponential shape, mirrored. This is how a
            camera flash, a defibrillator, and a TV-remote LED all work —
            stored charge dumped fast.
          </p>
          <p>
            A question worth pausing on: why does R — which sat <em>before</em>
            the cap while charging — also govern the drain? Because "before"
            and "after" are bookkeeping, not physics: the loop is a single
            series path, and the escaping charge must traverse the same R in
            reverse. Position in a series loop never matters (chapter 2);
            what matters is what's <em>in</em> the loop. One R, so one τ —
            both directions. (Flash circuits that need fast dump but gentle
            charge use two different paths, steered by diodes — chapter 7.)
          </p>
        </>
      )}
      <div className="rule">try discharging</div>
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
        <ModeButton mode="charge" current={mode} setMode={setMode}>▶ Charge</ModeButton>
        <ModeButton mode="hold" current={mode} setMode={setMode}>❚❚ Hold</ModeButton>
        <ModeButton mode="discharge" current={mode} setMode={setMode}>▼ Drain</ModeButton>
      </div>
    </div>
  );
}

function TimeConstantBeat({ R, C, setR, setC, onView, kids }) {
  const ref = useInViewCallback(onView);
  const tau = R * C;
  if (kids) {
    return (
      <div className="beat" id="time-constant" data-screen-label="04 Time" ref={ref}>
        <div className="beat-marker">§ 04 · how fast or slow</div>
        <h2 className="serif">How <em>fast</em><br/>does it fill?</h2>
        <p className="lede">
          Two things decide how fast the bucket fills (or drains):
        </p>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginTop: 22 }}>
          <div className="card" style={{ background: "transparent", padding: "18px" }}>
            <div className="eyebrow" style={{ marginBottom: 10 }}>The pipe</div>
            <p style={{ margin: 0, fontSize: 16 }}>
              Tighter pinch <span className="mono">R</span> → slower flow → slower fill.
            </p>
          </div>
          <div className="card" style={{ background: "transparent", padding: "18px" }}>
            <div className="eyebrow" style={{ marginBottom: 10 }}>The bucket</div>
            <p style={{ margin: 0, fontSize: 16 }}>
              Bigger bucket <span className="mono">C</span> → more to fill → slower fill.
            </p>
          </div>
        </div>
        <div className="rule">try changing them</div>
        <Slider name="R · pinch" value={R} min={0.5} max={10} step={0.1}
                unit="Ω" accent="" onChange={setR} />
        <Slider name="C · bucket size" value={C} min={0.5} max={8} step={0.1}
                unit="" accent="water" onChange={setC} />
      </div>
    );
  }
  return (
    <div className="beat" id="time-constant" data-screen-label="04 Time constant" ref={ref}>
      <div className="beat-marker">§ 04 · the time constant</div>
      <h2 className="serif">Tau<br/>(<span className="mono">τ = R · C</span>)</h2>
      <p className="lede">
        One number summarizes everything about how fast a capacitor settles —
        the <em>time constant</em> τ. Bigger R or bigger C → longer τ → slower
        response.
      </p>
      <div className="card" style={{ background: "transparent", padding: "20px 22px", marginTop: 16 }}>
        <div className="eyebrow" style={{ marginBottom: 10 }}>right now</div>
        <div className="eq" style={{ fontSize: 28 }}>
          <span>τ</span>
          <span className="op">=</span>
          <span className="num">{fmt(R, 1)}</span>
          <span className="op" style={{ fontSize: 16 }}>Ω</span>
          <span className="op">×</span>
          <span className="num">{fmt(C, 1)}</span>
          <span className="op" style={{ marginLeft: 12 }}>=</span>
          <span className="num">{fmt(tau, 1)}</span>
        </div>
        <div className="marg" style={{ marginTop: 8 }}>
          Roughly: after τ seconds it's 63% there. After 5τ ≈ done.
        </div>
      </div>
      <div className="rule">try it</div>
      <Slider name="R · resistance" value={R} min={0.5} max={10} step={0.1}
              unit="Ω" accent="" onChange={setR} />
      <Slider name="C · capacitance" value={C} min={0.5} max={8} step={0.1}
              unit="" accent="water" onChange={setC} />
      <div className="marg" style={{ marginTop: 14 }}>
        <em>Note on units.</em> We're using arbitrary "C" units here so the
        animation is watchable. Real capacitors range from picofarads (RF
        circuits) to thousands of microfarads (power supplies).
      </div>
    </div>
  );
}

function PredictBeat({ onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="predict" data-screen-label="05 Predict" ref={ref}>
      <div className="beat-marker">§ 05 · check your gut</div>
      <h2 className="serif">A puzzle.</h2>
      <PredictReveal
        question={kids
          ? "You DOUBLE the size of the bucket. How long does it take to fill?"
          : "Double the capacitance. How does the charge time change?"
        }
        options={[
          "Half as long",
          "About the same",
          "Twice as long",
          "Four times as long",
        ]}
        correct={2}
        explanation={kids
          ? "Bigger bucket means more water to fit in. Twice as much room → twice as long to fill. The pipe didn't change, but there's more space to fill."
          : "τ = RC. Doubling C doubles τ, so charge time scales the same way. After 5τ the cap is ~99% charged either way."
        }
        accent="water"
      />
      <PredictReveal
        question={kids
          ? "You CHARGE the bucket all the way up, then close the tap. How full is the bucket a minute later?"
          : "You charge a real capacitor fully, then disconnect it from everything. What's V_cap an hour later?"
        }
        options={[
          "Zero — it leaks out",
          "Same — it stays charged",
          "Negative — it reverses",
          "Half — depends on size",
        ]}
        correct={1}
        explanation={kids
          ? "With both valves shut, water has nowhere to go. The bucket stays full. (In real life, real capacitors leak a little — but a good one holds its charge for a long time.)"
          : "Ideal capacitors hold their charge indefinitely with nothing connected. Real ones have tiny leakage currents, but a good film cap can hold charge for days. This is why repair manuals tell you to short caps before touching old TVs."
        }
        accent="current"
      />
    </div>
  );
}

function PlaygroundBeat({ vIn, setVIn, R, setR, C, setC, mode, setMode, vCap, onView, kids }) {
  const ref = useInViewCallback(onView);
  const tau = R * C;
  // hear the RC curve: tone follows the cap level — glides up while charging
  // (fast then slowing), down while draining. Active only when this beat is on.
  const tone = useToneFollow();
  const seen = React.useRef(false);
  const vis = useInViewCallback(() => { seen.current = true; });
  React.useEffect(() => {
    if (!seen.current) return;
    const level = Math.max(0, Math.min(1, vCap / Math.max(0.01, vIn)));
    if (mode === "hold" || level < 0.005) { tone.stop(); return; }
    tone.set(0.12 + level * 0.8, 0.45);
  }, [vCap, vIn, mode]);
  React.useEffect(() => tone.stop, []);
  return (
    <div className="beat" id="playground" data-screen-label="06 Playground" ref={(el) => { ref.current = el; vis.current = el; }}>
      <div className="beat-marker">§ 06 · all knobs unlocked</div>
      <h2 className="serif">Drive it<br/><em>by hand</em>.</h2>
      <p className="lede">
        {kids
          ? "Cycle between Charge and Drain. Change the bucket size. Watch what happens."
          : "Cycle modes manually. Pin different RC products and feel the difference between snappy and sluggish."}
      </p>
      <SonifyHint text="Sound's on — hit Charge and listen: the pitch rises fast, then slows. That's the RC curve." />

      <div style={{ marginTop: 22, display: "flex", gap: 8, flexWrap: "wrap" }}>
        <ModeButton mode="charge" current={mode} setMode={setMode}>▶ Charge</ModeButton>
        <ModeButton mode="hold" current={mode} setMode={setMode}>❚❚ Hold</ModeButton>
        <ModeButton mode="discharge" current={mode} setMode={setMode}>▼ Drain</ModeButton>
      </div>

      <div style={{ marginTop: 22, display: "flex", flexDirection: "column", gap: 6 }}>
        <Slider name="V_in · battery" value={vIn} min={0} max={12} step={0.5}
                unit="V" accent="water" onChange={setVIn} />
        <Slider name="R · pinch" value={R} min={0.5} max={10} step={0.1}
                unit="Ω" accent="" onChange={setR} />
        <Slider name="C · bucket size" value={C} min={0.5} max={8} step={0.1}
                unit="" accent="water" onChange={setC} />
      </div>

      <div className="card" style={{ background: "transparent", marginTop: 22, padding: "16px 20px" }}>
        <div className="eyebrow" style={{ marginBottom: 10 }}>state</div>
        {kids ? (
          <p style={{ margin: 0, fontSize: 17 }}>
            Bucket is <span className="mono" style={{ color: "var(--water-deep)" }}>{fmt((vCap / Math.max(0.01, vIn)) * 100, 0)}%</span> full.
          </p>
        ) : (
          <p style={{ margin: 0, fontSize: 17 }}>
            V<sub>cap</sub>: <span className="mono" style={{ color: "var(--water-deep)" }}>{fmt(vCap, 2)} V</span>{" "}
            ({fmt((vCap / Math.max(0.01, vIn)) * 100, 0)}% of V<sub>in</sub>) · τ = <span className="mono">{fmt(tau, 1)}</span>
          </p>
        )}
      </div>
    </div>
  );
}

/* ─── LessonScrollyteller ───────────────────────────────────────────────── */
function LessonScrollyteller({ showCircuit, kids }) {
  const [vIn, setVIn] = useState(9);
  const [R, setR] = useState(3);
  const [C, setC] = useState(2);
  const [mode, setMode] = useState("hold");
  const [navMode, setNavMode] = useState("begin");

  const { vCap } = useCapSim({ vIn, R, C, mode });
  const visHeight = showCircuit ? 340 : 540;

  return (
    <section className="lesson">
      <div className="lesson-scroll">
        <BigIdeaBeat onView={() => setNavMode("begin")} kids={kids} />
        <ChargingBeat vIn={vIn} R={R} C={C} setMode={setMode}
                      onView={() => { setNavMode("charging"); setMode("charge"); }} kids={kids} />
        <DischargingBeat mode={mode} setMode={setMode}
                         onView={() => { setNavMode("discharging"); setMode("discharge"); }} kids={kids} />
        <TimeConstantBeat R={R} C={C} setR={setR} setC={setC}
                          onView={() => setNavMode("time-constant")} kids={kids} />
        <PredictBeat onView={() => setNavMode("predict")} kids={kids} />
        <PlaygroundBeat vIn={vIn} setVIn={setVIn} R={R} setR={setR} C={C} setC={setC}
                        mode={mode} setMode={setMode} vCap={vCap}
                        onView={() => setNavMode("playground")} kids={kids} />
      </div>
      <aside className="lesson-sticky" data-single={showCircuit ? "0" : "1"}>
        {showCircuit && <VisTabs labels={["WATER", "LOOP"]} />}
        <div className="vis-block">
          <div className="stage-label">WATER · the bucket fills and drains</div>
          <BucketScene vIn={vIn} R={R} C={C} vCap={vCap} mode={mode} height={visHeight} kids={kids} />
        </div>
        {showCircuit && (
          <div className="vis-block">
            <div className="stage-label">{kids ? "THE LOOP · charge piles up, flow stops" : "THE LOOP · current tapers as the cap fills"}</div>
            <LoopScene4 vIn={vIn} R={R} vCap={vCap} mode={mode} kids={kids} />
          </div>
        )}
        <div className="vis-readout">
          <div className="ro-v">
            <span className="ro-name">{kids ? "Tower" : <>V<sub>in</sub></>}</span>
            <span className="ro-val">{fmt(vIn, 1)}<span className="ro-unit">V</span></span>
          </div>
          <div className="ro-r">
            <span className="ro-name">{kids ? "Pinch" : "R"}</span>
            <span className="ro-val">{fmt(R, 1)}<span className="ro-unit">Ω</span></span>
          </div>
          <div className="ro-i">
            <span className="ro-name">{kids ? "Bucket" : "C"}</span>
            <span className="ro-val">{fmt(C, 1)}</span>
          </div>
          <div className="ro-p ro-active">
            <span className="ro-name">{kids ? "Level" : <>V<sub>cap</sub></>}</span>
            <span className="ro-val">{fmt(vCap, 1)}<span className="ro-unit">V</span></span>
          </div>
        </div>
      </aside>
    </section>
  );
}

/* ─── Worked example (adult): camera flash ────────────────────────────── */
function WorkedExampleSection({ kids }) {
  if (kids) return null;
  return (
    <section className="section" id="example" data-screen-label="07 Camera flash">
      <div className="marker">§ 07 · a real RC story · the camera flash</div>
      <div className="section-inner">
        <div className="two-col">
          <div>
            <h2 className="serif">A practical story:<br/><em>the camera flash</em>.</h2>
            <p className="lede">
              Hit the shutter — <em>BRRZT</em>, a few seconds of charging hum,
              then the ready light blinks on. Click — and a brilliant flash
              dumps in milliseconds. That whole dance is a capacitor.
            </p>
            <p>
              A typical flash holds about <span className="mono">100 µF</span>{" "}
              charged to <span className="mono">300 V</span>. Doing the math:
            </p>
          </div>
          <div>
            <div className="card" style={{ padding: "24px 26px" }}>
              <div className="eyebrow" style={{ marginBottom: 12 }}>energy stored</div>
              <div className="mono" style={{ fontSize: 17, lineHeight: 1.7 }}>
                E = ½ · C · V²<br/>
                E = ½ · 100×10⁻⁶ · 300²<br/>
                E = <span style={{ color: "var(--current)" }}>4.5 joules</span>
              </div>
              <div className="eyebrow" style={{ marginTop: 22, marginBottom: 12 }}>peak power</div>
              <p style={{ margin: 0 }}>
                That 4.5 J dumps in ~<span className="mono">1 ms</span>.
                Power = energy / time:
              </p>
              <div className="mono" style={{ fontSize: 17, marginTop: 8 }}>
                P = 4.5 J / 0.001 s = <span style={{ color: "var(--current)" }}>4,500 W</span>
              </div>
              <p className="marg" style={{ marginTop: 14 }}>
                A 4.5 kW pulse from a battery that can barely supply 5 W
                continuously. <em>This is what capacitors are for</em>: trading
                a slow trickle for a brief burst.
              </p>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─── Quiz banks ────────────────────────────────────────────────────────
   App below. */

const ADULT_QUIZ = [
  {
    q: "A capacitor is most like which water thing?", kind: "concept",
    options: ["A pipe", "A bucket that holds water", "A pump", "A pinch in the pipe"],
    correct: 1,
    explain: "A capacitor stores charge the way a bucket stores water — fill it, hold it, drain it later.",
  },
  {
    q: "While charging, the capacitor voltage rises…", kind: "concept",
    options: ["instantly", "fast at first, then slowing as it fills", "at a steady constant rate", "never"],
    correct: 1,
    explain: "It's an exponential approach — big gap means fast fill, tapering as it nears full.",
  },
  {
    q: "The time constant is…", kind: "math",
    options: ["τ = R + C", "τ = R × C", "τ = R ÷ C", "τ = V × I"],
    correct: 1,
    explain: "τ = R·C. Bigger resistance or bigger capacitance → longer time constant → slower response.",
  },
  {
    q: "Double the capacitance. The charge time…", kind: "math",
    options: ["halves", "stays the same", "doubles", "becomes zero"],
    correct: 2,
    explain: "τ = RC, so doubling C doubles τ — it takes twice as long to settle.",
  },
  {
    q: "Why can a camera flash deliver a huge burst from a small battery?", kind: "concept",
    options: [
      "The battery is secretly huge",
      "A capacitor stores energy slowly, then dumps it fast",
      "It uses no energy at all",
      "Light is free",
    ],
    correct: 1,
    explain: "The cap trickle-charges over seconds, then releases joules in a millisecond — a brief, enormous power spike.",
  },
  {
    q: "Bigger resistance in the charging path makes the capacitor fill…", kind: "math",
    options: ["faster", "slower", "instantly", "backwards"],
    correct: 1,
    explain: "τ = R·C. A tighter pinch (bigger R) slows the fill.",
  },
  {
    q: "After about 5 time constants, a charging capacitor is…", kind: "math",
    options: ["barely started", "halfway", "essentially fully charged", "empty again"],
    correct: 2,
    explain: "By 5τ the cap is ~99% charged — close enough to call it done.",
  },
  {
    q: "Why does the SAME resistor set both the fill speed AND the drain speed?",
    kind: "concept",
    options: [
      "It doesn't — draining is always faster",
      "The circuit is one loop: the escaping charge must squeeze back through the very same R",
      "Capacitors remember the resistor",
      "Because τ = R + C",
    ],
    correct: 1,
    explain: "There's no back door. One series loop means one path — so one τ = RC governs both directions.",
  },
  {
    q: "What genuinely NEW ability does a capacitor add to a circuit?",
    kind: "concept",
    options: ["More resistance", "Memory — it holds charge, so the present depends on the past", "Free energy", "Color"],
    correct: 1,
    explain: "The first three chapters were steady state. A cap stores charge over time — circuits gain a sense of time: delay, smoothing, filtering.",
  },
  {
    q: "Q = C·V. A 2 F capacitor charged to 3 V holds…",
    kind: "math",
    options: ["1.5 C of charge", "5 C of charge", "6 C of charge", "9 C of charge"],
    correct: 2,
    explain: "Charge = capacitance × voltage = 2 × 3 = 6 coulombs.",
  },
  {
    q: "Can a capacitor charge to a HIGHER voltage than the battery feeding it?",
    kind: "concept",
    options: ["Yes, if you wait long enough", "Yes, if R is small", "No — the source voltage is the ceiling it approaches", "Only in winter"],
    correct: 2,
    explain: "The cap climbs toward the battery's voltage and levels off there. The gap drives the flow; no gap, no flow.",
  },
  {
    q: "After ONE time constant τ, the capacitor is roughly…",
    kind: "math",
    options: ["10% charged", "50% charged", "63% charged", "99% charged"],
    correct: 2,
    explain: "One τ ≈ 63% of the way there; ~5τ is essentially full.",
  },
];

const KIDS_QUIZ = [
  {
    q: "A capacitor is like…", kind: "concept",
    options: ["a pipe", "a bucket", "a pump", "a pinch"],
    correct: 1,
    explain: "A bucket! It holds water (charge) for later.",
  },
  {
    q: "When you open the tap, the bucket…", kind: "concept",
    options: ["empties", "fills up", "explodes", "disappears"],
    correct: 1,
    explain: "Open the tap and water flows in — the bucket fills.",
  },
  {
    q: "A BIGGER bucket takes — to fill.", kind: "concept",
    options: ["less time", "more time", "no time", "the same time"],
    correct: 1,
    explain: "More room to fill = more time. Bigger bucket, slower fill.",
  },
  {
    q: "You fill the bucket, then shut both the tap and the drain. A minute later it's…", kind: "concept",
    options: ["empty", "still full", "frozen", "on fire"],
    correct: 1,
    explain: "With nowhere to go, the water stays put. The bucket holds its level.",
  },
  {
    q: "What makes a camera flash go off so bright and fast?", kind: "concept",
    options: [
      "A bucket fills up slowly, then dumps all at once",
      "The battery is huge",
      "It doesn't use energy",
      "Magic mirrors",
    ],
    correct: 0,
    explain: "Fill the bucket slowly, then tip it all out at once — a big splash in an instant!",
  },
  {
    q: "A tighter pinch on the pipe makes the bucket fill…", kind: "concept",
    options: ["faster", "slower", "never", "sideways"],
    correct: 1,
    explain: "Less water gets through a tight pinch, so the bucket fills more slowly.",
  },
  {
    q: "When you open the DRAIN, the bucket…", kind: "concept",
    options: ["fills up", "empties out", "stays full", "gets bigger"],
    correct: 1,
    explain: "Open the drain and the stored water rushes out — the bucket empties.",
  },
  {
    q: "The water drains out through the SAME pinch it came in by. So a tight pinch means…",
    kind: "concept",
    options: ["slow fill AND slow drain", "fast fill, slow drain", "slow fill, fast drain", "no filling at all"],
    correct: 0,
    explain: "One loop of pipe, no back door! The same squeeze slows the water both ways.",
  },
  {
    q: "You unplug the battery. Can the full bucket still light the bulb?",
    kind: "concept",
    options: ["No, never", "Yes — briefly, as it dumps its stored water", "Only if you shake it", "Yes, forever"],
    correct: 1,
    explain: "The full bucket acts like a little battery for a moment — that's how a camera flash works!",
  },
];

/* ─── 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: "begin", label: "The bucket" },
    { id: "charging", label: "Charge" },
    { id: "discharging", label: "Drain" },
    { id: "time-constant", label: kids ? "How fast" : "τ = RC" },
    { id: "predict", label: "Predict" },
    { id: "playground", label: "Playground" },
    ...(kids ? [] : [{ id: "example", label: "Flash" }]),
    { id: "practice", label: "Practice" },
    { id: "quiz", label: "Quiz" },
    { id: "whats-next", label: "What's next" },
  ];
  return (
    <>
      <ChapterStartMarker chapterN="04" />
      <ProgressBar />
      <TopBar currentN="04" chapterLabel="Ch. 04 — The Bucket"
              audience={t.audience}
              setAudience={(v) => setTweak("audience", v)} />
      <ChapterNav items={navItems} />
      <main>
        <CoverPage chapterN="04"
                   chapterTitle={<>The <em>Bucket</em>.</>}
                   chapterSub="Chapter 4 · Capacitors and time"
                   kids={kids}
                   lede={kids
                     ? <>So far, water just flows. Now we'll learn how to <em>hold</em> some — like filling a bucket. A capacitor is a bucket for electricity.</>
                     : <>The first three chapters were all about steady state. This one is about <em>time</em>. A capacitor can hold charge, so the present depends on the past. Welcome to dynamics.</>
                   } />
        <LessonScrollyteller showCircuit={t.showCircuit} kids={kids} />

        <CheckpointQuiz kids={kids} label="Checkpoint 1" pick={2}
          title={kids ? "Quick check!" : "Did it stick?"}
          questions={[
            {
              q: "A bigger bucket (more C) behind the same pinch…",
              options: ["Takes longer to fill", "Fills faster", "Can't fill at all", "Fills instantly"],
              correct: 0,
              explain: kids ? "More bucket to fill through the same skinny squeeze = a longer wait. Big bucket, slow clock."
                            : "τ = R·C. Growing C at fixed R stretches the time constant — more charge to deliver through the same restriction.",
            },
            {
              q: "You loosen the pinch while the bucket drains. It empties…",
              options: ["Faster — more flow at the same level", "Slower", "At the same speed", "Not at all"],
              correct: 0,
              explain: kids ? "A wider opening lets the bucket's water rush out quicker — the squeeze was the only thing slowing it down."
                            : "Discharge current is V_cap/R. Lower R, bigger current, faster drain — τ = R·C shrinks.",
            },
            {
              q: "Why does the bucket fill fast at first, then slow to a crawl?",
              options: ["As it fills, its own level pushes back — less difference, less flow", "The water gets tired", "The pinch tightens by itself", "The barrel empties"],
              correct: 0,
              explain: kids ? "When the bucket is nearly as full as the barrel is high, there's hardly any push left to drive water in. The last bit takes forever."
                            : "Charging current rides the DIFFERENCE: I = (V_in − V_cap)/R. As V_cap approaches V_in the drive collapses — that's the exponential's long tail.",
            },
            {
              q: "Close BOTH valves on a full bucket. An hour later it is…",
              options: ["Still full — it holds its level", "Empty", "Half full", "Overflowing"],
              correct: 0,
              explain: kids ? "No way in, no way out — the bucket just sits there holding its water. That's the whole point of a bucket!"
                            : "With no discharge path, the charge has nowhere to go. Capacitors hold their voltage — which is also why big ones deserve respect.",
            },
          ]} />

        <WorkedExampleSection kids={kids} />

        <CheckpointQuiz kids={kids} label="Checkpoint 2" pick={2}
          title={kids ? "Spot it in real life!" : "Out in the wild."}
          intro={kids ? "Buckets are hiding in almost every gadget you own." : "The bucket, dressed as everyday electronics."}
          questions={[
            {
              q: "A camera flash whines for a few seconds before it's ready. What's happening?",
              options: ["It's filling a bucket slowly, to dump it all at once", "It's warming up the bulb", "It's compressing air", "It's downloading the photo"],
              correct: 0,
              explain: kids ? "The little battery can't make a big flash by itself — so it fills a bucket, then tips the WHOLE bucket out in a single bright splash."
                            : "A small battery charges a capacitor over seconds, which then discharges in microseconds — same energy, enormously higher power. Buckets trade time for punch.",
            },
            {
              q: "You unplug a gadget and its power light fades out slowly instead of dying instantly. Why?",
              options: ["A capacitor inside is still draining, like a bucket emptying through the circuit", "Electricity is stuck in the wires", "The LED stores light", "The switch is broken"],
              correct: 0,
              explain: kids ? "The gadget's bucket was full when you pulled the plug — the light keeps sipping from it until the bucket runs dry."
                            : "The supply's smoothing capacitors keep feeding the circuit after disconnect, decaying on their R·C curve — the fade IS the discharge curve.",
            },
            {
              q: "Power supplies put a big capacitor right at their output to…",
              options: ["Smooth the bumps — a bucket keeps the level steady between pours", "Add more push", "Block all current", "Save money on wire"],
              correct: 0,
              explain: kids ? "When the pours come in gulps, a bucket in the middle keeps the stream out the bottom nice and even."
                            : "The cap rides through the gaps between the rectified peaks (the one-way bumps left once the valves have straightened AC — chapter 7's job): it tops up on each crest and supplies the load — the thing being powered — in the troughs. Ripple smoothing.",
            },
            {
              q: "Old TV repair manuals warn about the insides even when UNPLUGGED, because…",
              options: ["Big buckets (capacitors) can stay full long after the power is cut", "Metal stays magnetic", "Wires hold their heat", "Screens store sunlight"],
              correct: 0,
              explain: kids ? "Remember the closed-valve bucket? Big ones can stay full for a long time — and dump on whoever touches them. Always assume full!"
                            : "High-voltage caps with no bleed path hold their charge for minutes to days. Technicians discharge them deliberately before reaching in.",
            },
          ]} />

        <PracticeProblems chapterN="04" kids={kids} problems={[
          (rng) => {
            const k = rng.pick([1, 2, 4.7, 10, 22]), uf = rng.pick([10, 47, 100, 220, 470]);
            const tau = +(k * 1000 * uf * 1e-6).toFixed(3);
            return {
              q: { adult: `A ${k} kΩ resistor charges a ${uf} µF capacitor. What is the time constant τ? (Answer in seconds.)`, kids: `A pinch of ${k * 1000} fills a bucket of ${uf} millionths. Time = pinch × bucket. (Answer in seconds.)` },
              unit: "s", answer: tau, tol: 0.05,
              hint: "\u03c4 = R × C, with R in ohms and C in farads.",
              solution: { adult: `\u03c4 = R × C = ${k * 1000} Ω × ${+(uf * 1e-6).toPrecision(6)} F = ${tau} s.`, kids: `${k * 1000} × ${+(uf * 1e-6).toPrecision(6)} = ${tau} seconds.` } };
          },
          (rng) => {
            const n = rng.pick([1, 2, 3]);
            const pctMap = { 1: 63, 2: 86, 3: 95 };
            return {
              q: { adult: `After exactly ${n === 1 ? "one time constant" : n + " time constants"}, roughly what percentage of the supply voltage has the capacitor reached?`, kids: `After ${n} 'time-step${n > 1 ? "s" : ""},' about how full is the bucket — what percent?` },
              unit: "%", answer: pctMap[n], tol: 0.12,
              hint: "Each \u03c4 closes ~63% of the remaining gap: 63%, 86%, 95%…",
              solution: { adult: `After ${n} \u03c4 a capacitor reaches ~${pctMap[n]}% of the supply.`, kids: `About ${pctMap[n]}% full after ${n} time-step${n > 1 ? "s" : ""}.` } };
          },
          (rng) => {
            const uf = rng.pick([100, 220, 470, 1000]), v = rng.int(5, 15, 1);
            const mc = +(uf * 1e-6 * v * 1000).toFixed(2);
            return {
              q: { adult: `How much charge sits on a ${uf} µF capacitor at ${v} V? (Answer in millicoulombs.)`, kids: `A bucket of ${uf} millionths filled to ${v}. Charge = bucket × push. (Answer in thousandths.)` },
              unit: "mC", answer: mc, tol: 0.04,
              hint: "Q = C × V, then ×1000 for mC.",
              solution: { adult: `Q = C × V = ${+(uf * 1e-6).toPrecision(6)} F × ${v} V = ${+(uf * 1e-6 * v).toFixed(5)} C = ${mc} mC.`, kids: `${+(uf * 1e-6).toPrecision(6)} × ${v} = ${+(uf * 1e-6 * v).toFixed(5)} → ${mc} thousandths.` } };
          },
        ]} />

        <ChapterQuiz
          chapterN="04"
          title={kids ? "Quick quiz!" : "Check your understanding."}
          intro={kids
            ? "Five quick questions about buckets and filling. Try as often as you like."
            : "Five questions on capacitors and the RC time constant. 70% to pass; retry freely."}
          questions={kids ? KIDS_QUIZ : ADULT_QUIZ}
          pick={5}
        />
        <div className="section" style={{ paddingTop: 0 }}>
          <div className="section-inner">
            <p className="lede" style={{ maxWidth: "46em", color: "var(--ink-soft)" }}>
              {kids
                ? <>Try it: open <b>The Sandbox</b>, load <b>“Capacitor (RC)”</b> and watch the charges pile in and slow to a stop as the bucket fills. Then try <b>“Charge &amp; flash”</b> — fill it, then dump it through a light.</>
                : <>See it move: in <b>The Sandbox</b>, the <b>RC</b> example shows the charging current taper to zero as V<sub>C</sub> rises; <b>Charge &amp; flash</b> stores energy, then dumps it through an LED. Drop a probe on the cap to scope V(t).</>}
            </p>
            <a className="wn-link" href="flow-sandbox.html?ex=rc" style={{ display: "inline-block", marginTop: 8 }}>Open The Sandbox →</a>
          </div>
        </div>
        <WhatsNext currentN="04" kids={kids}
          summary={kids
            ? <>Buckets and pipes. Now you've got memory in your circuits.</>
            : <>Capacitors give your circuits a sense of time. Coupled with R, they filter, delay, smooth, and store. Next: a brutally simple component that built the entire digital world.</>}
          prevHref="chapter3.html"
          prevLabel="Chapter 3"
          nextHref="chapter5.html"
          nextLabel="Chapter 5 · The Switch" />
      </main>
      <TweaksPanel title="Tweaks">
        <CommonTweaks t={t} setTweak={setTweak}
          animationToggles={[{ key: "showCircuit", label: "Show circuit" }]} />
      </TweaksPanel>
      <GlossaryFab />
    </>
  );
}

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