/* chapter5.jsx — Chapter 5: The Switch */

const { useState, useEffect, useRef } = React;

function BigIdeaBeat({ onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="begin" data-screen-label="01 What is a switch" ref={ref}>
      <div className="beat-marker">§ 01 · open or closed</div>
      {kids ? (
        <>
          <h2 className="serif">A switch<br/>is a <em>valve</em>.</h2>
          <p className="lede">
            Open the valve, water flows. Close it, water stops. That's it.
          </p>
          <p>
            A light switch on your wall is the exact same idea — only with
            electricity. Flick it on, current flows, bulb glows. Flick it
            off, no current, no glow.
          </p>
        </>
      ) : (
        <>
          <h2 className="serif">A switch is the simplest<br/>thing in electronics.</h2>
          <p className="lede">
            Two states. Open — the wire is broken, no current can flow.
            Closed — the wire is whole, current flows like normal.
          </p>
          <p>
            The water analogy: a valve in the pipe. Open valve, flow. Shut
            valve, no flow.
          </p>
          <div className="marg" style={{ marginTop: 12 }}>
            We've been quietly assuming switches all along — every circuit
            we drew had an implicit "battery is connected" state. Now we
            make it explicit, and toggleable.
          </div>
        </>
      )}
      <div className="pull">
        {kids ? "On or off. Two choices. That's the whole gadget." : "Two states. From that simple kernel — your phone, your laptop, the internet."}
      </div>
    </div>
  );
}

function OnOffBeat({ on, setOn, onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="on-off" data-screen-label="02 On Off" ref={ref}>
      <div className="beat-marker">§ 02 · two states</div>
      <h2 className="serif">Click it.<br/>Watch it <em>happen</em>.</h2>
      <p className="lede">
        {kids
          ? "Tap the buttons. The valve opens and closes. The bulb glows and goes dark."
          : "Toggle the switch. Watch the whole circuit go from alive to dead and back."}
      </p>

      <div style={{ display: "flex", gap: 10, marginTop: 24, flexWrap: "wrap" }}>
        <button onClick={() => setOn(true)}
                style={{
                  appearance: "none",
                  border: `1.5px solid ${on ? "var(--water)" : "var(--rule-strong)"}`,
                  background: on ? "var(--water)" : "transparent",
                  color: on ? "var(--bg-card)" : "var(--ink)",
                  padding: "12px 30px",
                  borderRadius: 999,
                  fontFamily: "'IBM Plex Mono', monospace",
                  fontSize: 13,
                  letterSpacing: "0.18em",
                  textTransform: "uppercase",
                  cursor: "pointer",
                  fontWeight: 600,
                }}>
          ◉ On
        </button>
        <button onClick={() => setOn(false)}
                style={{
                  appearance: "none",
                  border: `1.5px solid ${!on ? "var(--current)" : "var(--rule-strong)"}`,
                  background: !on ? "var(--current)" : "transparent",
                  color: !on ? "var(--bg-card)" : "var(--ink)",
                  padding: "12px 30px",
                  borderRadius: 999,
                  fontFamily: "'IBM Plex Mono', monospace",
                  fontSize: 13,
                  letterSpacing: "0.18em",
                  textTransform: "uppercase",
                  cursor: "pointer",
                  fontWeight: 600,
                }}>
          ○ Off
        </button>
      </div>

      <div className="card" style={{ background: "transparent", marginTop: 24, padding: "18px 22px" }}>
        <div className="eyebrow" style={{ marginBottom: 10 }}>state</div>
        <p style={{ margin: 0, fontSize: 18 }}>
          The switch is <span className="mono" style={{ color: on ? "var(--water)" : "var(--current)" }}>{on ? "CLOSED" : "OPEN"}</span>.
          The bulb is <span className="mono" style={{ color: on ? "var(--current)" : "var(--ink-faint)" }}>{on ? "LIT" : "DARK"}</span>.
        </p>
      </div>
    </div>
  );
}

function BinaryBeat({ onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="binary" data-screen-label="03 Binary" ref={ref}>
      <div className="beat-marker">§ 03 · just two numbers</div>
      <h2 className="serif">Two states.<br/>Call them <em>0 and 1</em>.</h2>
      {kids ? (
        <>
          <p className="lede">
            We can give the two states <em>names</em>:
            "off" is <span className="mono">0</span>, "on" is <span className="mono">1</span>.
          </p>
          <p>
            With just <span className="mono">0</span>s and <span className="mono">1</span>s
            (called <em>bits</em>), you can do everything a computer does:
            store pictures, send messages, play videos. Everything.
          </p>
          <p>
            But you'd need <em>billions</em> of switches working together.
            That's literally what a phone chip is.
          </p>
        </>
      ) : (
        <>
          <p className="lede">
            Once you commit to just two states, you've invented <em>binary</em>.
            Off = <span className="mono">0</span>. On = <span className="mono">1</span>.
            Every digital signal in every computer is built from this dichotomy.
          </p>
          <p>
            Eight switches together hold a <em>byte</em>:{" "}
            <span className="mono">00000000</span> to{" "}
            <span className="mono">11111111</span>. That's 256 distinct
            patterns — enough to encode every Latin character.
          </p>
          <p>
            A modern CPU has <em>tens of billions</em> of switches, each one
            essentially a fancy version of the toggle you just flicked. The
            whole digital world is this idea, repeated obsessively.
          </p>
          <div className="card" style={{ background: "transparent", marginTop: 18, padding: "18px 22px" }}>
            <div className="eyebrow" style={{ marginBottom: 10 }}>some example bytes</div>
            <div className="mono" style={{ fontSize: 16, lineHeight: 1.7 }}>
              01000001 = "A"<br/>
              00110001 = "1"<br/>
              11111111 = 255 (all on)<br/>
              00000000 = 0 (all off)
            </div>
          </div>
        </>
      )}
    </div>
  );
}

function LogicBeat({ a, b, setA, setB, onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="logic" data-screen-label="04 Logic" ref={ref}>
      <div className="beat-marker">§ 04 · combining switches</div>
      <h2 className="serif">Two switches.<br/><em>Two ways to combine</em>.</h2>
      <p className="lede">
        {kids
          ? <>Hook two switches into one circuit. Series means both have to be ON. Parallel means either one will do.</>
          : <>Stick two switches in series and you've built an <em>AND</em> gate — the bulb lights only if both are closed. Wire them in parallel and you've built an <em>OR</em> — either one suffices.</>}
      </p>

      <div style={{ display: "flex", gap: 12, marginTop: 22 }}>
        <button onClick={() => setA(!a)}
                style={btnStyle(a, "A")}>
          A = {a ? 1 : 0}
        </button>
        <button onClick={() => setB(!b)}
                style={btnStyle(b, "B")}>
          B = {b ? 1 : 0}
        </button>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(210px, 1fr))", gap: 20, marginTop: 24 }}>
        <div style={{ background: "var(--bg-card)", border: "1px solid var(--rule)", borderRadius: 8, padding: 14, minWidth: 0 }}>
          <LogicGateBox kind="and" a={a} b={b} />
        </div>
        <div style={{ background: "var(--bg-card)", border: "1px solid var(--rule)", borderRadius: 8, padding: 14, minWidth: 0 }}>
          <LogicGateBox kind="or" a={a} b={b} />
        </div>
      </div>

      {!kids && (
        <div className="marg" style={{ marginTop: 18 }}>
          AND, OR, plus a third gate called <em>NOT</em> (which inverts a
          single input) is enough to build any digital function — adders,
          multipliers, processors, the whole stack. This is the kernel of{" "}
          <em>Boolean algebra</em>, invented by George Boole in 1854 and
          retroactively perfect for computing.
        </div>
      )}
    </div>
  );
}

function btnStyle(on, label) {
  return {
    appearance: "none",
    border: `1.5px solid ${on ? "var(--water)" : "var(--rule-strong)"}`,
    background: on ? "var(--water)" : "transparent",
    color: on ? "var(--bg-card)" : "var(--ink)",
    padding: "10px 22px",
    borderRadius: 999,
    fontFamily: "'IBM Plex Mono', monospace",
    fontSize: 13,
    letterSpacing: "0.16em",
    cursor: "pointer",
    fontWeight: 500,
    minWidth: 90,
  };
}

function PredictBeat({ onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="predict" data-screen-label="05 Predict" ref={ref}>
      <div className="beat-marker">§ 05 · check your gut</div>
      <h2 className="serif">A puzzle<br/>(or two).</h2>

      <PredictReveal
        question={kids
          ? "You have an AND gate (two switches in series). What's the only way to get the bulb to light?"
          : "AND gate. The output is on when…"
        }
        options={[
          "Either A or B (or both) is on",
          "Both A and B are on",
          "Either A or B but not both",
          "Neither A nor B is on",
        ]}
        correct={1}
        explanation={kids
          ? "Series means the water has to get through BOTH valves. If even one is shut, no flow. Both have to be open."
          : "Series demands a continuous path. Open either switch and the loop breaks; current = 0. Both must be closed for I > 0."
        }
        accent="water"
      />

      <PredictReveal
        question={kids
          ? "You wire 4 light switches in a long row (series). One of them is busted permanently OPEN. What can the lights do?"
          : "Four switches in series. One is stuck open. What's the output?"
        }
        options={[
          "It depends on the others",
          "Always on",
          "Always off",
          "It alternates",
        ]}
        correct={2}
        explanation={kids
          ? "Stuck open = a permanent gap. Doesn't matter what the other three do — the chain is broken. This is exactly the Christmas-lights problem from chapter 2!"
          : "An open in a series chain breaks the loop. I = 0 regardless of every other switch. (See: every horror story about pre-1970s Christmas lights.)"
        }
        accent="current"
      />
    </div>
  );
}

function PlaygroundBeat({ on, setOn, V, setV, R, setR, onView, kids }) {
  const ref = useInViewCallback(onView);
  const I = on ? V / R : 0;
  const P = V * I;
  return (
    <div className="beat" id="playground" data-screen-label="06 Playground" ref={ref}>
      <div className="beat-marker">§ 06 · all knobs unlocked</div>
      <h2 className="serif">Drive it<br/><em>by hand</em>.</h2>
      <p className="lede">
        {kids ? <>Toggle on and off. Slide everything else.</>
              : <>The switch gates everything that came before — voltage, resistance, power. The switch decides if anything happens at all.</>}
      </p>

      <div style={{ display: "flex", gap: 10, marginTop: 22 }}>
        <button onClick={() => setOn(!on)}
                style={{
                  appearance: "none",
                  border: `2px solid ${on ? "var(--water)" : "var(--rule-strong)"}`,
                  background: on ? "var(--water)" : "transparent",
                  color: on ? "var(--bg-card)" : "var(--ink)",
                  padding: "14px 32px",
                  borderRadius: 999,
                  fontFamily: "'IBM Plex Mono', monospace",
                  fontSize: 14,
                  letterSpacing: "0.18em",
                  textTransform: "uppercase",
                  cursor: "pointer",
                  fontWeight: 600,
                }}>
          {on ? "◉ ON · CLOSED" : "○ OFF · OPEN"}
        </button>
      </div>

      <div style={{ marginTop: 22, display: "flex", flexDirection: "column", gap: 6 }}>
        <Slider name="V · battery" value={V} min={0} max={12} step={0.5}
                unit="V" accent="water" onChange={setV} />
        <Slider name="R · resistance" value={R} min={0.5} max={10} step={0.1}
                unit="Ω" accent="" onChange={setR} />
      </div>

      <div className="card" style={{ background: "transparent", marginTop: 22, padding: "16px 20px" }}>
        <div className="eyebrow" style={{ marginBottom: 10 }}>state</div>
        <p style={{ margin: 0, fontSize: 17 }}>
          {on ? <>I = <span className="mono" style={{ color: "var(--current)" }}>{fmt(I, 2)} A</span> · P = <span className="mono">{fmt(P, 1)} W</span></>
              : <>Switch open — nothing flows. The whole circuit is dead.</>}
        </p>
      </div>
    </div>
  );
}

/* ─── LessonScrollyteller ───────────────────────────────────────────────── */
function LessonScrollyteller({ showCircuit, kids }) {
  const [on, setOn] = useState(true);
  const [V, setV] = useState(9);
  const [R, setR] = useState(3);
  const [a, setA] = useState(true);
  const [b, setB] = useState(false);
  const [mode, setMode] = useState("begin");

  const visHeight = showCircuit ? 340 : 540;

  return (
    <section className="lesson">
      <div className="lesson-scroll">
        <BigIdeaBeat onView={() => setMode("begin")} kids={kids} />
        <OnOffBeat on={on} setOn={setOn} onView={() => setMode("on-off")} kids={kids} />
        <BinaryBeat onView={() => setMode("binary")} kids={kids} />
        <LogicBeat a={a} b={b} setA={setA} setB={setB}
                   onView={() => setMode("logic")} kids={kids} />
        <PredictBeat onView={() => setMode("predict")} kids={kids} />
        <PlaygroundBeat on={on} setOn={setOn} V={V} setV={setV} R={R} 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 · valve open or shut</div>
          <ValveScene voltage={V} R={R} on={on} height={visHeight} />
        </div>
        {showCircuit && (
          <div className="vis-block">
            <div className="stage-label">{kids ? "THE LOOP · one break stops it all" : "THE LOOP · the switch breaks the ring"}</div>
            <LoopScene5 v={V} r={R} on={on} kids={kids} />
          </div>
        )}
        <div className="vis-readout">
          <div className="ro-v">
            <span className="ro-name">V</span>
            <span className="ro-val">{fmt(V, 1)}<span className="ro-unit">V</span></span>
          </div>
          <div className="ro-r">
            <span className="ro-name">R</span>
            <span className="ro-val">{fmt(R, 1)}<span className="ro-unit">Ω</span></span>
          </div>
          <div className="ro-i">
            <span className="ro-name">State</span>
            <span className="ro-val" style={{ color: on ? "var(--water)" : "var(--current)" }}>
              {on ? "1" : "0"}
            </span>
          </div>
          <div className="ro-p ro-active">
            <span className="ro-name">I</span>
            <span className="ro-val">{fmt(on ? V / R : 0, 2)}<span className="ro-unit">A</span></span>
          </div>
        </div>
      </aside>
    </section>
  );
}

/* ─── Worked example (adult): basement light ───────────────────────────── */
function WorkedExampleSection({ kids }) {
  if (kids) return null;
  return (
    <section className="section" id="example" data-screen-label="07 Two-way switch">
      <div className="marker">§ 07 · the two-way switch</div>
      <div className="section-inner">
        <div className="two-col">
          <div>
            <h2 className="serif">A practical story:<br/><em>the staircase light</em>.</h2>
            <p className="lede">
              A switch at the bottom of the stairs and another at the top —
              <em>either</em> one can toggle the same light. Neither is "the
              on switch." Both are full toggles.
            </p>
            <p>
              The trick is a pair of <em>SPDT</em> (single-pole, double-throw)
              switches — each one routes the wire down one of two paths. The
              two paths cross at the bulb. The light is on when both switches
              pick the <em>same</em> path, off when they pick opposite paths.
            </p>
            <p>
              In logic terms, that's an <em>XOR</em> — exclusive or. Output is
              1 if A ≠ B. The first circuit a kid wires correctly without
              instructions feels like magic. It's just XOR.
            </p>
          </div>
          <div>
            <div className="card" style={{ padding: "24px 26px" }}>
              <div className="eyebrow" style={{ marginBottom: 14 }}>XOR truth table</div>
              <div className="mono" style={{ fontSize: 17, lineHeight: 2 }}>
                A=0, B=0 → <span style={{ color: "var(--ink-faint)" }}>0 (off)</span><br/>
                A=0, B=1 → <span style={{ color: "var(--current)" }}>1 (on)</span><br/>
                A=1, B=0 → <span style={{ color: "var(--current)" }}>1 (on)</span><br/>
                A=1, B=1 → <span style={{ color: "var(--ink-faint)" }}>0 (off)</span>
              </div>
              <p className="marg" style={{ marginTop: 18 }}>
                XOR is the heart of binary addition. The "carry" bit when
                summing 1+1=10 is exactly XOR's pattern. Half a CPU is built
                from XOR.
              </p>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

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

const ADULT_QUIZ = [
  {
    q: "A switch has how many useful states?", kind: "concept",
    options: ["One", "Two: open and closed", "Three", "Infinitely many"],
    correct: 1,
    explain: "Open (no current) and closed (current flows). Two states — the seed of binary.",
  },
  {
    q: "An open switch in a circuit means…", kind: "concept",
    options: ["current flows freely", "the wire is broken, no current", "the voltage is zero", "the resistor melts"],
    correct: 1,
    explain: "Open = a gap in the loop. No complete path, so no current.",
  },
  {
    q: "Two switches in SERIES light a bulb only when…", kind: "concept",
    options: ["either is closed", "both are closed", "both are open", "neither is closed"],
    correct: 1,
    explain: "Series needs a continuous path — both must be closed. That's an AND gate.",
  },
  {
    q: "Two switches in PARALLEL light a bulb when…", kind: "concept",
    options: ["both are closed only", "either one (or both) is closed", "both are open", "never"],
    correct: 1,
    explain: "Parallel gives two paths — either closed switch completes the circuit. That's an OR gate.",
  },
  {
    q: "Why are switches the foundation of digital computers?", kind: "concept",
    options: [
      "They're cheap",
      "Two states map to 0 and 1, and gates build any logic",
      "They glow nicely",
      "They store water",
    ],
    correct: 1,
    explain: "On/off = 1/0. Combine switches into AND/OR/NOT and you can build any digital function.",
  },
  {
    q: "Eight switches together can represent how many distinct patterns?", kind: "math",
    options: ["8", "16", "64", "256"],
    correct: 3,
    explain: "Each switch doubles the count: 2⁸ = 256 patterns. That's one byte.",
  },
  {
    q: "A NOT gate (inverter) does what to its input?", kind: "concept",
    options: ["copies it", "flips it: 0→1, 1→0", "doubles it", "deletes it"],
    correct: 1,
    explain: "NOT inverts: a 1 becomes 0 and a 0 becomes 1. With AND/OR/NOT you can build anything.",
  },
  {
    q: "A stairway light has a switch at the top AND the bottom. Which one is 'the on switch'?",
    kind: "concept",
    options: ["The bottom one", "The top one", "Neither — each is a full toggle; the light responds to the COMBINATION", "Whichever you flip first"],
    correct: 2,
    explain: "Two SPDT switches each route the wire down one of two paths. The bulb lights when both pick the same path — so flipping EITHER switch toggles the light. That's XOR in your wall.",
  },
  {
    q: "An XOR gate outputs 1 when…",
    kind: "concept",
    options: ["both inputs are 1", "both inputs are 0", "its inputs are different", "its inputs are equal"],
    correct: 2,
    explain: "Exclusive-or: 1 if A ≠ B. It's the stairway-light circuit — and the heart of binary addition (the carry bit is XOR's pattern).",
  },
  {
    q: "Two switches, four gates' worth of behavior. What decides whether they act as AND or OR?",
    kind: "concept",
    options: ["The brand of switch", "How they're WIRED — series makes AND, parallel makes OR", "The battery voltage", "The bulb's resistance"],
    correct: 1,
    explain: "Same parts, different shape: series demands both closed (AND); parallel accepts either (OR). Logic is topology.",
  },
];

const KIDS_QUIZ = [
  {
    q: "A switch is like a…", kind: "concept",
    options: ["bucket", "valve", "battery", "magnet"],
    correct: 1,
    explain: "A valve! Open lets water through, closed stops it.",
  },
  {
    q: "When the switch is OFF (open), the bulb is…", kind: "concept",
    options: ["bright", "dark", "warm", "blue"],
    correct: 1,
    explain: "Open switch = no flow = dark bulb.",
  },
  {
    q: "We can call the two states by numbers. Off is — and on is —.", kind: "concept",
    options: ["1 and 2", "0 and 1", "A and B", "yes and maybe"],
    correct: 1,
    explain: "Off = 0, on = 1. Those two numbers build everything a computer does!",
  },
  {
    q: "Two switches in a ROW (series). The bulb lights when…", kind: "concept",
    options: ["either one is on", "both are on", "both are off", "never"],
    correct: 1,
    explain: "In a row, the water must get through BOTH — so both have to be on.",
  },
  {
    q: "Two switches SIDE BY SIDE (parallel). The bulb lights when…", kind: "concept",
    options: ["both are off", "either one is on", "only both are on", "never"],
    correct: 1,
    explain: "Two roads — either open path lets the water through.",
  },
  {
    q: "How many states does a light switch have?", kind: "concept",
    options: ["one", "two", "ten", "a hundred"],
    correct: 1,
    explain: "Just two: on and off. That's all you need to build a computer!",
  },
  {
    q: "Computers think using only…", kind: "concept",
    options: ["colors", "0s and 1s", "letters", "pictures"],
    correct: 1,
    explain: "Everything inside is just 0s and 1s — offs and ons — billions of them.",
  },
  {
    q: "The stairs have a switch at the top AND the bottom. Flipping EITHER one…",
    kind: "concept",
    options: ["does nothing", "toggles the light", "breaks the light", "only works at night"],
    correct: 1,
    explain: "Neither switch is 'the on switch' — each one flips the light from wherever you are. Clever wiring!",
  },
  {
    q: "With 8 switches you can make enough patterns for…",
    kind: "concept",
    options: ["just 8 things", "every letter of the alphabet and more", "only numbers", "nothing useful"],
    correct: 1,
    explain: "Each switch doubles the patterns: 8 switches = 256 patterns — enough for every letter, number, and symbol!",
  },
];

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

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useCrossChapterPersistence(t, setTweak);
  useEffect(() => { document.body.setAttribute("data-theme", t.theme); }, [t.theme]);
  const kids = t.audience === "kids";
  const navItems = [
    { id: "cover", label: "Cover" },
    { id: "begin", label: "Open/closed" },
    { id: "on-off", label: "Two states" },
    { id: "binary", label: kids ? "0 and 1" : "Binary" },
    { id: "logic", label: kids ? "Two switches" : "Logic" },
    { id: "predict", label: "Predict" },
    { id: "playground", label: "Playground" },
    ...(kids ? [] : [{ id: "example", label: "Stairs" }]),
    { id: "practice", label: "Practice" },
    { id: "quiz", label: "Quiz" },
    { id: "whats-next", label: "What's next" },
  ];
  return (
    <>
      <ChapterStartMarker chapterN="05" />
      <ProgressBar />
      <TopBar currentN="05" chapterLabel="Ch. 05 — The Switch"
              audience={t.audience}
              setAudience={(v) => setTweak("audience", v)} />
      <ChapterNav items={navItems} />
      <main>
        <CoverPage chapterN="05"
                   chapterTitle={<>The <em>Switch</em>.</>}
                   chapterSub="Chapter 5 · On, off, and binary"
                   kids={kids}
                   lede={kids
                     ? <>The simplest gadget in electronics: on or off. Two states. Believe it or not, that's enough to build every computer ever made.</>
                     : <>Two states. From that brutally simple idea, the entire digital revolution. We'll meet binary, hint at logic gates, and set up the punchline for Chapter 6 — the thing that automates the switch.</>
                   } />
        <LessonScrollyteller showCircuit={t.showCircuit} kids={kids} />

        <CheckpointQuiz kids={kids} label="Checkpoint 1" pick={2}
          title={kids ? "Quick check!" : "Did it stick?"}
          questions={[
            {
              q: "Two switches in SERIES feed one bulb. The bulb lights when…",
              options: ["BOTH are closed — that's AND", "Either one is closed", "Neither is closed", "It never lights"],
              correct: 0,
              explain: kids ? "The water has to get through both gates in a row. One shut gate anywhere blocks the whole path."
                            : "Series switches form an AND: the single path must be complete end-to-end, so every contact has to be closed.",
            },
            {
              q: "Two switches in PARALLEL feed one bulb. It lights when…",
              options: ["At least one is closed — that's OR", "Only when both are closed", "Only when both are open", "Never"],
              correct: 0,
              explain: kids ? "Two doors into the same room — the water only needs ONE of them open to get through."
                            : "Parallel switches form an OR: any closed branch completes a path, regardless of the others.",
            },
            {
              q: "An OPEN switch in the pipe is like…",
              options: ["A fully shut valve — no path, no flow at all", "A tighter pinch that still leaks", "A bigger barrel", "A loose pinch"],
              correct: 0,
              explain: kids ? "Open switch = gate slammed shut. Not a trickle gets past — that's what makes it different from a pinch."
                            : "A switch isn't a resistor: open means effectively infinite resistance — zero current, full stop. Closed means nearly zero resistance.",
            },
            {
              q: "Digital thinking treats a switch as…",
              options: ["Fully open or fully closed — two clean states, nothing in between", "A dimmer with many levels", "A heater", "A battery"],
              correct: 0,
              explain: kids ? "On or off, yes or no, 1 or 0. Two clean answers — that's the secret language computers are built on."
                            : "Binary abstraction: two unambiguous states resist noise and copy perfectly. Every bit in every computer is this idea, multiplied.",
            },
          ]} />

        <WorkedExampleSection kids={kids} />

        <CheckpointQuiz kids={kids} label="Checkpoint 2" pick={2}
          title={kids ? "Spot it in real life!" : "Out in the wild."}
          intro={kids ? "AND and OR are guarding things all around you." : "Logic you've already been living with."}
          questions={[
            {
              q: "A microwave won't run unless the door is shut AND the start button is pressed. As switches, that's…",
              options: ["Two switches in series", "Two switches in parallel", "No switches at all", "A dimmer"],
              correct: 0,
              explain: kids ? "Both conditions must be true at once — two gates in a row. Door open? Path broken, no cooking. That's a safety AND."
                            : "Safety interlocks are series ANDs: the door switch and the start switch must both close to complete the magnetron's path.",
            },
            {
              q: "The front AND back doorbell buttons both ring the same chime. They're wired…",
              options: ["In parallel — either button completes the path (OR)", "In series — you'd need two visitors", "To different chimes", "Backwards"],
              correct: 0,
              explain: kids ? "Either door, same ding-dong! Two side-by-side paths into one chime — only one needs pressing."
                            : "Multiple triggers for one load is the classic OR: parallel buttons, any closure rings it. (Series would need simultaneous visitors.)",
            },
            {
              q: "A car beeps when the engine is on AND a seatbelt is unbuckled. The 'AND' behaves like…",
              options: ["Two conditions in series — both must pass for the beep", "Two in parallel — either one beeps", "A bigger battery", "A loose wire"],
              correct: 0,
              explain: kids ? "The beeper only gets its path when BOTH things are true at the same time — gates in a row again."
                            : "Condition chaining is series logic, whether done with real contacts or in software: engine-running AND belt-open → annunciator path complete.",
            },
            {
              q: "Why do computers love switches so much?",
              options: ["Two clean states make perfect yes/no symbols — bits", "Switches stay warm", "Switches store water", "They don't — computers avoid them"],
              correct: 0,
              explain: kids ? "Billions of tiny on/off gates, each holding a yes or a no — stack enough of them and you can count, remember, and decide!"
                            : "Unambiguous binary states survive noise, copy losslessly, and compose into logic. Chapter 6's transistor is exactly this switch, shrunk and automated.",
            },
          ]} />

        <PracticeProblems chapterN="05" kids={kids}
          intro={kids ? "Switch puzzles — count the combinations, just like a real designer does." : "Logic-counting drills in the style of the Beacon project. Enter a number and check it."}
          problems={[
          (rng) => {
            const n = rng.int(3, 5, 1);
            return {
              q: { adult: `How many distinct on/off combinations can ${n} switches make?`, kids: `Each switch is on or off. With ${n} switches, how many different combinations?` },
              unit: "", answer: Math.pow(2, n),
              hint: "Each switch doubles the count: 2 × 2 × …",
              solution: { adult: `Each switch has 2 states, so 2^${n} = ${Math.pow(2, n)} combinations.`, kids: `${Array(n).fill(2).join(" × ")} = ${Math.pow(2, n)}.` } };
          },
          (rng) => {
            const n = rng.int(3, 5, 1);
            return {
              q: { adult: `${n} switches are wired in series (an AND gate). Of all ${Math.pow(2, n)} combinations, how many light the lamp?`, kids: `All ${n} switches must be ON for the light (that's AND). Out of ${Math.pow(2, n)} combos, how many work?` },
              unit: "", answer: 1,
              hint: "AND needs every switch closed — only one combination does that.",
              solution: { adult: `Series = AND: only the all-closed combination conducts. That's 1 of ${Math.pow(2, n)}.`, kids: "Only 'all on' works — just 1." } };
          },
          (rng) => {
            const n = rng.int(2, 4, 1);
            return {
              q: { adult: `${n} switches are wired in parallel (an OR gate). Of the ${Math.pow(2, n)} combinations, how many light the lamp?`, kids: `With OR, the light works if any switch is on. Out of ${Math.pow(2, n)} combos, how many?` },
              unit: "", answer: Math.pow(2, n) - 1,
              hint: "OR fails only when every switch is open.",
              solution: { adult: `Parallel = OR: it lights unless all are open, so ${Math.pow(2, n) - 1} of ${Math.pow(2, n)} combinations work.`, kids: `Only 'all off' fails — so ${Math.pow(2, n) - 1} of ${Math.pow(2, n)} work.` } };
          },
        ]} />

        <ChapterQuiz
          chapterN="05"
          title={kids ? "Quick quiz!" : "Check your understanding."}
          intro={kids
            ? "Five quick questions about on, off, and combining switches. Try as often as you like."
            : "Five questions on switches, binary, and logic. 70% to pass; retry freely."}
          questions={kids ? KIDS_QUIZ : ADULT_QUIZ}
          pick={5}
        />
        {kids && (
          <div className="section" style={{ paddingTop: 0 }}>
            <div className="section-inner">
              <p className="lede" style={{ maxWidth: "46em", color: "var(--ink-soft)" }}>
                Finished chapters 1–5 and the builds? That's the whole <b>Explorer Route</b> —
                go pass the checkpoint and claim your Explorer Engineer certificate.
              </p>
              <a className="wn-link" href="explorer.html#checkpoint" style={{ display: "inline-block", marginTop: 8 }}>Take the Explorer Checkpoint →</a>
            </div>
          </div>
        )}
        <WhatsNext currentN="05" kids={kids}
          summary={kids
            ? <>You're one chapter from the punchline of all electronics.</>
            : <>You've got every digital function in principle — but flipping switches by hand doesn't scale. Next: a switch that's flipped by electricity itself. That's the trick that built everything.</>}
          prevHref="chapter4.html"
          prevLabel="Chapter 4"
          nextHref="chapter6.html"
          nextLabel="Chapter 6 · The Transistor" />
      </main>
      <TweaksPanel title="Tweaks">
        <CommonTweaks t={t} setTweak={setTweak}
          animationToggles={[{ key: "showCircuit", label: "Show circuit" }]} />
      </TweaksPanel>
      <GlossaryFab />
    </>
  );
}

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