/* chapter7.jsx — Chapter 7: The One-Way Valve (Diodes). */

const { useState, useEffect, useRef } = React;

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

/* ── beats ─────────────────────────────────────────────────────────────── */
function BigIdeaBeat({ onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="begin" data-screen-label="01 One-way" ref={ref}>
      <div className="beat-marker">§ 01 · one direction only</div>
      {kids ? (
        <>
          <h2 className="serif">A door that only<br/>opens <em>one way</em>.</h2>
          <p className="lede">
            Some pipes have a little flap inside. Push water one way and the
            flap opens — water flows. Push the other way and the flap slams
            shut. Nothing gets through.
          </p>
          <p>A <em>diode</em> is that flap, but for electricity.</p>
        </>
      ) : (
        <>
          <h2 className="serif">A valve that passes<br/>current <em>one way</em>.</h2>
          <p className="lede">
            Every component so far works the same in both directions. A diode
            breaks that symmetry: it lets current through one way (<em>forward</em>)
            and blocks it the other (<em>reverse</em>).
          </p>
          <p>
            The water version is a <em>check valve</em> — a hinged flap that
            swings open with the flow but is pushed shut against it.
          </p>
          <div className="marg" style={{ marginTop: 12 }}>
            You've already met one: an <em>LED</em> is a diode that also glows.
            That's why it only lit one way round in Chapter 1.
          </div>
        </>
      )}
      <div className="pull">Forward: open. Backward: blocked.</div>
    </div>
  );
}

function ForwardReverseBeat({ forward, setForward, v, onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="direction" data-screen-label="02 Direction" ref={ref}>
      <div className="beat-marker">§ 02 · flip it around</div>
      <div className="chip current" style={{ marginBottom: 16 }}>try it</div>
      <h2 className="serif">Flip the <em>direction</em>.</h2>
      <p className="lede">
        {kids
          ? <>Press the buttons to push the water forward or backward. Watch the flap open and shut.</>
          : <>Toggle which way the source pushes. Forward biases the diode on; reverse holds it shut and current drops to zero.</>}
      </p>
      <div style={{ display: "flex", gap: 10, marginTop: 22, flexWrap: "wrap" }}>
        <button onClick={() => setForward(true)}
                style={dirBtn(forward, "var(--water)")}>
          {kids ? "▶ Push forward" : "▶ Forward"}
        </button>
        <button onClick={() => setForward(false)}
                style={dirBtn(!forward, "var(--current)")}>
          {kids ? "◀ Push backward" : "◀ Reverse"}
        </button>
      </div>
      <div className="card" style={{ background: "transparent", marginTop: 22, padding: "16px 20px" }}>
        <div className="eyebrow" style={{ marginBottom: 8 }}>state</div>
        <p style={{ margin: 0, fontSize: 18 }}>
          The valve is <span className="mono" style={{ color: forward ? "var(--water)" : "var(--current)" }}>
          {forward ? "OPEN" : "SHUT"}</span>.{" "}
          {forward
            ? <>Water flows{!kids && <> — about {((v) / 3).toFixed(2)} A</>}.</>
            : <>Nothing gets through. {kids ? "Blocked!" : "I = 0 A."}</>}
        </p>
      </div>
    </div>
  );
}

function WhyBeat({ onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="why" data-screen-label="03 The drop" ref={ref}>
      <div className="beat-marker">§ 03 · the toll booth</div>
      <h2 className="serif">{kids ? "A small toll." : "It costs a little to get through."}</h2>
      {kids ? (
        <>
          <p className="lede">
            The flap is a tiny bit heavy. Water has to push a little to swing
            it open. So a diode "uses up" a small bit of the push to open
            itself — about <span className="mono">0.7 V</span> for a normal one.
          </p>
          <p>For an LED it's more — that energy is what becomes <em>light</em>.</p>
        </>
      ) : (
        <>
          <p className="lede">
            A real diode isn't free. It only conducts once the forward voltage
            passes its <em>turn-on</em> threshold — about <span className="mono">0.7 V</span>
            for silicon, ~2 V for an LED. Below that, almost nothing flows.
          </p>
          <p>
            Above it, the diode drops that roughly-fixed voltage and passes
            whatever current the rest of the circuit allows. That fixed drop is
            why we still need a series resistor with an LED — the diode won't
            limit current itself.
          </p>
          <div className="card" style={{ background: "transparent", marginTop: 18, padding: "16px 20px" }}>
            <div className="eyebrow" style={{ marginBottom: 8 }}>forward drop</div>
            <div className="mono" style={{ fontSize: 17, lineHeight: 1.7 }}>
              Silicon diode … ~0.7 V<br/>
              Schottky diode … ~0.3 V<br/>
              Red LED … ~1.8 V<br/>
              Blue/white LED … ~3 V
            </div>
          </div>
        </>
      )}
    </div>
  );
}

function PredictBeat({ onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="predict" data-screen-label="04 Predict" ref={ref}>
      <div className="beat-marker">§ 04 · check your gut</div>
      <h2 className="serif">A puzzle<br/>(or two).</h2>
      <PredictReveal
        question={kids
          ? "You put a diode in backwards in your LED circuit. What happens?"
          : "An LED is installed reversed in a working circuit. Result?"}
        options={["It glows brighter", "It stays dark", "It pops", "It blinks"]}
        correct={1}
        explanation={kids
          ? "The flap is shut against the flow, so no electricity gets through — the LED stays dark. Flip it around!"
          : "Reverse-biased, the diode blocks current, so I = 0 and the LED is dark. (Exceed its reverse breakdown voltage and it can be damaged — but normally it just stays off.)"}
        accent="current" />
      <PredictReveal
        question={kids
          ? "Why does a diode still need a resistor friend in an LED circuit?"
          : "Why is a series resistor still required with an LED, even though the diode 'controls' direction?"}
        options={[
          "It doesn't — the diode handles everything",
          "The diode sets direction, not current — the resistor limits current",
          "To make it blink",
          "To store charge"]}
        correct={1}
        explanation={kids
          ? "The diode only picks the direction. Something still has to slow the flow so the LED doesn't get too much — that's the resistor's job."
          : "A diode fixes the voltage drop but not the current; above threshold it looks nearly like a short. The resistor sets how much current actually flows."}
        accent="water" />
    </div>
  );
}

function PlaygroundBeat({ forward, setForward, v, setV, onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="playground" data-screen-label="05 Playground" ref={ref}>
      <div className="beat-marker">§ 05 · all knobs unlocked</div>
      <h2 className="serif">Drive it<br/><em>by hand</em>.</h2>
      <p className="lede">
        {kids ? <>Change the push and flip the direction. See when the flap opens.</>
              : <>Vary the voltage and direction. Note how nothing flows below the turn-on threshold, even forward.</>}
      </p>
      <div style={{ display: "flex", gap: 10, marginTop: 20, flexWrap: "wrap" }}>
        <button onClick={() => setForward(!forward)} style={dirBtn(true, forward ? "var(--water)" : "var(--current)")}>
          {forward ? "▶ Forward" : "◀ Reverse"} · tap to flip
        </button>
      </div>
      <div style={{ marginTop: 20 }}>
        <Slider name="Voltage · push" value={v} min={0} max={12} step={0.5}
                unit="V" accent="water" onChange={setV} />
      </div>
      <div className="card" style={{ background: "transparent", marginTop: 20, padding: "16px 20px" }}>
        <div className="eyebrow" style={{ marginBottom: 8 }}>result</div>
        <p style={{ margin: 0, fontSize: 17 }}>
          {!forward
            ? <>Reverse — <span className="mono" style={{ color: "var(--current)" }}>blocked</span>, no flow.</>
            : v < 0.7
            ? <>Forward, but only <span className="mono">{v.toFixed(1)} V</span> — below the ~0.7 V toll. Barely a trickle.</>
            : <>Forward & above threshold — <span className="mono" style={{ color: "var(--water)" }}>flowing</span>.</>}
        </p>
      </div>
    </div>
  );
}

function dirBtn(active, color) {
  return {
    appearance: "none",
    border: `2px solid ${active ? color : "var(--rule-strong)"}`,
    background: active ? color : "transparent",
    color: active ? "var(--bg-card)" : "var(--ink)",
    padding: "11px 22px", borderRadius: 8, cursor: "pointer",
    fontFamily: "'IBM Plex Mono', monospace", fontSize: 13,
    letterSpacing: "0.1em", textTransform: "uppercase", fontWeight: 500,
  };
}

/* ── scrollyteller ─────────────────────────────────────────────────────── */
function LessonScrollyteller({ showCircuit, kids }) {
  const [forward, setForward] = useState(true);
  const [v, setV] = useState(6);
  const [mode, setMode] = useState("begin");
  const visHeight = showCircuit ? 340 : 540;
  return (
    <section className="lesson">
      <div className="lesson-scroll">
        <BigIdeaBeat onView={() => setMode("begin")} kids={kids} />
        <ForwardReverseBeat forward={forward} setForward={setForward} v={v}
                            onView={() => setMode("direction")} kids={kids} />
        <WhyBeat onView={() => setMode("why")} kids={kids} />
        <PredictBeat onView={() => setMode("predict")} kids={kids} />
        <PlaygroundBeat forward={forward} setForward={setForward} v={v} setV={setV}
                        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 · the check valve</div>
          <DiodeWaterScene voltage={v} forward={forward} height={visHeight} />
        </div>
        {showCircuit && (
          <div className="vis-block">
            <div className="stage-label">{kids ? "THE LOOP · one way only" : "THE LOOP · the diode blocks reverse"}</div>
            <LoopScene7 v={v} forward={forward} 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">Direction</span>
            <span className="ro-val" style={{ fontSize: 18, color: forward ? "var(--water)" : "var(--current)" }}>
              {forward ? "FWD" : "REV"}
            </span>
          </div>
          <div className="ro-i ro-active">
            <span className="ro-name">{kids ? "Flow" : "Current"}</span>
            <span className="ro-val">{fmt(forward && v > 0.7 ? (v - 0.7) / 3 : 0, 2)}<span className="ro-unit">A</span></span>
          </div>
          <div className="ro-p">
            <span className="ro-name">Valve</span>
            <span className="ro-val" style={{ fontSize: 18 }}>{forward && v > 0.3 ? "OPEN" : "SHUT"}</span>
          </div>
        </div>
      </aside>
    </section>
  );
}

/* ── worked example ────────────────────────────────────────────────────── */
function WorkedExampleSection({ kids }) {
  if (kids) return null;
  return (
    <section className="section" id="example" data-screen-label="06 Rectifier">
      <div className="marker">§ 06 · a real diode job · the rectifier</div>
      <div className="section-inner">
        <div className="two-col">
          <div>
            <h2 className="serif">A practical story:<br/><em>turning AC into DC</em>.</h2>
            <p className="lede">
              The wall socket delivers alternating current — it sloshes back and
              forth 50–60 times a second. But your laptop wants steady DC. How do
              you turn a slosh into a one-way flow?
            </p>
            <p>
              A diode. It only passes the forward half of each wave, chopping off
              the backward half. Four diodes in a clever arrangement (a <em>bridge
              rectifier</em>) flip the backward halves forward too — and a
              capacitor smooths the bumps into a near-steady voltage.
            </p>
            <p>
              Every phone charger, every power brick, contains this. It's the
              single most common job a diode does on Earth.
            </p>
          </div>
          <div>
            <div className="card" style={{ padding: "24px 26px" }}>
              <div className="eyebrow" style={{ marginBottom: 14 }}>the chain</div>
              <div className="mono" style={{ fontSize: 15, lineHeight: 1.9 }}>
                AC in &nbsp;→&nbsp; <span style={{ color: "var(--current)" }}>diodes</span> &nbsp;→&nbsp; bumpy DC<br/>
                bumpy DC &nbsp;→&nbsp; <span style={{ color: "var(--water)" }}>capacitor</span> &nbsp;→&nbsp; smooth DC<br/>
                smooth DC &nbsp;→&nbsp; your device
              </div>
              <p className="marg" style={{ marginTop: 16 }}>
                Diodes set direction (Ch 7), the capacitor stores and smooths
                (Ch 4). Two ideas you already know, combined.
              </p>
            </div>
            <div className="marg" style={{ marginTop: 18 }}>
              Next chapter we meet the AC wave itself — the thing the diode is
              taming here.
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

const Q_ADULT = [
  { q: "A diode allows current to flow…", kind: "concept", options: ["both directions equally", "one direction (forward) only", "only when cold", "never"], correct: 1, explain: "A diode conducts forward and blocks reverse — the electronic one-way valve." },
  { q: "The water analogy for a diode is a…", kind: "concept", options: ["bucket", "pinch", "check valve / one-way flap", "pump"], correct: 2, explain: "A check valve swings open with forward flow and shuts against reverse flow." },
  { q: "A silicon diode starts conducting at roughly…", kind: "concept", options: ["0 V", "0.7 V", "5 V", "12 V"], correct: 1, explain: "~0.7 V forward turn-on for silicon; below that, almost no current." },
  { q: "An LED installed backwards will…", kind: "concept", options: ["glow brighter", "stay dark", "explode instantly", "blink"], correct: 1, explain: "Reverse-biased, it blocks current and stays off." },
  { q: "Why does an LED still need a series resistor?", kind: "concept", options: ["the diode limits current already", "to set direction", "the diode sets direction but not current — the resistor limits it", "to store charge"], correct: 2, explain: "A diode fixes voltage drop, not current; the resistor limits the current." },
  { q: "Using diodes to turn AC into DC is called…", kind: "concept", options: ["amplifying", "rectifying", "switching", "resisting"], correct: 1, explain: "Rectification — passing only the forward halves of the AC wave." },
  {
    q: "An LED is lit. You flip the battery around. Now the LED…", kind: "concept",
    options: ["glows brighter", "stays the same", "goes dark — it blocks reverse current", "explodes immediately"],
    correct: 2,
    explain: "An LED is a diode: it conducts (and glows) one way only. Reversed, it simply blocks.",
  },
  {
    q: "A silicon diode in a 5 V circuit 'costs' about how much voltage to stay open?", kind: "math",
    options: ["0 V", "0.7 V", "2.5 V", "5 V"],
    correct: 1,
    explain: "The forward drop is ~0.7 V for silicon — a fixed toll, taken off the top, regardless of current.",
  },
  {
    q: "Why put a diode in series with a device's power input?", kind: "concept",
    options: ["to make it faster", "to protect it if the battery goes in backwards", "to raise the voltage", "to store energy"],
    correct: 1,
    explain: "Reverse the supply and the diode blocks — no current flows, nothing fries. Cheap insurance.",
  },
  {
    q: "A bridge rectifier uses four diodes so that…",
    kind: "concept",
    options: [
      "it can rectify twice as fast",
      "BOTH halves of the AC wave get flipped forward, not just one",
      "it doubles the voltage",
      "it stores charge like a capacitor",
    ],
    correct: 1,
    explain: "A single diode only passes half the wave — the other half is wasted. Four diodes in a bridge redirect the reverse half forward too, so nothing is thrown away.",
  },
  {
    q: "After the bridge rectifier, why is there still a capacitor in every phone charger?",
    kind: "concept",
    options: [
      "To block DC",
      "To smooth the rectified bumps into a steady voltage",
      "To set the diode's turn-on voltage",
      "To convert AC to a higher frequency",
    ],
    correct: 1,
    explain: "Rectified AC is a series of one-way bumps, not flat DC. The capacitor (Ch 4) charges on each bump and coasts through the gaps, smoothing it into something steady.",
  },
  {
    q: "Two diodes point the SAME direction in series. Compared to one diode, the pair…",
    kind: "concept",
    options: ["passes twice the current", "still only opens once BOTH ~0.7 V drops are met — needs ~1.4 V total", "cancels out completely", "blocks all current permanently"],
    correct: 1,
    explain: "Each diode still takes its own toll. Stack two and you need roughly double the forward voltage before either conducts.",
  },
];
const Q_KIDS = [
  { q: "A diode lets electricity flow…", kind: "concept", options: ["both ways", "one way only", "never", "in circles"], correct: 1, explain: "One way only — like a door that opens just one direction!" },
  { q: "A diode is like a water…", kind: "concept", options: ["bucket", "one-way flap", "splash", "balloon"], correct: 1, explain: "A one-way flap (check valve) — opens forward, shuts backward." },
  { q: "Put an LED in backwards and it…", kind: "concept", options: ["glows", "stays dark", "flies away", "gets cold"], correct: 1, explain: "Backwards means the flap is shut — no light." },
  { q: "An LED is a special diode that also…", kind: "concept", options: ["beeps", "glows", "freezes", "floats"], correct: 1, explain: "It makes light when current flows forward through it!" },
  { q: "A diode picks the… of the flow.", kind: "concept", options: ["color", "direction", "smell", "price"], correct: 1, explain: "Direction! It decides which way electricity may go." },
  {
    q: "A one-way valve lets water go…", kind: "concept",
    options: ["both ways", "one way only", "no way", "up only"],
    correct: 1,
    explain: "That's the whole trick — forward fine, backward blocked.",
  },
  {
    q: "If you put a light's battery in backwards, the diode…", kind: "concept",
    options: ["lets it break", "blocks the flow and keeps it safe", "doubles the push", "melts"],
    correct: 1,
    explain: "Backwards push gets blocked completely. The circuit just waits.",
  },
  {
    q: "An LED is special because when flow goes through it, it…", kind: "concept",
    options: ["gets cold", "makes light", "spins", "gets heavier"],
    correct: 1,
    explain: "An LED is a one-way valve that spends its toll as light!",
  },
  {
    q: "Why do phone chargers use FOUR one-way valves instead of one?",
    kind: "concept",
    options: ["To go faster", "So NEITHER half of the wobbly wall power gets wasted", "To make it louder", "To change the color"],
    correct: 1,
    explain: "One valve throws half the wave away. Four of them redirect BOTH halves forward — nothing wasted!",
  },
  {
    q: "After the four valves, why is there still a bucket (capacitor) inside the charger?",
    kind: "concept",
    options: ["To block the flow completely", "To smooth the bumpy flow into something steady", "To make it colorful", "To cool it down"],
    correct: 1,
    explain: "The valves leave a bumpy flow. The bucket fills and holds through the gaps, smoothing it into steady flow.",
  },
];

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: kids ? "One-way" : "The valve" },
    { id: "direction", label: "Direction" },
    { id: "why", label: kids ? "The toll" : "The drop" },
    { id: "predict", label: "Predict" },
    { id: "playground", label: "Playground" },
    ...(kids ? [] : [{ id: "example", label: "Rectifier" }]),
    { id: "practice", label: "Practice" },
    { id: "quiz", label: "Quiz" },
    { id: "whats-next", label: "What's next" },
  ];
  return (
    <>
      <ChapterStartMarker chapterN="07" />
      <ProgressBar />
      <TopBar currentN="07" chapterLabel="Ch. 07 — The One-Way Valve"
              audience={t.audience} setAudience={(v) => setTweak("audience", v)} />
      <ChapterNav items={navItems} />
      <main>
        <CoverPage chapterN="07"
                   chapterTitle={<>The One-Way<br/><em>Valve</em>.</>}
                   chapterSub="Chapter 7 · Diodes & direction"
                   kids={kids}
                   lede={kids
                     ? <>Meet the door that only opens one way. A <em>diode</em> lets electricity through in one direction and blocks it in the other — and an LED is one that glows while it does.</>
                     : <>Every part so far worked the same both ways. The diode breaks that symmetry — it passes current forward and blocks it backward. It's the one-way valve that makes power supplies, signals, and LEDs possible.</>} />
        <LessonScrollyteller showCircuit={t.showCircuit} kids={kids} />

        <CheckpointQuiz kids={kids} label="Checkpoint 1" pick={2}
          title={kids ? "Quick check!" : "Did it stick?"}
          questions={[
            {
              q: "Pushed in the FORWARD direction, the one-way valve…",
              options: [kids ? "Opens (after a small toll of push) and the flow passes" : "Opens once ~0.7 V is paid, then conducts", "Stays shut no matter what", "Leaks backwards", "Explodes"],
              correct: 0,
              explain: kids ? "Forward is its friendly direction — it swings open once the push is strong enough to lift the flap, then water flows freely."
                            : "A silicon diode conducts forward after its ~0.7 V threshold; beyond that it passes current with only that small fixed drop.",
            },
            {
              q: "Pushed BACKWARD, the valve…",
              options: ["Blocks — essentially no flow", "Opens wider", "Conducts half as much", "Heats up and melts"],
              correct: 0,
              explain: kids ? "Backward pressure just presses the flap tighter shut. Nothing gets through — that's its whole job."
                            : "Reverse bias seats the valve: only a negligible leakage flows. (Push far enough past its rated reverse voltage and it breaks down — avoid.)",
            },
            {
              q: kids ? "The small 'toll' the valve charges is…" : "The diode's forward drop (~0.7 V) is…",
              options: [kids ? "A little bite of the push, lost opening the flap" : "A roughly fixed bite of voltage, lost across the diode", "Half of the current", "One ohm of resistance", "A myth"],
              correct: 0,
              explain: kids ? "Opening the flap costs a fixed bit of push every time — the rest of the push carries on to the rest of the circuit."
                            : "It behaves like a fixed fee, not a proportional one: ~0.6–0.7 V for silicon, ~2–3 V for LEDs — subtract it before sizing your resistor.",
            },
            {
              q: kids ? "The valve's two ends have names: the way IN and the way OUT are the…" : "A diode's two terminals are named…",
              options: [kids ? "Anode (in) and cathode (out)" : "Anode (current in) and cathode (current out)", "Base and emitter", "Plus and minus", "Source and drain"],
              correct: 0,
              explain: kids ? "ANODE is the friendly way in, CATHODE is the way out — the stripe printed on a real diode marks the cathode end."
                            : "Conventional current enters the anode and exits the cathode; the painted band on the package marks the cathode. On an LED, the long leg is the anode.",
            },
            {
              q: "An LED is…",
              options: ["A one-way valve that glows when flow passes", "A battery", "A pinch that stays cold", "A switch you flip"],
              correct: 0,
              explain: kids ? "Same one-way flap — but this one lights up whenever water rushes through it the right way!"
                            : "Light-Emitting Diode: all the diode rules apply (direction, threshold), plus photons when forward current flows. Hence the polarity legs.",
            },
          ]} />

        <WorkedExampleSection kids={kids} />

        <CheckpointQuiz kids={kids} label="Checkpoint 2" pick={2}
          title={kids ? "Spot it in real life!" : "Out in the wild."}
          intro={kids ? "One-way valves quietly save your gadgets every day." : "Where the one-way valve earns its keep."}
          questions={[
            {
              q: "You put the batteries in backwards and the gadget just does nothing — no damage. Thank…",
              options: ["A protection diode blocking the reverse flow", "Thicker wires", "The on/off switch", "Luck"],
              correct: 0,
              explain: kids ? "A one-way valve at the door said 'nope' to the backwards push, so nothing inside ever felt it."
                            : "A series or shunt protection diode makes reverse polarity an open circuit (or a blown fuse) instead of dead electronics.",
            },
            {
              q: "At night a solar panel could quietly drain its battery backwards. The classic fix is…",
              options: ["A one-way valve between panel and battery", "A bigger panel", "A longer cable", "Unplugging it every evening"],
              correct: 0,
              explain: kids ? "Daytime: water flows panel → battery. Night: the valve slams shut so the battery can't trickle back out through the dark panel."
                            : "A blocking diode passes charge current and blocks reverse discharge through the panel when its voltage falls below the battery's.",
            },
            {
              q: "Your USB charger turns the wall's back-and-forth (AC) into one-way (DC) using…",
              options: ["One-way valves that only pass pushes in one direction", "A very long wire", "A switch flipped fast by hand", "A heavier plug"],
              correct: 0,
              explain: kids ? "The wall pushes back-and-forth, but a team of one-way valves only lets the forward shoves through — out comes one-way flow."
                            : "A rectifier — typically four diodes in a bridge — steers both halves of the AC swing into the same output direction. Chapter 8 meets the wave itself.",
            },
            {
              q: "An LED wired backwards in your circuit will…",
              options: ["Stay dark but (usually) unhurt — it just blocks", "Explode instantly", "Glow a different color", "Drain the battery fast"],
              correct: 0,
              explain: kids ? "Backwards, the flap stays shut: no flow, no glow, no harm. Flip it around and it lights right up."
                            : "Reverse-biased it simply blocks — the usual first debugging question for a dark LED. (Only exotic reverse voltages beyond its rating cause damage.)",
            },
          ]} />

        <PracticeProblems chapterN="07" kids={kids} problems={[
          (rng) => {
            const v = rng.int(5, 12, 1);
            return {
              q: { adult: `${v} V passes through one diode with a 0.7 V forward drop. What voltage comes out?`, kids: `A one-way valve 'uses up' 0.7 of the push. Start with ${v}. What's left?` },
              unit: "V", answer: +(v - 0.7).toFixed(1), tol: 0.04,
              hint: "Subtract the 0.7 V diode drop.",
              solution: { adult: `${v} V − 0.7 V = ${+(v - 0.7).toFixed(1)} V.`, kids: `${v} − 0.7 = ${+(v - 0.7).toFixed(1)}.` } };
          },
          (rng) => {
            const v = rng.int(9, 18, 1);
            return {
              q: { adult: `A bridge rectifier sends current through two diodes (each 0.7 V). From a ${v} V peak input, what is the peak output?`, kids: `Two valves in the path, each using up 0.7. Start at ${v}. What's left?` },
              unit: "V", answer: +(v - 1.4).toFixed(1), tol: 0.04,
              hint: "Two diode drops: subtract 2 × 0.7 V.",
              solution: { adult: `${v} V − (2 × 0.7 V) = ${v} − 1.4 = ${+(v - 1.4).toFixed(1)} V.`, kids: `${v} − 0.7 − 0.7 = ${+(v - 1.4).toFixed(1)}.` } };
          },
          (rng) => {
            const vf = rng.pick([1.8, 2, 2.2]), v = rng.int(5, 12, 1), ma = rng.pick([10, 15, 20]);
            const r = Math.round((v - vf) / (ma / 1000));
            return {
              q: { adult: `An LED (${vf} V drop) runs from ${v} V at ${ma} mA. What series resistor do you need?`, kids: `The LED uses up ${vf} of the ${v}, leaving ${+(v - vf).toFixed(1)} for the pinch. You want a flow of ${ma} thousandths. Pinch = leftover ÷ flow.` },
              unit: "Ω", answer: r, tol: 0.05,
              hint: `R = (${v} − ${vf}) V ÷ ${ma / 1000} A.`,
              solution: { adult: `R = (${v} − ${vf}) ÷ ${ma / 1000} = ${+(v - vf).toFixed(1)} ÷ ${ma / 1000} = ${r} Ω.`, kids: `(${v} − ${vf}) ÷ ${ma / 1000} = ${r}.` } };
          },
        ]} />

        <ChapterQuiz chapterN="07"
          title={kids ? "Quick quiz!" : "Check your understanding."}
          intro={kids ? "Five quick questions about one-way valves." : "Diodes & direction. 70% to pass; retry freely."}
          questions={kids ? Q_KIDS : Q_ADULT} pick={5} />
        <WhatsNext currentN="07" kids={kids}
          summary={kids
            ? <>You learned the one-way valve! Next: the back-and-forth wave that diodes love to tame — AC.</>
            : <>You've got the diode — direction control, the 0.7 V toll, and rectification. Next we meet the AC wave itself: why wall power sloshes, and what frequency means.</>}
          prevHref="chapter6.html" prevLabel="Chapter 6"
          nextHref="chapter8.html" nextLabel="Chapter 8 · The Wave" />
      </main>
      <TweaksPanel title="Tweaks">
        <CommonTweaks t={t} setTweak={setTweak}
          animationToggles={[{ key: "showCircuit", label: "Show circuit" }]} />
      </TweaksPanel>
      <GlossaryFab />
    </>
  );
}

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