/* chapter3.jsx — Chapter 3: Power & Heat
   Uses HeatedPipeScene + BulbHeatScene (from visuals3.jsx).
   Helpers 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 What is power" ref={ref}>
      <div className="beat-marker">§ 02 · what is power?</div>
      {kids ? (
        <>
          <h2 className="serif">Power means<br/><em>stuff happening</em>.</h2>
          <p className="lede">
            A weak flashlight uses a little power. A toaster uses a lot. A jet
            engine uses an <em>enormous</em> amount.
          </p>
          <p>
            We measure power in <span className="mono">watts (W)</span>. The bigger
            the watts, the more is going on — more light, more heat, more spin.
          </p>
        </>
      ) : (
        <>
          <h2 className="serif">Power = work, <em>per second</em>.</h2>
          <p className="lede">
            One watt is one joule of energy delivered every second. A 60-watt
            bulb dumps 60 joules per second into the room (mostly as heat, in
            the case of an old incandescent).
          </p>
          <p>
            In an electrical context, power is the simplest possible quantity:
          </p>
          <div className="eq" style={{ fontSize: 48, margin: "18px 0" }}>
            <span style={{ color: "var(--ink)" }}>P</span>
            <span className="op">=</span>
            <span className="V">V</span>
            <span className="op">×</span>
            <span className="I">I</span>
          </div>
          <EqEase kids={kids} />
          <p>
            Volts times amps. That's it. Big push <em>and</em> big flow means
            a lot is happening; either alone doesn't.
          </p>
          <div className="marg" style={{ marginTop: 14 }}>
            Named for James Watt, the Scottish engineer who improved the steam
            engine. (Yes, his unit is named after him. Also his name is on
            every light bulb you've ever owned.)
          </div>
        </>
      )}
      <div className="pull">
        {kids ? "Lots of watts → lots of stuff happening." : "Watts is the answer to “how much, how fast?”"}
      </div>
    </div>
  );
}

function ThreeWaysBeat({ v, r, onView, kids }) {
  const ref = useInViewCallback(onView);
  const I = v / r;
  const P = v * I;
  if (kids) {
    return (
      <div className="beat" id="three-ways" data-screen-label="03 Heat" ref={ref}>
        <div className="beat-marker">§ 03 · the heat is real</div>
        <h2 className="serif">A pinch in the pipe<br/>gets <em>warm</em>.</h2>
        <p className="lede">
          Right now the bulb is glowing at <span className="mono" style={{ color: "var(--current)" }}>{fmt(P, 1)} watts</span>.
          The little thermometer right at the pinch shows it heating up — the heat
          happens <em>where the squeeze is</em>, not at the end of the pipe.
        </p>
        <p>
          At the end of the pipe the water isn't hot — it's just moving. There it
          turns a <em>wheel</em>: that's the useful work. Heat at the pinch,
          work at the wheel.
        </p>
        <p>
          The tighter the pinch, the hotter it gets. The bigger the push,
          the hotter it gets. <em>Both</em> matter.
        </p>
        <p>
          A toaster is a <em>very</em> tight pinch with lots of push behind it —
          on purpose, so it gets bright orange and warms your bread. A wire is
          a wide pipe, so it barely heats up at all.
        </p>
      </div>
    );
  }
  return (
    <div className="beat" id="three-ways" data-screen-label="03 Three forms" ref={ref}>
      <div className="beat-marker">§ 03 · three faces of the same law</div>
      <h2 className="serif">One law, <em>three ways</em>.</h2>
      <p className="lede">
        Combine P = V·I with Ohm's law (V = I·R) and the same fact pops out
        in three convenient shapes. Use whichever you have the numbers for:
      </p>
      <div className="eq-three">
        {[
          { eq: <><span>P</span><span className="op">=</span><span className="V">V</span><span className="op">·</span><span className="I">I</span></>,
            when: "You know V & I." },
          { eq: <><span>P</span><span className="op">=</span><span className="I">I</span><span style={{ fontSize: "0.6em", verticalAlign: "super" }}>2</span><span className="op">·</span><span className="R">R</span></>,
            when: "You know I & R." },
          { eq: <><span>P</span><span className="op">=</span><span className="frac"><span><span className="V">V</span><span style={{ fontSize: "0.6em", verticalAlign: "super" }}>2</span></span><span className="bar"></span><span className="R">R</span></span></>,
            when: "You know V & R." },
        ].map((x, i) => (
          <div key={i} className="card" style={{ textAlign: "center", padding: "20px 14px", background: "transparent" }}>
            <div className="eq" style={{ fontSize: 32, justifyContent: "center" }}>{x.eq}</div>
            <div className="marg" style={{ marginTop: 12, margin: "12px auto 0" }}>{x.when}</div>
          </div>
        ))}
      </div>
      <div className="card" style={{ marginTop: 24, background: "transparent", padding: "18px 22px" }}>
        <div className="eyebrow" style={{ marginBottom: 10 }}>right now · all three agree</div>
        <div className="mono" style={{ fontSize: 17, lineHeight: 1.7 }}>
          V·I = {fmt(v, 1)} × {fmt(I, 2)} = <span style={{ color: "var(--current)" }}>{fmt(P, 1)} W</span><br/>
          I²·R = {fmt(I * I, 2)} × {fmt(r, 1)} = <span style={{ color: "var(--current)" }}>{fmt(I * I * r, 1)} W</span><br/>
          V²/R = {fmt(v * v, 0)} ÷ {fmt(r, 1)} = <span style={{ color: "var(--current)" }}>{fmt((v * v) / r, 1)} W</span>
        </div>
      </div>
    </div>
  );
}

function HeatBeat({ v, r, onView, kids }) {
  const ref = useInViewCallback(onView);
  const P = (v * v) / r;
  return (
    <div className="beat" id="heat" data-screen-label="04 Heat" ref={ref}>
      <div className="beat-marker">§ 04 · where it all goes</div>
      <h2 className="serif">Almost everything<br/>becomes <em>heat</em>.</h2>
      {kids ? (
        <>
          <p className="lede">
            Here's the secret: nearly all electricity, somewhere along the way,
            turns into <em>heat</em>. Even the light from a regular bulb is
            mostly heat — only a little becomes light.
          </p>
          <p>
            That's why a phone gets warm when it's working hard. Why your
            laptop has a little fan. Why a hairdryer feels nice on cold
            mornings — that's the whole point!
          </p>
        </>
      ) : (
        <>
          <p className="lede">
            Every electron that pushes through a resistor jostles its way
            past atoms, and those bumps add up to heat. Old incandescent
            bulbs are ~5% light, 95% heat — the filament glows because it's
            hot enough to <em>emit visible light</em>. The light is a side-effect.
          </p>
          <p>
            This is why power matters in design:
          </p>
          <ul style={{ paddingLeft: 22, lineHeight: 1.7 }}>
            <li>A resistor needs a <em>power rating</em> high enough to handle the heat without melting.</li>
            <li>A laptop CPU has a <em>heat sink</em> bolted to it for exactly this reason.</li>
            <li>An LED is so efficient (~30% of power becomes light) it can run cool on a coin cell.</li>
          </ul>
          <div className="card" style={{ marginTop: 24, background: "transparent" }}>
            <div className="eyebrow" style={{ marginBottom: 8 }}>this resistor is dissipating</div>
            <div className="eq" style={{ fontSize: 30 }}>
              <span style={{ color: "var(--ink)" }}>P</span>
              <span className="op">=</span>
              <span className="num">{fmt(P, 1)}</span>
              <span className="op" style={{ fontSize: 18 }}>watts</span>
            </div>
            <div className="eyebrow" style={{ margin: "18px 0 8px" }}>resistor power ratings · how much heat a part can shed</div>
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
              {[{ w: 0.125, label: "⅛ W" }, { w: 0.25, label: "¼ W" }, { w: 0.5, label: "½ W" }, { w: 1, label: "1 W" }, { w: 5, label: "5 W · power" }].map(rt => {
                const ok = P <= rt.w;
                return (
                  <span key={rt.label} className="mono" style={{
                    padding: "7px 13px", borderRadius: 999, fontSize: 12.5, letterSpacing: "0.05em",
                    border: `1.5px solid ${ok ? "var(--water)" : "var(--rule-strong)"}`,
                    color: ok ? "var(--water)" : "var(--ink-faint)",
                    textDecoration: ok ? "none" : "line-through",
                  }}>{rt.label}</span>
                );
              })}
            </div>
            <div className="marg" style={{ marginTop: 12 }}>
              A rating isn't resistance — it's a <em>heat budget</em>. A bigger body sheds
              heat faster, so it survives more watts. The common little ones on a breadboard
              are ¼ W. Crossed-out sizes above would cook at today's {fmt(P, 1)} W —
              {P > 5 ? " even a 5 W power resistor isn't enough; you'd need a heatsink." : P > 0.25 ? " pick one of the surviving sizes." : " any of them would survive this."}
            </div>
          </div>
        </>
      )}
    </div>
  );
}

function PlaygroundBeat({ v, r, setV, setR, onView, kids }) {
  const ref = useInViewCallback(onView);
  const I = v / r;
  const P = v * I;
  return (
    <div className="beat" id="playground" data-screen-label="05 Playground" ref={ref}>
      <div className="beat-marker">§ 05 · turn it up</div>
      <h2 className="serif">Crank it.<br/>Watch it <em>heat up</em>.</h2>
      <p className="lede">
        {kids
          ? "Push hard and squeeze tight at the same time. The bulb glows brighter, the thermometer at the pinch climbs, and the wheel at the end spins faster."
          : "Push harder or squeeze tighter — either grows power. The pinch's thermometer and the wheel's spin both respond live."
        }
      </p>
      <div style={{ marginTop: 24, display: "flex", flexDirection: "column", gap: 6 }}>
        <Slider name="Voltage · push" value={v} min={0} max={12} step={0.5}
                unit="V" accent="water" onChange={setV} />
        <Slider name="Resistance · squeeze" value={r} min={0.5} max={10} step={0.1}
                unit="Ω" accent="" onChange={setR} />
      </div>
      <div className="card" style={{ marginTop: 22, background: "transparent" }}>
        <div className="eyebrow" style={{ marginBottom: 10 }}>{kids ? "right now" : "power"}</div>
        {kids ? (
          <p style={{ margin: 0, fontSize: 18 }}>
            <span className="mono" style={{ color: "var(--current)" }}>{fmt(P, 1)} watts</span> of glow.
            The pipe is at about <span className="mono">{P > 12 ? "scalding" : P > 6 ? "hot" : P > 2 ? "warm" : "barely warm"}</span>.
          </p>
        ) : (
          <div className="eq" style={{ fontSize: 28 }}>
            <span style={{ color: "var(--ink)" }}>P</span>
            <span className="op">=</span>
            <span className="V">V</span>
            <span className="op">·</span>
            <span className="I">I</span>
            <span className="op" style={{ marginLeft: 16 }}>=</span>
            <span className="num">{fmt(P, 1)}</span>
            <span className="op" style={{ fontSize: 18 }}>W</span>
          </div>
        )}
      </div>

      <div className="card" style={{ marginTop: 18, background: "var(--bg-card)", borderLeft: "3px solid var(--current)" }}>
        <div className="eyebrow" style={{ marginBottom: 8, color: "var(--current)" }}>why does squeezing make heat?</div>
        <p style={{ margin: 0, fontSize: 15, color: "var(--ink-soft)" }}>
          {kids
            ? <>When water shoves past a tight spot, it bumps and rubs — and those bumps <em>are</em> heat. In a wire, electrons bump into the metal atoms as they squeeze through, and every bump warms it up.</>
            : <>Drop the resistor and the wire lets <em>more</em> current through — so far more electrons crowd past the metal atoms each second. More electrons jostling means more collisions per second, and each collision sheds heat. (P = I²R captures it: R falls but I climbs faster.)</>}
        </p>
        <p style={{ margin: "10px 0 0", fontSize: 13.5, color: "var(--ink-faint)" }}>
          <b style={{ color: "var(--ink-soft)" }}>Power vs. energy — watch the wheel.</b> The waterwheel at the
          end of the pipe is the <em>load</em> — the thing the flow actually drives.
          How <em>fast</em> it spins right now is <b style={{ color: "var(--ink-soft)" }}>power</b> (watts).
          The counter under it — total energy delivered so far — is <b style={{ color: "var(--ink-soft)" }}>energy</b> (joules
          = watts × seconds). Turn the power down and the wheel slows, but the counter{" "}
          <em>keeps climbing</em> — a trickle for a long time can deliver more energy than a blast for a moment.
          That counter is exactly what your electricity bill meters (in kWh).
        </p>
      </div>

      <div className="rule">household presets</div>
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
        {[
          { label: "LED indicator", v: 3, r: 10 },     // ~0.9 W
          { label: "Phone charger", v: 5, r: 2.5 },    // 10 W
          { label: "Old bulb-ish",  v: 12, r: 2.5 },   // ~57 W (scaled)
          { label: "Toaster-ish",   v: 12, r: 0.8 },   // ~180 W (scaled)
        ].map(p => (
          <button key={p.label}
                  onClick={() => { setV(p.v); setR(p.r); }}
                  style={{
                    appearance: "none", border: "1px solid var(--rule-strong)",
                    background: "transparent", padding: "8px 14px",
                    borderRadius: 999, fontFamily: "'IBM Plex Mono', monospace",
                    fontSize: 11, letterSpacing: "0.06em", color: "var(--ink-soft)",
                    cursor: "pointer",
                  }}>
            {p.label}
          </button>
        ))}
      </div>
    </div>
  );
}

/* ─── LessonScrollyteller ───────────────────────────────────────────────── */
function LessonScrollyteller({ showCircuit, kids }) {
  const [v, setV] = useState(8);
  const [r, setR] = useState(3);
  const [mode, setMode] = useState("cover");
  const I = v / r;
  const P = v * I;
  const visHeight = showCircuit ? 330 : 475;

  return (
    <section className="lesson" data-mode={mode}>
      <div className="lesson-scroll">
        <BigIdeaBeat onView={() => setMode("big-idea")} kids={kids} />
        <ThreeWaysBeat v={v} r={r} onView={() => setMode("three-ways")} kids={kids} />
        <HeatBeat v={v} r={r} onView={() => setMode("heat")} kids={kids} />
        <PlaygroundBeat v={v} r={r} setV={setV} setR={setR} onView={() => setMode("playground")} kids={kids} />
      </div>
      <aside className="lesson-sticky" data-single={showCircuit ? "0" : "1"}>
        {showCircuit && <VisTabs labels={["WATER", "LOOP"]} />}
        <div className="vis-block">
          <div className="stage-label">WATER · pinch heats up · wheel does the work</div>
          <HeatedPipeScene voltage={v} resistance={r} height={visHeight} kids={kids} />
        </div>
        {showCircuit && (
          <div className="vis-block">
            <div className="stage-label">THE LOOP · power burns at the pinch</div>
            <LoopScene3 v={v} r={r} kids={kids} />
          </div>
        )}
        <div className="vis-readout">
          <div className="ro-v">
            <span className="ro-name">{kids ? "Push" : "Voltage"}</span>
            <span className="ro-val">{fmt(v, 1)}<span className="ro-unit">V</span></span>
          </div>
          <div className="ro-r">
            <span className="ro-name">{kids ? "Squeeze" : "Resistance"}</span>
            <span className="ro-val">{fmt(r, 1)}<span className="ro-unit">Ω</span></span>
          </div>
          <div className="ro-i">
            <span className="ro-name">{kids ? "Flow" : "Current"}</span>
            <span className="ro-val">{fmt(I, 2)}<span className="ro-unit">A</span></span>
          </div>
          <div className="ro-p ro-active">
            <span className="ro-name">Power</span>
            <span className="ro-val">{fmt(P, 1)}<span className="ro-unit">W</span></span>
          </div>
        </div>
      </aside>
    </section>
  );
}

/* ─── Worked example: car battery & headlights (DC) ──────────────────── */
function WorkedExampleSection({ kids }) {
  if (kids) return null;
  return (
    <section className="section" id="example" data-screen-label="07 Car battery">
      <div className="marker">§ 07 · a 12 V car battery, in practice</div>
      <div className="section-inner">
        <div className="two-col">
          <div>
            <h2 className="serif">A practical story:<br/><em>your car</em>.</h2>
            <p className="lede">
              A car battery is a <span className="mono">12 V</span> reservoir of DC —
              same shape as the barrel-and-pipe we've been drawing. Every accessory
              draws current from it. The total power budget matters a lot,
              because a flat battery means you're walking.
            </p>
            <p>
              Three DC loads, one fully-charged 12 V battery:
            </p>
          </div>
          <div>
            <div className="card" style={{ padding: "24px 26px" }}>
              {[
                { name: "Headlights (low beam)", v: 12, i: 9.0 },   // ~108 W
                { name: "Cabin fan, medium",     v: 12, i: 3.0 },   // ~36 W
                { name: "Phone charger",          v: 12, i: 1.7 },   // ~20 W
                { name: "Stereo, modest volume",  v: 12, i: 1.5 },   // ~18 W
                { name: "Dome light",             v: 12, i: 0.5 },   // ~6 W
              ].map(a => (
                <div key={a.name} style={{
                  display: "grid", gridTemplateColumns: "1fr auto auto auto",
                  gap: 12,
                  padding: "10px 0", borderTop: "1px solid var(--rule)",
                  alignItems: "baseline",
                }}>
                  <span>{a.name}</span>
                  <span className="mono" style={{ color: "var(--water)" }}>{a.v} V</span>
                  <span className="mono" style={{ color: "var(--current)" }}>{a.i} A</span>
                  <span className="mono" style={{ minWidth: 56, textAlign: "right" }}>{(a.v * a.i).toFixed(0)} W</span>
                </div>
              ))}
              <div style={{
                display: "grid", gridTemplateColumns: "1fr auto",
                padding: "14px 0 0", borderTop: "2px solid var(--rule-strong)",
                marginTop: 6, alignItems: "baseline"
              }}>
                <span className="eyebrow">Everything on at once:</span>
                <span className="mono" style={{ color: "var(--current)" }}>~188 W · 15.7 A</span>
              </div>
              <p className="marg" style={{ marginTop: 14 }}>
                A typical car battery holds <span className="mono">~50 Ah</span> of charge.
                At <span className="mono">15.7 A</span>, that's roughly <span className="mono">3 hours</span> of
                "everything on" before it's flat. Which is why you don't leave the
                lights on overnight.
              </p>
            </div>
            <div className="marg" style={{ marginTop: 20 }}>
              <em>Note on units.</em> Amp-hours (Ah) is a sloppy but practical capacity unit —
              how much current the battery can supply for how long. 50 Ah × 12 V ≈ 600 Wh of
              stored energy. We'll meet Wh again in Chapter 4 (capacitors store the same kind
              of thing, much less of it, much faster).
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─── WhatsNext handled by shared component ──────────────────────────── */

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

/* ─── Where the heat lives — the push budget ────────────────────── */
function HeatBudgetSection({ kids }) {
  const [rPinch, setRPinch] = useState(3);
  const rLamp = 6, V = 9;
  const I = V / (rPinch + rLamp);
  const pPinch = I * I * rPinch;
  const pLamp = I * I * rLamp;
  const maxP = (V * V) / rLamp;          // all power lands in the lamp at rPinch = 0
  const bar = (p) => `${Math.max(1.5, (p / maxP) * 100)}%`;
  return (
    <section className="section" id="heat-budget" data-screen-label="06 Heat moves">
      <div className="marker">§ 06 · the heat has an address</div>
      <div className="section-inner">
        <div className="two-col">
          <div>
            <h2 className="serif">The heat doesn't vanish.<br/>It <em>moves house</em>.</h2>
            <p className="lede">
              {kids
                ? <>Squeeze the pinch tight: the <em>pinch</em> gets hot and the bulb goes dim. Open it wide: the <em>bulb</em> blazes bright — and warm! Either way something heats up. The heat just changes address.</>
                : <>Tighten the pinch and <em>it</em> heats up while the lamp starves. Open it wide and the lamp blazes — now the <em>lamp</em> is where the power lands. Resistance doesn't make heat go away; it decides where the heat shows up.</>}
            </p>
            <p>
              {kids
                ? <>The rule is simple: heat appears wherever the push gets <em>used up</em>. Whoever takes the biggest share of the push collects the most heat. A bulb glowing IS heat — that's the part doing the useful work.</>
                : <>The rule: heat lands wherever push is dropped. In a series loop, parts split the voltage in proportion to their resistance — the pinch's share warms the pinch, the lamp's share lights (and warms) the lamp. One honest catch: tightening the pinch also shrinks the <em>total</em> flow, so the whole heat budget gets smaller even as the pinch claims a bigger slice of it.</>}
            </p>
            <div className="marg" style={{ marginTop: 14 }}>
              {kids
                ? <>A toaster and a dim lamp obey the same rule — the only question is <em>where</em> you want the heat to show up.</>
                : <>A space heater and a dimmed lamp are the same physics. Engineering is mostly choosing the address: put the drop where the work is useful, keep it away from where it isn't.</>}
            </div>
          </div>
          <div>
            <div className="card" style={{ padding: "24px 26px" }}>
              <div className="eyebrow" style={{ marginBottom: 14 }}>try it · 9 V barrel · lamp fixed at 6 Ω</div>
              <Slider name={kids ? "How tight is the pinch?" : "R · pinch"} value={rPinch} min={0} max={20} step={0.5}
                      unit={kids ? "" : " Ω"} accent="" onChange={setRPinch} />
              {[{ label: kids ? "heat at the pinch" : "heat at the pinch · I²Rₚ", p: pPinch },
                { label: kids ? "heat & light at the bulb" : "heat & light at the lamp · I²Rₗ", p: pLamp }].map((row, i) => (
                <div key={i} style={{ marginTop: i ? 14 : 18 }}>
                  <div style={{ display: "flex", justifyContent: "space-between", fontFamily: "IBM Plex Mono, monospace", fontSize: 12.5, color: "var(--ink-soft)", marginBottom: 5 }}>
                    <span>{row.label}</span>
                    <span style={{ color: "var(--current-deep)" }}>{row.p.toFixed(1)} W</span>
                  </div>
                  <div style={{ height: 12, background: "var(--bg-deeper)", border: "1px solid var(--rule)", borderRadius: 2 }}>
                    <div style={{ height: "100%", width: bar(row.p), background: i === 0 ? "var(--current)" : "var(--current-deep)", transition: "width 160ms ease" }}></div>
                  </div>
                </div>
              ))}
              <div className="branch-readout" style={{ marginTop: 16 }}>
                <span>{kids ? "total heat being made" : "total · P = V²/(Rₚ+Rₗ)"}</span>
                <span className="mono"><b style={{ color: "var(--current-deep)" }}>{(pPinch + pLamp).toFixed(1)} W</b></span>
              </div>
              <div className="marg" style={{ marginTop: 12 }}>
                {kids
                  ? <>Slide it! Tight pinch: the pinch wins the heat (and there's less heat overall). Open pinch: the bulb gets everything.</>
                  : <>Watch both effects at once: the pinch's <em>share</em> grows as you tighten, while the <em>total</em> shrinks. At Rₚ = 0, every watt lands in the lamp.</>}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─── Battery capacity: mAh — the size of the barrel ────────────────── */

/* Two barrels filled to the same height — one skinny, one fat. Same push
   (height), wildly different capacity (girth). AAA vs D cell, drawn. */
function TwoBarrelsFigure({ kids }) {
  const top = 54, bot = 240, fillF = 0.8;
  const waterY = top + (1 - fillF) * (bot - top);
  return (
    <svg viewBox="0 0 460 300" width="100%"
         style={{ display: "block", maxWidth: 460, margin: "18px 0 4px" }}>
      {renderBarrel({ cx: 100, top, bot, rimRx: 28, midRx: 35, fill: fillF, idSuffix: "mah-thin", deepWater: true })}
      {renderBarrel({ cx: 300, top, bot, rimRx: 86, midRx: 106, fill: fillF, idSuffix: "mah-fat", deepWater: true })}
      {/* shared water line — the whole point of the figure */}
      <line x1="40" y1={waterY} x2="428" y2={waterY}
            stroke="var(--ink-faint)" strokeWidth="1.2" strokeDasharray="4 5" />
      <text x="166" y="26" textAnchor="middle" fontFamily="IBM Plex Mono, monospace"
            fontSize="15" fill="var(--ink-soft)" letterSpacing="0.1em">
        SAME HEIGHT = SAME PUSH
      </text>
      <line x1="166" y1="34" x2="166" y2={waterY - 4}
            stroke="var(--ink-faint)" strokeWidth="1" strokeDasharray="2 4" />
      <text x="100" y={bot + 30} textAnchor="middle" fontFamily="IBM Plex Mono, monospace"
            fontSize="16.5" fontWeight="600" fill="var(--ink-soft)">AAA · 1.5 V</text>
      <text x="100" y={bot + 50} textAnchor="middle" fontFamily="IBM Plex Mono, monospace"
            fontSize="14.5" fill="var(--ink-faint)">{kids ? "runs dry fast" : "~1,000 mAh"}</text>
      <text x="300" y={bot + 30} textAnchor="middle" fontFamily="IBM Plex Mono, monospace"
            fontSize="16.5" fontWeight="600" fill="var(--ink-soft)">D · 1.5 V</text>
      <text x="300" y={bot + 50} textAnchor="middle" fontFamily="IBM Plex Mono, monospace"
            fontSize="14.5" fill="var(--ink-faint)">{kids ? "keeps going & going" : "~12,000 mAh"}</text>
    </svg>
  );
}

function BatteryCapacitySection({ kids }) {
  const [drawMa, setDrawMa] = useState(50);
  const capacity = 500;                       // a typical 9 V alkaline, in mAh
  const hours = capacity / drawMa;
  const hLabel = hours >= 48 ? `${(hours / 24).toFixed(1)} days` : `${hours.toFixed(1)} hours`;
  return (
    <section className="section" id="battery-life" data-screen-label="08 Battery life">
      <div className="marker">§ {kids ? "07" : "08"} · how long will the barrel last?</div>
      <div className="section-inner">
        <div className="two-col">
          <div>
            <h2 className="serif">The barrel has<br/>a <em>size</em>.</h2>
            <p className="lede">
              {kids
                ? <>Volts tell you how hard the barrel pushes — but not how much water is <em>in</em> it. A battery's size is written in <span className="mono">mAh</span>, and it works just like litres in a barrel.</>
                : <>Voltage is the <em>height</em> of the barrel — the push. <span className="mono">mAh</span> (milliamp-hours) is the <em>girth</em> — how much water it holds. Capacity, not pressure. Two batteries can push identically and last wildly different lengths of time.</>}
            </p>
            <p>
              {kids
                ? <>Picture a skinny barrel and a fat barrel filled to the same height. The water squirts out of both <em>just as hard</em> — the push only cares about how high the water is! But the skinny one runs dry fast, while the fat one keeps pouring and pouring. That's a little AAA battery next to a big chunky D battery: the exact same push, just way more water inside the big one.</>
                : <>Picture two barrels filled to the same height — one skinny, one fat. A pressure gauge at each spigot reads <em>identically</em>: pressure cares about height, not girth. But open the taps and the skinny one runs dry while the fat one is still pouring. That's a AAA next to a D cell — both 1.5 V, both light a bulb to the exact same brightness. The D just holds roughly ten times the charge, so it keeps that push up ten times longer.</>}
            </p>
            <TwoBarrelsFigure kids={kids} />
            <p>
              {kids
                ? <>One more battery secret: as a battery gets used up, it doesn't just hold less water — it gets <em>worse at pushing</em>. It's like the barrel's own spigot slowly furring up with gunk: a tired battery has a tight built-in squeeze, so the moment something thirsty asks for a big gulp, the push droops. That's why a "dying" flashlight can still run a clock for months — the clock only sips!</>
                : <>And a depletion footnote: a draining battery doesn't just lose capacity — its <em>internal resistance</em> climbs. Picture the barrel growing its own built-in pinch that slowly tightens with age and use. An old cell can still read 1.5 V on a meter (no load, no flow, no drop across that internal pinch) yet sag badly the moment a real load draws current. That's why "dead" remote batteries still run a wall clock, and why the car cranks weakly on cold mornings — cold tightens the internal pinch further.</>}
            </p>
            <p>
              {kids
                ? <>The maths is friendly: a 500 mAh battery can pour out 500 “units” — use 50 each hour and it lasts 10 hours. Use 100 each hour, only 5. The faster you drink, the sooner it's empty.</>
                : <>Read it literally: <span className="mono">500 mAh = 500 mA for 1 hour</span>, or 50 mA for 10 hours, or 5 mA for 100 — the product stays the same. Halve the draw, double the life.</>}
            </p>
            <div className="eq" style={{ fontSize: 26, margin: "16px 0" }}>
              <span>{kids ? "how long" : "life"}</span>
              <span className="op">=</span>
              <span className="frac">
                <span>{kids ? "barrel size (mAh)" : "capacity (mAh)"}</span>
                <span className="bar"></span>
                <span>{kids ? "flow (mA)" : "draw (mA)"}</span>
              </span>
            </div>
          </div>
          <div>
            <div className="card" style={{ padding: "24px 26px" }}>
              <div className="eyebrow" style={{ marginBottom: 14 }}>try it · a 9 V battery · {capacity} mAh</div>
              <Slider name={kids ? "How thirsty is your circuit?" : "Circuit draw"} value={drawMa} min={5} max={500} step={5}
                      unit=" mA" accent="current" onChange={setDrawMa} />
              <div className="branch-readout" style={{ marginTop: 14 }}>
                <span>{kids ? "the battery lasts" : "battery life"}</span>
                <span className="mono">{capacity} ÷ {drawMa} = <b style={{ color: "var(--water)" }}>{hLabel}</b></span>
              </div>
              <div className="marg" style={{ marginTop: 12 }}>
                {kids
                  ? <>The Beacon sips about 14 mA — so one battery runs it for about a day and a half of nights!</>
                  : <>The Beacon draws ~14 mA → ~36 h on one 9 V. This is the budget you'll design against in Level 2: brightness costs current; current costs hours.</>}
              </div>
            </div>
            <div className="marg" style={{ marginTop: 16 }}>
              {kids
                ? <>Watch out: a barrel twice as tall (more volts) is NOT twice as big (more mAh). Push and size are different things!</>
                : <>mAh compares batteries of the <em>same voltage</em>. For true stored energy, multiply by volts: 500 mAh × 9 V = 4.5 Wh — watt-hours, the wheel-counter unit from above.</>}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

const ADULT_QUIZ = [
  {
    q: "Electrical power is…", kind: "math",
    options: ["V + I", "V × I", "V − I", "V ÷ I"],
    correct: 1,
    explain: "Power P = V × I. Volts times amps gives watts — the rate work happens.",
  },
  {
    q: "A device runs at 12 V and draws 2 A. Its power is…", kind: "math",
    options: ["6 W", "14 W", "24 W", "10 W"],
    correct: 2,
    explain: "P = V × I = 12 × 2 = 24 W.",
  },
  {
    q: "Most of the energy an old incandescent bulb uses becomes…", kind: "concept",
    options: ["light", "heat", "sound", "motion"],
    correct: 1,
    explain: "~95% is heat; the visible light is almost a side-effect of the hot filament.",
  },
  {
    q: "Hold voltage fixed. You lower the resistance. The power dissipated…", kind: "math",
    options: ["goes up", "goes down", "stays the same", "becomes zero"],
    correct: 0,
    explain: "P = V²/R. Lower R → more current → more power. (Same V, easier path, harder work.)",
  },
  {
    q: "Why does a resistor need a 'power rating'?", kind: "concept",
    options: [
      "To set its resistance",
      "So it can handle the heat it makes without melting",
      "To pick its color",
      "To store charge",
    ],
    correct: 1,
    explain: "Power becomes heat. Exceed the rating and the part cooks. Pick a part rated above its dissipation.",
  },
  {
    q: "A 60 W bulb on a 120 V line draws how much current?", kind: "math",
    options: ["0.5 A", "2 A", "60 A", "7200 A"],
    correct: 0,
    explain: "I = P / V = 60 / 120 = 0.5 A.",
  },
  {
    q: "Double the current through a fixed resistor. The heat it makes…", kind: "math",
    options: ["doubles", "halves", "quadruples", "stays the same"],
    correct: 2,
    explain: "P = I²R — power goes with the SQUARE of current. Double I → 4× the heat.",
  },
  {
    q: "A 500 mAh battery feeds a circuit drawing 25 mA. Roughly how long does it last?", kind: "math",
    options: ["25 minutes", "2 hours", "20 hours", "500 hours"],
    correct: 2,
    explain: "Life = capacity ÷ draw = 500 mAh ÷ 25 mA = 20 hours. mAh is the size of the barrel.",
  },
  {
    q: "A resistor's power rating (⅛ W, ¼ W, ½ W…) tells you…", kind: "concept",
    options: ["its resistance in ohms", "how much heat it can shed without cooking", "its physical length", "its voltage limit only"],
    correct: 1,
    explain: "The rating is a heat budget, set by the part's size. Dissipate more than it and the part burns up.",
  },
  {
    q: "mAh measures a battery's…", kind: "concept",
    options: ["push (pressure)", "capacity — how much charge it holds", "resistance", "temperature"],
    correct: 1,
    explain: "mAh is the barrel's SIZE, not its push. Volts are the push; mAh says how long it can keep it up.",
  },
  {
    q: "In a series loop with a pinch and a lamp, where does the heat show up?",
    kind: "concept",
    options: ["Always at the battery", "Wherever the push is dropped — each part's share warms that part", "Only in the wires", "Nowhere — it cancels out"],
    correct: 1,
    explain: "Heat lands where voltage is dropped. The pinch's share warms the pinch; the lamp's share lights (and warms) the lamp. Resistance decides the heat's address.",
  },
  {
    q: "A 'dying' flashlight battery can still run a wall clock for months. Why?",
    kind: "concept",
    options: [
      "Clocks recharge batteries",
      "A tired battery's internal resistance has climbed — big gulps make its push droop, but tiny sips are fine",
      "The clock runs on zero power",
      "Flashlights drain batteries backwards",
    ],
    correct: 1,
    explain: "As a battery depletes, its built-in squeeze tightens. A thirsty load (flashlight) makes the voltage sag; a clock only sips, so the droop barely matters.",
  },
  {
    q: "Your electricity bill charges you for…",
    kind: "concept",
    options: ["peak power (W)", "voltage (V)", "energy — power added up over time (kWh)", "current (A)"],
    correct: 2,
    explain: "The meter integrates: energy = power × time. A trickle for a long time can cost more than a blast for a moment.",
  },
  {
    q: "A AAA and a D cell are both 1.5 V. The D cell…",
    kind: "concept",
    options: ["pushes harder", "lights a bulb brighter", "holds the same push but far more charge — it lasts longer", "is more dangerous"],
    correct: 2,
    explain: "Same height of water, fatter barrel. Identical push (same brightness), roughly 10× the capacity.",
  },
];

const KIDS_QUIZ = [
  {
    q: "Power means…", kind: "concept",
    options: ["how pretty it looks", "how much stuff is happening", "how heavy it is", "what color it is"],
    correct: 1,
    explain: "Lots of watts = lots happening: more light, more heat, more spin.",
  },
  {
    q: "To make LOTS of power, you want…", kind: "concept",
    options: ["big push AND big flow", "no push", "a cold wire", "a longer wire"],
    correct: 0,
    explain: "Power is push times flow. Big push and big flow together = lots of power.",
  },
  {
    q: "When electricity does work, where does most of the energy end up?", kind: "concept",
    options: ["as heat", "as sound", "it disappears", "as water"],
    correct: 0,
    explain: "Almost everything turns into heat in the end — that's why gadgets get warm.",
  },
  {
    q: "Why does a toaster glow but a normal wire doesn't?", kind: "concept",
    options: [
      "The toaster wire squeezes the flow hard, making heat",
      "The toaster is painted orange",
      "Normal wires are broken",
      "Toasters use magic",
    ],
    correct: 0,
    explain: "A tight squeeze with lots of push makes heat — on purpose, to toast your bread.",
  },
  {
    q: "Your laptop gets warm when it works hard because…", kind: "concept",
    options: ["it's sad", "electricity turns into heat", "the sun is out", "it's full of water"],
    correct: 1,
    explain: "Working hard means using power, and power becomes heat. That's why there's a little fan!",
  },
  {
    q: "Which uses the MOST power?", kind: "concept",
    options: ["a tiny LED night-light", "a toaster", "a phone charger", "a clock"],
    correct: 1,
    explain: "A toaster! It makes lots of heat on purpose, so it uses lots of power.",
  },
  {
    q: "Watts is a way to measure…", kind: "concept",
    options: ["how much stuff is happening", "how blue something is", "how far away it is", "how old it is"],
    correct: 0,
    explain: "Watts = how much is happening. More watts, more light/heat/spin.",
  },
  {
    q: "A battery's mAh number tells you…", kind: "concept",
    options: ["how hard it pushes", "how big its barrel is — how long it lasts", "what colour it is", "how heavy it is"],
    correct: 1,
    explain: "mAh is the SIZE of the barrel. A thirstier circuit empties it faster.",
  },
  {
    q: "The wheel at the end of the pipe spins faster when…", kind: "concept",
    options: ["there's more power", "the water is colder", "the pipe is longer", "you watch it closely"],
    correct: 0,
    explain: "Spin speed = power, how fast work is happening. The counter under it adds up the energy.",
  },
  {
    q: "Where does the pipe get HOT?",
    kind: "concept",
    options: ["Right at the squeeze", "At the very start", "Nowhere", "Only at night"],
    correct: 0,
    explain: "The bumping and rubbing happens where the water squeezes past the tight spot — that's where the heat is made.",
  },
  {
    q: "A big D battery and a little AAA both push the same. What's different?",
    kind: "concept",
    options: ["The big one pushes harder", "The big one holds more water, so it lasts longer", "The little one is faster", "Nothing"],
    correct: 1,
    explain: "Same push (same brightness!) — but the fat barrel keeps pouring long after the skinny one runs dry.",
  },
];

/* ─── 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: kids ? "What's power" : "Power" },
    { id: "three-ways", label: kids ? "Heat" : "Three forms" },
    { id: "heat", label: kids ? "Why warm?" : "Where it goes" },
    { id: "playground", label: "Playground" },
    { id: "heat-budget", label: kids ? "Heat moves" : "Heat budget" },
    ...(kids ? [] : [{ id: "example", label: "Car battery" }]),
    { id: "battery-life", label: kids ? "Battery life" : "mAh" },
    { id: "practice", label: "Practice" },
    { id: "quiz", label: "Quiz" },
    { id: "whats-next", label: "What's next" },
  ];
  return (
    <>
      <ChapterStartMarker chapterN="03" />
      <ProgressBar />
      <TopBar currentN="03" chapterLabel="Ch. 03 — Power & Heat"
              audience={t.audience}
              setAudience={(v) => setTweak("audience", v)} />
      <ChapterNav items={navItems} />
      <main>
        <CoverPage chapterN="03"
                   chapterTitle={<>Power<br/>& <em>Heat</em>.</>}
                   chapterSub="Chapter 3 · How much actually happens?"
                   kids={kids}
                   lede={kids
                     ? <>When water rushes through a tight pipe, the pipe <em>warms up</em>. When electricity rushes through a resistor, it does the same. That heat is the price of getting work done.</>
                     : <>Voltage tells you the push. Current tells you the flow. Together they tell you <em>power</em> — the rate at which electricity is actually <em>doing</em> something. Almost all of it eventually becomes heat.</>
                   } />
        <LessonScrollyteller showCircuit={t.showCircuit} kids={kids} />

        <CheckpointQuiz kids={kids} label="Checkpoint 1" pick={2}
          title={kids ? "Quick check!" : "Did it stick?"}
          questions={[
            {
              q: "The wheel at the end of the pipe spins twice as fast when…",
              options: ["The power doubles — more push × flow", "The water gets warmer", "You watch it more closely", "The pipe gets longer"],
              correct: 0,
              explain: kids ? "The wheel's speed shows how fast work is happening right now — that's power: push times flow."
                            : "Spin rate tracks P = V × I, the rate of work. Double either factor (at the same other) and the wheel doubles its pace.",
            },
            {
              q: "Where does the heat show up along the pipe?",
              options: ["At the pinch — where push is lost fighting resistance", "At the barrel", "Spread evenly everywhere", "Only at the wheel"],
              correct: 0,
              explain: kids ? "The squeeze is where the water fights hardest — that fight becomes warmth, right there at the pinch."
                            : "Power dissipates where voltage is dropped. The resistor takes the drop, so it takes the I²R heat — that's why real resistors have wattage ratings.",
            },
            {
              q: "A gentle trickle for an hour vs. a huge blast for one second — which can deliver more ENERGY?",
              options: ["The trickle, if it runs long enough — energy is power × time", "Always the blast", "They're always exactly equal", "Neither delivers energy"],
              correct: 0,
              explain: kids ? "Energy is power kept up over time. A slow wheel turning all afternoon can out-work a fast wheel that only spins for a blink."
                            : "Energy = ∫P dt. A 5 W trickle for an hour is 18,000 J; a 1,000 W blast for a second is 1,000 J. The counter under the wheel keeps score.",
            },
            {
              q: kids ? "The thing your circuit is powering — the wheel here — has an engineer name. It's called…" : "In engineer-speak, the thing being powered — the wheel at the end of the pipe — is the…",
              options: ["The load", "The source", "The pinch", "The gauge"],
              correct: 0,
              explain: kids ? "The LOAD is whatever does the useful work — the wheel, a bulb, a motor. The battery is the SOURCE; everything it powers is its load."
                            : "Load = whatever consumes the power (wheel, lamp, motor, chip). 'Driving a load' just means delivering current to it — the term shows up everywhere from here on.",
            },
            {
              q: "Same pinch, but you raise the barrel's level (more push). The pinch gets…",
              options: ["Hotter — more flow forced through the same squeeze", "Cooler", "No different", "Wider on its own"],
              correct: 0,
              explain: kids ? "More push shoves more water through the same tight spot — a harder fight, more warmth."
                            : "With R fixed, raising V raises I = V/R, and heat goes as I²R — so doubling the push QUADRUPLES the pinch's heat.",
            },
          ]} />

        <HeatBudgetSection kids={kids} />
        <WorkedExampleSection kids={kids} />
        <BatteryCapacitySection kids={kids} />

        <CheckpointQuiz kids={kids} label="Checkpoint 2" pick={2}
          title={kids ? "Spot it in real life!" : "Out in the wild."}
          intro={kids ? "Power, heat, and battery size — out in your house." : "Watts, heat, and capacity in everyday objects."}
          questions={[
            {
              q: "Your phone charger feels warm while charging. That warmth is…",
              options: ["Power being lost as heat inside it — part of the bill you pay", "Electricity stored as warmth for later", "Proof it's broken", "Heat leaking out of the phone"],
              correct: 0,
              explain: kids ? "Some of the push gets used up inside the charger itself — and used-up push always shows up as heat."
                            : "No converter is perfect — a few percent of the throughput drops inside, and dropped power is heat. Warm is normal; HOT means trouble.",
            },
            {
              q: "A toaster glows red on purpose. Its heating wire is…",
              options: ["A deliberate pinch — resistance turning power into heat where you want it", "A perfect conductor", "A tiny battery", "A one-way valve"],
              correct: 0,
              explain: kids ? "A toaster is a pinch built on purpose! All that fighting-the-squeeze warmth is aimed straight at your bread."
                            : "Nichrome wire is engineered resistance: the mains push drops across it and the full I²R budget lands exactly where the bread is.",
            },
            {
              q: "You open the pinch wide and the bulb blazes bright. Where is most of the heat being made now?",
              options: ["At the bulb — it gets nearly all the push now", "Still at the pinch", "Nowhere — the heat stopped", "In the wires evenly"],
              correct: 0,
              explain: kids ? "The heat moved house! With the squeeze gone, the bulb takes all the push — its glow (and warmth) is where the power lands."
                            : "Heat follows the voltage drop. With Rₚ ≈ 0, the lamp takes the full push and the full power budget — brightness IS its dissipation.",
            },
            {
              q: "Two batteries both say 1.5 V, but one is rated for many more mAh. The bigger-mAh one…",
              options: ["Lasts longer at the same draw — same push, bigger barrel", "Pushes harder", "Makes bulbs brighter", "Charges your devices faster"],
              correct: 0,
              explain: kids ? "Same height of barrel, fatter belly. It squirts just as hard — it just keeps squirting for much longer."
                            : "mAh is capacity, not pressure. Identical voltage means identical brightness; the extra capacity only stretches the runtime.",
            },
            {
              q: "Your electricity bill charges by the kWh. A kWh is…",
              options: ["Energy — power kept up over time, like the wheel's counter", "Peak power only", "A kind of voltage", "The number of devices you own"],
              correct: 0,
              explain: kids ? "The power company counts how much work was done in total — like counting the wheel's turns, not how fast it spun at any moment."
                            : "A kilowatt-hour is 1,000 W sustained for an hour — 3.6 MJ. Utilities meter accumulated energy, exactly like the joule counter under the wheel.",
            },
          ]} />

        <PracticeProblems chapterN="03" kids={kids} problems={[
          (rng) => {
            const v = rng.int(5, 24, 1), i = rng.pick([0.25, 0.5, 0.75, 1.5, 2]);
            const p = +(v * i).toFixed(2);
            return {
              q: { adult: `A device runs at ${v} V and draws ${i} A. How much power does it use?`, kids: `Push is ${v}, flow is ${i}. Power = push × flow. How many watts?` },
              unit: "W", answer: p, tol: 0.04,
              hint: "P = V × I.",
              solution: { adult: `P = V × I = ${v} V × ${i} A = ${p} W.`, kids: `${v} × ${i} = ${p}.` } };
          },
          (rng) => {
            const i = rng.pick([1, 2, 3, 0.5]), r = rng.int(2, 12, 1);
            const p = +(i * i * r).toFixed(2);
            return {
              q: { adult: `${i} A flows through a ${r} Ω resistor. How much power does it turn into heat?`, kids: `${i} of flow through a pinch of ${r}. Heat = flow × flow × pinch. How many watts?` },
              unit: "W", answer: p, tol: 0.04,
              hint: "P = I²R.",
              solution: { adult: `P = I²R = ${i}² × ${r} = ${+(i * i).toFixed(2)} × ${r} = ${p} W.`, kids: `${i} × ${i} × ${r} = ${p}.` } };
          },
          (rng) => {
            const v = rng.int(5, 20, 1), r = rng.pick([2, 4, 5, 10]);
            const p = +(v * v / r).toFixed(2);
            return {
              q: { adult: `What power is dissipated by a ${r} Ω resistor with ${v} V across it?`, kids: `${v} of push across a pinch of ${r}. Power = push × push ÷ pinch. Watts?` },
              unit: "W", answer: p, tol: 0.04,
              hint: "P = V² ÷ R.",
              solution: { adult: `P = V² ÷ R = ${v}² ÷ ${r} = ${v * v} ÷ ${r} = ${p} W.`, kids: `${v} × ${v} ÷ ${r} = ${p}.` } };
          },
        ]} />

        <ChapterQuiz
          chapterN="03"
          title={kids ? "Quick quiz!" : "Check your understanding."}
          intro={kids
            ? "Five quick questions about power and heat. Try as often as you like."
            : "Five questions on power and where the heat goes. 70% to pass; retry freely."}
          questions={kids ? KIDS_QUIZ : ADULT_QUIZ}
          pick={5}
        />
        <WhatsNext
          currentN="03"
          kids={kids}
          summary={kids
            ? <>Now you know why your laptop gets warm and why toasters glow.</>
            : <>Power = V × I. Heat is the side-effect of pushing current through resistance. Engineering is mostly about getting useful work and shedding the heat.</>
          }
          prevHref="chapter2.html"
          prevLabel="Chapter 2"
          nextHref="chapter4.html"
          nextLabel="Chapter 4 · The Bucket"
        />
      </main>
      <TweaksPanel title="Tweaks">
        <CommonTweaks t={t} setTweak={setTweak}
          animationToggles={[{ key: "showCircuit", label: "Show circuit" }]} />
      </TweaksPanel>
      <GlossaryFab />
    </>
  );
}

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