/* chapter11.jsx — Ch. 11 · The Divider (Level 1½).
   Voltage dividers: two pinches share the push in proportion to their
   squeeze. The tap between them is the most-used trick in electronics. */

const { useState, useEffect, useRef } = React;

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

/* ─── Divider scene: real pipe renderer + gates + tap with its own faucet ─
   Uses the shared kit (renderPipe, renderFaucet, renderWaterCurrent) so the
   water has the same texture/levels as chapters 1–3, and every outlet is a
   proper tap. The first gate's opening lines up with the downstream level. */
function Ch11DividerSVG({ V = 12, r1, r2, kids }) {
  const frac = Math.max(0.1, r2 / (r1 + r2));
  const vout = V * (r2 / (r1 + r2));
  const I = V / (r1 + r2);
  const period = flowPeriod(I * 2);
  const W = 660, H = 268;
  const pipeY = 76, baseH = 28;
  const pipeStart = 22, pipeEnd = 596;
  const xP1a = 140, xP1b = 218, xP2a = 412, xP2b = 490;
  const m1 = (xP1a + xP1b) / 2, m2 = (xP2a + xP2b) / 2;
  const endFrac = 0.1;
  // Each gate's opening tracks ITS OWN resistor — tighter slider, tighter squeeze.
  const open1 = 1 - Math.min(0.9, (r1 / 12) * 0.9);
  const open2 = 1 - Math.min(0.9, (r2 / 12) * 0.9);
  const constrictions = [
    { xa: xP1a, xb: xP1b, narrowH: baseH * (0.1 + 0.9 * open1), gate: true },
    { xa: xP2a, xb: xP2b, narrowH: baseH * (0.1 + 0.9 * open2), gate: true },
  ];
  const levels = [
    { fromX: pipeStart, toX: m1, frac: 1 },
    { fromX: m1, toX: m2, frac },
    { fromX: m2, toX: pipeEnd, frac: endFrac },
  ];
  // ── the tap: standpipe down from between the gates, elbow, small faucet ──
  const xTap = 304, tapW = 15;
  const tapTop = pipeY + baseH - 2;
  const stubY = tapTop + 58;          // centerline of the horizontal stub
  const stubH = 10;                   // half-height
  const stubEnd = xTap + 58;
  const tip = faucetTip({ x: stubEnd, y: stubY, baseH: stubH, s: 0.72 });
  const dripDur = (2.3 - 1.7 * (vout / V)).toFixed(2) + "s";
  const dropPath = `M ${tip.x} ${tip.y} q 7 10 9 34`;
  // cup that catches the drips — its level mirrors V_out
  const cupX = tip.x - 6, cupW = 46, cupBot = stubY + 78, cupH = 42;
  const cupFill = cupH * (vout / V);
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" style={{ display: "block" }}>
      {/* main pipe — shared renderer: water texture, level steps, faucet outlet */}
      {renderPipe({ pipeStart, pipeEnd, pipeY, baseH, constrictions, current: I * 2, period,
                    idSuffix: "div11", levels })}
      {renderOutletDroplets({ pipeEnd, pipeY, baseH, current: I * 1.5, period })}
      {/* gate labels */}
      <text x={m1} y={pipeY - baseH - 26} textAnchor="middle" fontFamily="IBM Plex Mono, monospace" fontSize="14.5" fill="var(--ink-soft)">
        {kids ? "first squeeze" : "R₁"} · {r1.toFixed(1)}{kids ? "" : "k"}
      </text>
      <text x={m2} y={pipeY - baseH - 26} textAnchor="middle" fontFamily="IBM Plex Mono, monospace" fontSize="14.5" fill="var(--ink-soft)">
        {kids ? "second squeeze" : "R₂"} · {r2.toFixed(1)}{kids ? "" : "k"}
      </text>
      <text x={pipeStart + 4} y={pipeY - baseH - 10} fontFamily="IBM Plex Mono, monospace" fontSize="13" fill="var(--ink-faint)">
        {kids ? `full push · ${V}` : `V_in · ${V} V`}
      </text>
      {/* mid-level dashed marker */}
      <line x1={m1 + 14} y1={pipeY + baseH - 2 * baseH * frac} x2={m2 - 14} y2={pipeY + baseH - 2 * baseH * frac}
            stroke="var(--water-deep)" strokeWidth="1.6" strokeDasharray="5 5" opacity="0.8" />
      {/* ── tap standpipe ── */}
      <rect x={xTap} y={tapTop} width={tapW} height={stubY - tapTop} fill="var(--water)" opacity="0.8" />
      <rect x={xTap} y={stubY - stubH} width={stubEnd - xTap} height={stubH * 2} fill="var(--water)" opacity="0.8" />
      <line x1={xTap} y1={tapTop} x2={xTap} y2={stubY - stubH} stroke="var(--ink)" strokeWidth="2.2" />
      <line x1={xTap + tapW} y1={tapTop} x2={xTap + tapW} y2={stubY + stubH} stroke="var(--ink)" strokeWidth="2.2" />
      <line x1={xTap} y1={stubY - stubH} x2={stubEnd} y2={stubY - stubH} stroke="var(--ink)" strokeWidth="2.2" />
      <line x1={xTap + tapW} y1={stubY + stubH} x2={stubEnd} y2={stubY + stubH} stroke="var(--ink)" strokeWidth="2.2" />
      {/* the tap's own little faucet */}
      {renderFaucet({ x: stubEnd, y: stubY, baseH: stubH, on: vout > 0.4, s: 0.72 })}
      {/* drips — pace follows the tap's push */}
      {vout > 0.4 && [0, 1].map(i => (
        <circle key={i} r="3" fill="var(--water)">
          <animateMotion path={dropPath} dur={dripDur} begin={`-${i * parseFloat(dripDur) / 2}s`} repeatCount="indefinite" />
          <animate attributeName="opacity" values="0;1;1;0.4" keyTimes="0;0.15;0.8;1" dur={dripDur} begin={`-${i * parseFloat(dripDur) / 2}s`} repeatCount="indefinite" />
        </circle>
      ))}
      {/* cup with level = V_out */}
      <path d={`M ${cupX} ${cupBot - cupH} L ${cupX + 5} ${cupBot} L ${cupX + cupW - 5} ${cupBot} L ${cupX + cupW} ${cupBot - cupH}`}
            fill="none" stroke="var(--ink)" strokeWidth="2.2" strokeLinejoin="round" />
      <polygon points={`${cupX + (cupH - cupFill) * 0.12},${cupBot - cupFill} ${cupX + cupW - (cupH - cupFill) * 0.12},${cupBot - cupFill} ${cupX + cupW - 5},${cupBot} ${cupX + 5},${cupBot}`}
               fill="var(--water)" opacity="0.8" />
      <text x={cupX + cupW / 2} y={cupBot + 18} textAnchor="middle" fontFamily="IBM Plex Mono, monospace" fontSize="12" fill="var(--ink-faint)">
        {kids ? "your tap" : "V_out"}
      </text>
      {/* gauge */}
      <g transform={`translate(${xTap - 74} ${stubY + 26})`}>
        <rect x="-52" y="-24" width="104" height="48" rx="8" fill="var(--bg-card)" stroke="var(--ink)" strokeWidth="2" />
        <text y="-2" textAnchor="middle" fontFamily="IBM Plex Mono, monospace" fontSize="17.5" fontWeight="600" fill="var(--water-deep)">
          {vout.toFixed(1)}{kids ? "" : " V"}
        </text>
        <text y="16" textAnchor="middle" fontFamily="IBM Plex Mono, monospace" fontSize="10.5" fill="var(--ink-faint)" letterSpacing="0.06em">
          {Math.round((r2 / (r1 + r2)) * 100)}% {kids ? "of the push" : "of V_in"}
        </text>
      </g>
      <line x1={xTap - 22} y1={stubY + 14} x2={xTap - 2} y2={stubY - 4} stroke="var(--ink-faint)" strokeWidth="1.2" strokeDasharray="3 4" />
    </svg>
  );
}

/* ─── §01 + the main interactive ───────────────────────────────────────── */
function Ch11Playground({ kids }) {
  const [r1, setR1] = useState(6);
  const [r2, setR2] = useState(6);
  const V = 12;
  const vout = V * r2 / (r1 + r2);
  return (
    <section className="section" id="playground" data-screen-label="02 Playground">
      <div className="marker">§ 02 · two squeezes, one tap</div>
      <div className="section-inner">
        <div className="two-col">
          <div>
            <h2 className="serif">The push divides<br/>where the pinches <em>meet</em>.</h2>
            <p className="lede">
              {kids
                ? <>Remember chapter 2 — every squeeze uses up some of the push, and the water level steps down after each one. Now put a TAP between two squeezes. The tap's push is whatever level the water sits at right there!</>
                : <>Chapter 2 taught that series resistors split the voltage in proportion to their resistance. The divider weaponizes that: put a tap between two resistors and the tap delivers exactly the fraction you chose.</>}
            </p>
            <p>
              {kids
                ? <>Tighten the FIRST squeeze and the middle level drops — less push at the tap. Tighten the SECOND squeeze and the level rises — the water backs up! The two squeezes are having a tug-of-war over your tap.</>
                : <>The split follows the ratio: <Eq>V_out = V_in · R₂/(R₁+R₂)</Eq>. Equal resistors? Half. R₂ three times R₁? Three quarters. The absolute values barely matter — the <em>ratio</em> is the dial.</>}
            </p>
            <EqEase kids={kids} />
            <div className="marg" style={{ marginTop: 14 }}>
              {kids
                ? <>Try making the gauge read exactly half. How many different ways can you find?</>
                : <>Notice 6k/6k and 1k/1k both give 6 V — same ratio, same split. (They differ in how much current the divider itself wastes; more on that below.)</>}
            </div>
          </div>
          <div>
            <div className="card" style={{ padding: "22px 26px" }}>
              <div className="eyebrow" style={{ marginBottom: 12 }}>try it · 12 V in</div>
              <Ch11DividerSVG V={V} r1={r1} r2={r2} kids={kids} />
              <Slider name={kids ? "First squeeze" : "R₁ (top of the divider)"} value={r1} min={0.5} max={12} step={0.1}
                      unit={kids ? "" : " kΩ"} accent="" onChange={setR1} />
              <Slider name={kids ? "Second squeeze" : "R₂ (bottom, where you tap)"} value={r2} min={0.5} max={12} step={0.1}
                      unit={kids ? "" : " kΩ"} accent="water" onChange={setR2} />
              <div className="branch-readout" style={{ marginTop: 10 }}>
                <span>{kids ? "push at the tap" : "V_out = 12 · R₂/(R₁+R₂)"}</span>
                <span className="mono"><b style={{ color: "var(--water-deep)" }}>{vout.toFixed(2)} V</b></span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─── §03 the potentiometer ───────────────────────────────────────────── */
function Ch11PotSection({ kids }) {
  const [knob, setKnob] = useState(0.65);   // 0..1 wiper position
  const V = 12;
  const vout = V * knob;
  const angle = -135 + knob * 270;
  return (
    <section className="section" id="pot" data-screen-label="03 The knob" style={{ background: "var(--bg-deeper)" }}>
      <div className="marker">§ 03 · the knob is a divider</div>
      <div className="section-inner">
        <div className="two-col">
          <div>
            <h2 className="serif">Every volume knob<br/>is <em>this circuit</em>.</h2>
            <p className="lede">
              {kids
                ? <>A potentiometer ("pot") is a divider with a twist — literally. One strip of resistance, and a slider that taps it anywhere along its length. Turning the knob just moves the tap!</>
                : <>A potentiometer is a divider whose midpoint moves: one resistive strip, a wiper that taps it anywhere. Turn the shaft and you're sliding the tap — R₁ shrinks as R₂ grows, total fixed.</>}
            </p>
            <p>
              {kids
                ? <>Volume knobs, dimmer dials, joysticks, the speed dial on a fan — they're all the same trick: turn a knob, move a tap, change a push.</>
                : <>Volume controls divide the audio signal itself. Joysticks are two pots (one per axis) read by a chip. Old dimmers, tone knobs, analog synth panels — entire interfaces built from moving taps.</>}
            </p>
            <div className="marg" style={{ marginTop: 14 }}>
              {kids
                ? <>Sensors play the same game: some parts change their squeeze when the world changes — heat, light, a bend. Put one in a divider and the tap's push <em>reports the world</em>.</>
                : <>Sensors complete the picture: a thermistor (R falls with heat) or photoresistor (R falls with light) as one leg makes V_out track temperature or brightness — how a chip with no eyes "reads" the world. The Beacon's light sensor works exactly this way.</>}
            </div>
          </div>
          <div>
            <div className="card" style={{ padding: "22px 26px" }}>
              <div className="eyebrow" style={{ marginBottom: 12 }}>one knob · 12 V across the strip</div>
              <svg viewBox="0 0 380 210" width="100%" style={{ display: "block" }}>
                {/* the strip */}
                <rect x="40" y="150" width="300" height="18" rx="9" fill="var(--bg-deeper)" stroke="var(--ink)" strokeWidth="2" />
                <rect x="40" y="150" width={300 * knob} height="18" rx="9" fill="var(--water)" opacity="0.7" />
                <text x="40" y="190" fontFamily="IBM Plex Mono, monospace" fontSize="12" fill="var(--ink-faint)">0 V</text>
                <text x="340" y="190" textAnchor="end" fontFamily="IBM Plex Mono, monospace" fontSize="12" fill="var(--ink-faint)">12 V</text>
                {/* wiper */}
                <line x1={40 + 300 * knob} y1="150" x2={40 + 300 * knob} y2="112" stroke="var(--ink)" strokeWidth="2.5" />
                <circle cx={40 + 300 * knob} cy="106" r="5" fill="var(--water-deep)" />
                <text x={40 + 300 * knob} y="92" textAnchor="middle" fontFamily="IBM Plex Mono, monospace" fontSize="13.5"
                      fill="var(--water-deep)" fontWeight="600">{vout.toFixed(1)} V</text>
                {/* the knob */}
                <g transform="translate(310 52)">
                  <circle r="34" fill="var(--bg-card)" stroke="var(--ink)" strokeWidth="2.5" />
                  <line x1="0" y1="0" x2={34 * Math.sin(angle * Math.PI / 180) * 0.8} y2={-34 * Math.cos(angle * Math.PI / 180) * 0.8}
                        stroke="var(--current-deep)" strokeWidth="3.5" strokeLinecap="round" />
                  <circle r="4" fill="var(--ink)" />
                </g>
                <text x="310" y="14" textAnchor="middle" fontFamily="IBM Plex Mono, monospace" fontSize="11"
                      fill="var(--ink-faint)" letterSpacing="0.1em">{kids ? "THE KNOB" : "THE WIPER"}</text>
              </svg>
              <Slider name={kids ? "Turn the knob" : "Wiper position"} value={knob} min={0} max={1} step={0.01}
                      unit="" accent="water" onChange={setKnob} />
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─── §04 the honest catch: loading ────────────────────────────────────── */
function Ch11LoadingSection({ kids }) {
  const [rl, setRl] = useState(60);
  const r1 = 6, r2 = 6, V = 12;
  // loaded divider: R2 ∥ RL
  const r2eff = (r2 * rl) / (r2 + rl);
  const vout = V * r2eff / (r1 + r2eff);
  const sag = 6 - vout;
  const fracLoaded = Math.max(0.08, vout / V);
  const Iload = vout / rl;
  // mini scene geometry
  const ldW = 560, ldPipeY = 64, ldBaseH = 22, ldStart = 16, ldEnd = 500;
  const ldP1a = 110, ldP1b = 172, ldP2a = 350, ldP2b = 412;
  const ldM1 = (ldP1a + ldP1b) / 2, ldM2 = (ldP2a + ldP2b) / 2;
  const ldTap = 252, ldTapW = 13;
  const ldBranchY = ldPipeY + ldBaseH + 52;
  return (
    <section className="section" id="loading" data-screen-label="04 The catch">
      <div className="marker">§ 04 · the honest catch</div>
      <div className="section-inner">
        <div className="two-col">
          <div>
            <h2 className="serif">The tap is a promise<br/><em>only if nobody drinks</em>.</h2>
            <p className="lede">
              {kids
                ? <>So far your tap has just been a gauge — nothing actually LEAVES through it. Plug in something that drinks, and the reading drops. Here's the whole mystery, in three steps:</>
                : <>So far nothing flows <em>out</em> of the tap — it's just a gauge. Connect a real load and the reading sags. The mechanism is nothing new; it's chapter 2, wearing a disguise:</>}
            </p>
            <ol style={{ display: "grid", gap: 12, paddingLeft: 24, margin: "4px 0 0" }}>
              <li style={{ lineHeight: 1.6 }}>
                {kids
                  ? <><b>Alone, the middle pool just sits there.</b> Water passes through, but none leaves at the tap — so the level stays exactly where the two squeezes put it.</>
                  : <><b>Unloaded, the tap draws zero current.</b> The middle level sits exactly at the ratio: 6 V, for a 6k/6k split of 12.</>}
              </li>
              <li style={{ lineHeight: 1.6 }}>
                {kids
                  ? <><b>A load is a SECOND exit.</b> Plugging something in opens another pipe out of the middle pool — side-by-side with the second squeeze. Two exits… remember chapter 2? That's a parallel pair!</>
                  : <><b>A load is a second exit from the midpoint.</b> Electrically it sits in <em>parallel</em> with R₂ — chapter 2's side-by-side pipes, exactly.</>}
              </li>
              <li style={{ lineHeight: 1.6 }}>
                {kids
                  ? <><b>Two exits drain easier than one.</b> Water escapes the middle pool faster than before, so the pool can't stay as deep — the level falls, and your promised 6 droops.</>
                  : <><b>Two exits = a weaker bottom leg.</b> R₂∥R_L is smaller than R₂ alone, the ratio shifts, and V_out falls — the bottom of the divider hoards less of the push.</>}
              </li>
            </ol>
            <p style={{ marginTop: 16 }}>
              {kids
                ? <>The thirstier the drinker (a wider, easier exit), the worse the droop. A barely-sipping drinker — like a chip that only wants to <em>look</em> at the level — hardly moves it at all. That's why taps are for <b>telling</b> things a level, never for <b>feeding</b> hungry things.</>
                : <>How bad is it? Pure ratio. A load ≥10× R₂ adds only a trickle of an exit — the sag is pennies. At R_L ≈ R₂ the bottom leg effectively halves and your 6 V reads 4. Below that, the promise is gone. Hence the rules: keep R_L ≥ 10×R₂, and use dividers for <em>signals</em> (references, sensor reads, chip inputs) — never for power.</>}
            </p>
            <EqEase kids={kids}>
              {kids
                ? <>(No math needed — just remember: <b>a load is a second exit, and a second exit drops the level.</b>)</>
                : <>(The math is chapter 2 verbatim: R₂∥R_L = R₂·R_L/(R₂+R_L), then re-run the divider with that as the bottom leg. Try it once by hand for R_L = 6k — you'll get 4 V — and the practice problems below make it automatic. Chapter 12 has the elegant fix: a follower that reads the tap without sipping.)</>}
            </EqEase>
          </div>
          <div>
            <div className="card" style={{ padding: "22px 26px" }}>
              <div className="eyebrow" style={{ marginBottom: 12 }}>6k/6k divider · promised: 6 V</div>
              <svg viewBox={`0 0 ${ldW} 215`} width="100%" style={{ display: "block" }}>
                {renderPipe({ pipeStart: ldStart, pipeEnd: ldEnd, pipeY: ldPipeY, baseH: ldBaseH,
                              constrictions: [
                                { xa: ldP1a, xb: ldP1b, narrowH: ldBaseH * fracLoaded, gate: true },
                                { xa: ldP2a, xb: ldP2b, narrowH: ldBaseH * 0.1, gate: true },
                              ],
                              current: V / (r1 + r2eff), period: flowPeriod(V / (r1 + r2eff) * 1.6),
                              idSuffix: "ld11",
                              levels: [
                                { fromX: ldStart, toX: ldM1, frac: 1 },
                                { fromX: ldM1, toX: ldM2, frac: fracLoaded },
                                { fromX: ldM2, toX: ldEnd, frac: 0.1 },
                              ] })}
                <text x={ldM1} y={ldPipeY - ldBaseH - 24} textAnchor="middle" fontFamily="IBM Plex Mono, monospace" fontSize="12.5" fill="var(--ink-soft)">R₁ · 6k</text>
                <text x={ldM2} y={ldPipeY - ldBaseH - 24} textAnchor="middle" fontFamily="IBM Plex Mono, monospace" fontSize="12.5" fill="var(--ink-soft)">R₂ · 6k</text>
                {/* the load: a second exit branching DOWN from the tap */}
                <rect x={ldTap} y={ldPipeY + ldBaseH - 2} width={ldTapW} height={ldBranchY - ldPipeY - ldBaseH + 2} fill="var(--water)" opacity="0.8" />
                <line x1={ldTap} y1={ldPipeY + ldBaseH - 2} x2={ldTap} y2={ldBranchY} stroke="var(--ink)" strokeWidth="2.2" />
                <line x1={ldTap + ldTapW} y1={ldPipeY + ldBaseH - 2} x2={ldTap + ldTapW} y2={ldBranchY} stroke="var(--ink)" strokeWidth="2.2" />
                <rect x={ldTap - 8} y={ldBranchY} width={ldTapW + 16} height={26} rx="4"
                      fill="var(--bg-deeper)" stroke="var(--ink)" strokeWidth="2" />
                <text x={ldTap + ldTapW / 2} y={ldBranchY + 17} textAnchor="middle" fontFamily="IBM Plex Mono, monospace" fontSize="11" fill="var(--ink-soft)">R_L</text>
                {Iload > 0.02 && (
                  <line x1={ldTap + ldTapW / 2} y1={ldBranchY + 26} x2={ldTap + ldTapW / 2} y2={ldBranchY + 44 + Math.min(18, Iload * 14)}
                        stroke="var(--water)" strokeWidth={Math.min(11, 1.5 + Iload * 9)} strokeLinecap="round" opacity="0.85" />
                )}
                <text x={ldTap + ldTapW / 2 + 14} y={ldBranchY + 48} fontFamily="IBM Plex Mono, monospace" fontSize="11.5" fill="var(--ink-faint)">
                  {kids ? "the drinker — a second exit!" : `the load · draws ${Iload.toFixed(2)} mA`}
                </text>
                {/* promised level ghost line */}
                <line x1={ldM1 + 12} y1={ldPipeY + ldBaseH - 2 * ldBaseH * 0.5} x2={ldM2 - 12} y2={ldPipeY + ldBaseH - 2 * ldBaseH * 0.5}
                      stroke="var(--ink-faint)" strokeWidth="1.4" strokeDasharray="3 5" />
                <text x={ldM2 - 8} y={ldPipeY + ldBaseH - 2 * ldBaseH * 0.5 - 5} textAnchor="end" fontFamily="IBM Plex Mono, monospace" fontSize="10.5" fill="var(--ink-faint)">
                  {kids ? "promised level" : "promised · 6 V"}
                </text>
              </svg>
              <Slider name={kids ? "How thirsty is the drinker?" : "Load on the tap · R_L"} value={rl} min={1} max={100} step={1}
                      unit={kids ? "" : " kΩ"} accent="current" onChange={setRl} flip />
              <div className="branch-readout" style={{ marginTop: 14 }}>
                <span>{kids ? "what the tap really reads" : "V_out, loaded"}</span>
                <span className="mono"><b style={{ color: sag > 0.6 ? "oklch(0.55 0.17 35)" : "var(--water-deep)" }}>{vout.toFixed(2)} V</b></span>
              </div>
              <div style={{ height: 14, background: "var(--bg-deeper)", border: "1px solid var(--rule)", borderRadius: 3, marginTop: 12 }}>
                <div style={{ height: "100%", width: `${(vout / 6) * 100}%`, background: sag > 0.6 ? "oklch(0.62 0.17 35)" : "var(--water)", transition: "width 150ms ease" }}></div>
              </div>
              <div className="marg" style={{ marginTop: 12 }}>
                {kids
                  ? <>Slide left = a thirstier drinker = a wider second exit. Watch the middle pool and the reading droop <em>together</em> — they're the same thing!</>
                  : <>At R_L = 60k (10×R₂): 5.7 V — fine. At 6k (=R₂): 4.0 V — a third gone. At 1k: 1.6 V — ruined. Watch the pipe's middle level fall in step with the number.</>}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ─── App ─────────────────────────────────────────────────────────────── */
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: "playground", label: kids ? "Two squeezes" : "The divider" },
    { id: "pot", label: "The knob" },
    { id: "loading", label: kids ? "The catch" : "Loading" },
    { id: "practice", label: "Practice" },
    { id: "quiz", label: "Quiz" },
  ];

  return (
    <>
      <ProgressBar />
      <TopBar currentN="11" audience={t.audience} setAudience={(a) => setTweak("audience", a)} />
      <ChapterNav items={navItems} />

      <main>
        <CoverPage chapterN="11"
                   chapterTitle={<>The <em>Divider</em>.</>}
                   chapterSub="Two pinches share the push"
                   kids={kids}
                   lede={kids
                     ? <>One pipe, two squeezes, and a tap in the middle. It sounds too simple to matter — and it's secretly inside every knob you've ever turned.</>
                     : <>Two resistors and a tap between them — the most-used circuit fragment in all of electronics. This chapter is short, and you'll see it everywhere forever.</>
                   }>
          <ChapterStartMarker chapterN="11" />
          <div className="marg">
            Level 1½ · builds on chapters 1 & 2. If level-steps after a pinch feel fuzzy, skim chapter 2's series section first.
          </div>
        </CoverPage>

        <Ch11Playground kids={kids} />

        <CheckpointQuiz kids={kids} label="Checkpoint 1" pick={2}
          title={kids ? "Quick check!" : "Did it stick?"}
          questions={[
            { q: "Equal pinches, 12 V in. The tap between them reads…",
              options: ["6 V — an even split", "12 V", "0 V", "3 V"], correct: 0,
              explain: kids ? "Same squeezes share evenly — half the push is used by each, so the middle sits at half."
                            : "Equal R, equal share: V_out = 12 · R/(R+R) = 6 V." },
            { q: kids ? "You tighten the SECOND squeeze (after the tap). The tap's level…" : "Increase R₂ (below the tap). V_out…",
              options: ["rises — the water backs up", "falls", "doesn't change", "goes to zero"], correct: 0,
              explain: kids ? "A tighter exit makes the middle pool deeper — more push waiting at your tap."
                            : "V_out = V·R₂/(R₁+R₂) grows with R₂ — the bottom leg hoards more of the drop." },
            { q: "A 9 V source, R₁ = 1 kΩ, R₂ = 2 kΩ. The tap reads…",
              options: ["6 V", "3 V", "4.5 V", "9 V"], correct: 0,
              explain: kids ? "The second squeeze is twice the first, so it keeps two-thirds of the push: 6."
                            : "9 · 2/(1+2) = 6 V. Ratio is everything." },
            { q: kids ? "What matters most for where the tap sits?" : "Two dividers: 1k/1k and 10k/10k, same source. Their outputs are…",
              options: [kids ? "The RATIO of the two squeezes" : "identical — same ratio, same split", kids ? "Using big numbers" : "different by 10×", kids ? "The pipe's length" : "zero in both", kids ? "Luck" : "unstable"], correct: 0,
              explain: kids ? "Two same-size squeezes always split evenly — whether they're both big or both small."
                            : "Same ratio, same V_out. They differ only in wasted current through the divider itself (the 1k pair burns 10× more)." },
          ]} />

        <Ch11PotSection kids={kids} />
        <Ch11LoadingSection kids={kids} />

        <CheckpointQuiz kids={kids} label="Checkpoint 2" pick={2}
          title={kids ? "Spot it in real life!" : "Out in the wild."}
          questions={[
            { q: "An old radio's volume knob works by…",
              options: ["sliding a tap along a resistive strip — dividing the signal", "changing the battery voltage", "bending the antenna", "heating a wire"], correct: 0,
              explain: kids ? "Turn the knob, move the tap, more or less of the sound's push gets through!"
                            : "The pot divides the audio signal before the amplifier — wiper position = volume." },
            { q: kids ? "How can a chip with no eyes tell if it's dark outside?" : "A photoresistor (R falls with light) is the BOTTOM leg of a divider. In bright light, V_out…",
              options: [kids ? "A light-sensing part in a divider changes the tap's push" : "falls — the bottom leg hoards less", kids ? "It can't" : "rises", kids ? "A tiny camera" : "stays fixed", kids ? "Magic" : "oscillates"], correct: 0,
              explain: kids ? "The sensor's squeeze changes with light, so the tap's level IS a brightness report."
                            : "Bright → R₂ small → V_out = V·R₂/(R₁+R₂) drops. The chip reads light as a voltage." },
            { q: "Why shouldn't you power a motor from a divider tap?",
              options: ["The motor's thirst drags the tap voltage way down", "Motors don't use voltage", "Dividers only work at night", "You should — it's standard"], correct: 0,
              explain: kids ? "Thirsty things drink the middle level down — the promised push collapses."
                            : "A heavy load parallels R₂ and ruins the ratio — plus the divider wastes power constantly. Signals, not power." },
            { q: kids ? "A joystick knows where you pushed it because…" : "An analog joystick reports its position via…",
              options: ["each direction moves a tap on a divider", "tiny cameras", "it counts your pushes", "springs only"], correct: 0,
              explain: kids ? "Tilting the stick turns little knobs inside — taps move, pushes change, the game reads them!"
                            : "Two pots, one per axis. The console ADCs read two divider voltages — that's the whole sensor." },
          ]} />

        <PracticeProblems chapterN="11" kids={kids} problems={[
          (rng) => {
            const v = rng.pick([9, 12, 24]), r1 = rng.pick([1, 2, 3, 4]), r2 = rng.pick([1, 2, 3, 6]);
            return {
              q: { adult: `V_in = ${v} V, R₁ = ${r1} kΩ, R₂ = ${r2} kΩ. What is V_out at the tap?`,
                   kids: `The barrel pushes with ${v}. The first squeeze is ${r1}, the second is ${r2}. What push waits at the tap?` },
              unit: "V", answer: v * r2 / (r1 + r2),
              hint: { adult: "V_out = V_in · R₂/(R₁+R₂).", kids: "Tap push = total push × second ÷ (first + second)." },
              solution: { adult: `${v} · ${r2}/(${r1}+${r2}) = ${(v * r2 / (r1 + r2)).toFixed(2)} V.`,
                          kids: `${v} × ${r2} ÷ ${r1 + r2} = ${(v * r2 / (r1 + r2)).toFixed(2)}.` },
            };
          },
          (rng) => {
            const v = rng.pick([12, 10, 5]), vout = rng.pick([0.5, 0.25, 0.75]);
            const target = v * vout, r1 = rng.pick([2, 4, 10]);
            const r2 = r1 * vout / (1 - vout);
            return {
              q: { adult: `You need ${target} V from a ${v} V source. R₁ is ${r1} kΩ. What R₂ completes the divider?`,
                   kids: `You want the tap to read ${target} from a push of ${v}. The first squeeze is ${r1}. How big is the second?` },
              unit: "kΩ", answer: r2,
              hint: { adult: "Fraction needed = V_out/V_in. R₂ = R₁ · f/(1−f).", kids: "What fraction do you want? The second squeeze hoards that share." },
              solution: { adult: `f = ${vout}. R₂ = ${r1}·${vout}/(1−${vout}) = ${r2.toFixed(2)} kΩ.`,
                          kids: `You want ${vout === 0.5 ? "half" : vout === 0.25 ? "a quarter" : "three quarters"} — so R₂ = ${r2.toFixed(2)}.` },
            };
          },
          (rng) => {
            const r = rng.pick([2, 4, 6]), rl = r;
            const r2eff = (r * rl) / (r + rl);
            const vout = 12 * r2eff / (r + r2eff);
            return {
              q: { adult: `A ${r}k/${r}k divider on 12 V should read 6 V. A ${rl} kΩ load attaches to the tap. What does it actually read?`,
                   kids: `Your even divider promised 6. A thirsty straw exactly as big as the second squeeze starts drinking at the tap. What's the real level?` },
              unit: "V", answer: vout,
              hint: { adult: "The load parallels R₂: R₂∥R_L = R·R/(R+R) = R/2. Then redo the divider.", kids: "The drinker makes the bottom squeeze act half as strong." },
              solution: { adult: `R₂∥R_L = ${r / 2} k. V = 12·${r / 2}/(${r}+${r / 2}) = ${vout.toFixed(1)} V — a full third lost to loading.`,
                          kids: `The level droops to ${vout.toFixed(1)} — thirsty loads break the promise!` },
            };
          },
        ]} />

        <ChapterQuiz chapterN="11" pick={5}
          title={kids ? "Quick quiz!" : "Check your understanding."}
          questions={kids ? [
            { q: "A divider is…", kind: "concept", options: ["two squeezes with a tap between them", "a kind of battery", "a broken pipe", "two barrels"], correct: 0,
              explain: "One pipe, two squeezes, one tap — that's the whole circuit!" },
            { q: "Equal squeezes split the push…", kind: "concept", options: ["right down the middle", "all to the first", "all to the second", "randomly"], correct: 0,
              explain: "Same squeeze, same share — the tap sits at half." },
            { q: "To RAISE the tap's level you can…", kind: "concept", options: ["tighten the second squeeze", "tighten the first squeeze", "shorten the pipe", "wish"], correct: 0,
              explain: "A tighter exit backs the water up — deeper middle pool, more push at your tap." },
            { q: "A volume knob is secretly…", kind: "concept", options: ["a divider with a moving tap", "a tiny speaker", "a battery", "a switch"], correct: 0,
              explain: "Turning the knob slides the tap along a strip — more or less push gets through." },
            { q: "The tap's promise breaks when…", kind: "concept", options: ["something thirsty drinks from it", "you measure it twice", "it's raining", "the pipe is long"], correct: 0,
              explain: "Loads drag the middle level down. Taps are for telling, not feeding!" },
            { q: "A light sensor in a divider lets a chip…", kind: "concept", options: ["read brightness as a push level", "see pictures", "make light", "sleep"], correct: 0,
              explain: "The sensor's squeeze changes with light — so the tap's level reports the world." },
          ] : [
            { q: "V_out of a divider equals…", kind: "concept", options: ["V_in · R₂/(R₁+R₂)", "V_in · R₁/R₂", "V_in − R₂", "V_in · (R₁+R₂)/R₂"], correct: 0,
              explain: "The bottom leg's share of the total resistance is the tap's share of the voltage." },
            { q: "12 V, R₁ = 3k, R₂ = 9k. V_out = ?", kind: "math", options: ["9 V", "3 V", "6 V", "12 V"], correct: 0,
              explain: "12 · 9/12 = 9 V — the big bottom leg hoards three quarters." },
            { q: "Doubling BOTH resistors in a divider…", kind: "concept", options: ["leaves V_out unchanged", "doubles V_out", "halves V_out", "shorts it"], correct: 0,
              explain: "Only the ratio sets the split. (The divider's own waste current halves, though — often a free win.)" },
            { q: "A potentiometer is…", kind: "concept", options: ["a divider whose midpoint moves", "a variable battery", "a polarized capacitor", "a relay"], correct: 0,
              explain: "One strip, one wiper: R₁ and R₂ trade places as you turn it. Total stays fixed." },
            { q: "Loading a divider with R_L = R₂ makes V_out…", kind: "concept", options: ["sag — the effective bottom leg halves", "rise slightly", "stay put", "double"], correct: 0,
              explain: "R₂∥R₂ = R₂/2 — the ratio shifts down hard. Keep loads ≥10× the bottom leg." },
            { q: "Dividers are the wrong tool for…", kind: "concept", options: ["powering anything hungry", "reading a sensor", "setting a reference voltage", "feeding a chip input"], correct: 0,
              explain: "Power belongs to regulators. Dividers serve signals — references, sensors, inputs." },
            { q: "A thermistor divider 'reports' temperature because…", kind: "concept", options: ["its resistance change moves the tap voltage", "heat makes voltage directly", "it stores heat", "chips feel warmth"], correct: 0,
              explain: "R changes with T, the ratio changes with R, V_out changes with the ratio. Chain complete." },
            { q: "A divider's own current (V_in / (R₁+R₂)) flows even with nothing attached to the tap. Why does that matter?", kind: "concept",
              options: ["It never matters", "It's pure waste heat — the trade-off for a divider's simplicity, so designers pick R₁+R₂ large enough to be negligible but small enough to resist loading", "It charges a battery", "It powers the load directly"], correct: 1,
              explain: "That standing current does nothing useful — it just warms the resistors. Every divider design balances it against the loading-resistance rule from earlier in the bank." },
          ]} />

        <WhatsNext currentN="11" kids={kids}
          summary={kids
            ? <>Two squeezes + one tap = a push of any size you want. Knobs and sensors are all dividers in disguise. But taps droop when something thirsty drinks!</>
            : <>The divider: V_out = V_in·R₂/(R₁+R₂). Ratio sets the split; pots make the ratio turnable; sensors make it world-sensitive. Signals only — loading kills the promise.</>}
          prevHref="chapter10.html" prevLabel="Ch. 10 · The Blinker"
          nextHref="chapter12.html" nextLabel="Ch. 12 · The Gatekeeper" />
      </main>

      <TweaksPanel title="Tweaks">
        <CommonTweaks t={t} setTweak={setTweak} />
      </TweaksPanel>
      <GlossaryFab />
    </>
  );
}

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