/* chapter6.jsx — Chapter 6: The Transistor */

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 transistor" ref={ref}>
      <div className="beat-marker">§ 01 · a switch made of physics</div>
      {kids ? (
        <>
          <h2 className="serif">A <em>transistor</em><br/>is a magic valve.</h2>
          <p className="lede">
            Last chapter we had a switch — but a human had to flick it. What
            if a <em>tiny</em> bit of electricity could flick the switch all
            by itself? That's a transistor.
          </p>
          <p>
            A small water flow can twist the handle on a big valve, letting
            a much bigger flow through. The little stream <em>controls</em>{" "}
            the big one.
          </p>
        </>
      ) : (
        <>
          <h2 className="serif">A transistor is a switch<br/>flipped by <em>electricity</em>.</h2>
          <p className="lede">
            Take everything we just learned about switches, then automate
            them: a small input current opens a big output gate. No human
            required. This is the device that built the digital era.
          </p>
          <p>
            We'll use a BJT (bipolar junction transistor) — three terminals
            (base, collector, emitter). The base is the "handle"; tiny
            current there controls a much larger current between collector
            and emitter.
          </p>
          <div className="marg" style={{ marginTop: 12 }}>
            Invented at Bell Labs in 1947 by Bardeen, Brattain, and Shockley
            — replacing vacuum tubes and making everything 1,000× smaller,
            cheaper, and more reliable. Nobel in 1956. You're staring at a
            screen right now powered by literally billions of them.
          </div>
        </>
      )}
      <div className="pull">A tiny stream operates a big valve.</div>
    </div>
  );
}

function ControlBeat({ vBase, setVBase, beta, onView, kids }) {
  const ref = useInViewCallback(onView);
  const baseFrac = Math.max(0, Math.min(1, (vBase - 0.6) / 1.2));
  const iBase = baseFrac * 0.04;
  const iColl = iBase * beta;
  return (
    <div className="beat" id="control" data-screen-label="02 The handle" ref={ref}>
      <div className="beat-marker">§ 02 · the handle</div>
      <h2 className="serif">Turn the<br/><em>handle</em>.</h2>
      {kids ? (
        <>
          <p className="lede">
            Slide the base input. Watch the gate open. Watch the big flow
            grow.
          </p>
          <p>
            A small change at the handle makes a <em>big</em> change in the
            water coming out the other side.
          </p>
        </>
      ) : (
        <>
          <p className="lede">
            Drag the base voltage. The transistor stays "off" until <Eq>V_base</Eq>{" "}
            exceeds about <span className="mono">0.6 V</span> — the{" "}
            <em>turn-on voltage</em> of the base-emitter junction. Above
            that, the gate opens proportionally.
          </p>
          <p>
            Output current = base current × <em>β</em> (gain). For a small
            β = {beta}, every milliamp of base current pulls {beta} mA
            through the collector.
          </p>
          <div className="marg" style={{ marginTop: 12 }}>
            <em>Jargon check.</em> Setting up this base voltage is called
            <em> biasing</em> — "bias" just means which way (and how hard) you
            lean on a junction. ~0.6 V of forward bias and the gate opens.
            (And ~ means "roughly" — real parts vary a little.)
          </div>
        </>
      )}
      <div className="rule">try it · twist the handle</div>
      <Slider name={<Eq>V_base · the handle</Eq>} value={vBase} min={0} max={2} step={0.05}
              unit="V" accent="current" onChange={setVBase}
              hint={kids ? "Pull right to open the gate." : "Below ~0.6 V the transistor is off. Above, it conducts."} />

      <div className="card" style={{ background: "transparent", marginTop: 22, padding: "18px 22px" }}>
        <div className="eyebrow" style={{ marginBottom: 10 }}>state</div>
        <p style={{ margin: 0, fontSize: 17 }}>
          Gate is <span className="mono">{fmt(baseFrac * 100, 0)}%</span> open.
          {!kids && <> Tiny <Eq>I_base</Eq> = <span className="mono">{(iBase * 1000).toFixed(1)} mA</span> → <Eq>I_collector</Eq> = <span className="mono" style={{ color: "var(--current)" }}>{iColl.toFixed(2)} A</span>.</>}
          {kids && <> A tiny trickle at the handle becomes a <span className="mono" style={{ color: "var(--current)" }}>{iColl.toFixed(2)} A</span> gush.</>}
        </p>
      </div>
    </div>
  );
}

function SwitchVsAmpBeat({ onView, kids }) {
  const ref = useInViewCallback(onView);
  return (
    <div className="beat" id="modes" data-screen-label="03 Two modes" ref={ref}>
      <div className="beat-marker">§ 03 · two modes</div>
      <h2 className="serif">Two ways<br/>to use it.</h2>
      {kids ? (
        <>
          <p className="lede">
            You can use this magic valve two different ways:
          </p>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginTop: 22 }}>
            <div className="card" style={{ background: "transparent", padding: "18px" }}>
              <div className="eyebrow" style={{ marginBottom: 10, color: "var(--water)" }}>As a switch</div>
              <p style={{ margin: 0, fontSize: 16 }}>
                Either fully open or fully shut. Just like Chapter 5 — but no
                human needed. The handle is moved by electricity.
              </p>
            </div>
            <div className="card" style={{ background: "transparent", padding: "18px" }}>
              <div className="eyebrow" style={{ marginBottom: 10, color: "var(--current)" }}>As a louder voice</div>
              <p style={{ margin: 0, fontSize: 16 }}>
                Open it part way. A small wiggle of the handle makes a BIG
                wiggle in the output. Whispers become shouts. That's how
                speakers and microphones work.
              </p>
            </div>
          </div>
        </>
      ) : (
        <>
          <p className="lede">
            The transistor has two operating regimes, each enormously useful:
          </p>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 22 }}>
            <div className="card" style={{ background: "transparent", padding: "20px" }}>
              <div className="eyebrow" style={{ marginBottom: 12, color: "var(--water)" }}>Switching mode</div>
              <p style={{ margin: 0 }}>
                Drive <Eq>V_base</Eq> hard or to zero. The transistor is either{" "}
                <em>saturated</em> (fully on, low resistance) or
                <em>cut off</em> (fully off, no current). This is the digital
                regime — billions of these in your CPU, each storing a 1 or 0.
              </p>
            </div>
            <div className="card" style={{ background: "transparent", padding: "20px" }}>
              <div className="eyebrow" style={{ marginBottom: 12, color: "var(--current)" }}>Amplifying mode</div>
              <p style={{ margin: 0 }}>
                Bias <Eq>V_base</Eq> in the middle of its range. A small AC variation
                on the input produces a much bigger swing on the output.
                That's how a guitar amp, a radio, your phone's mic preamp
                all work.
              </p>
            </div>
          </div>
          <div className="marg" style={{ marginTop: 18 }}>
            Same device. Two completely different jobs. Engineering is the
            art of picking which mode (and which bias point) for which task.
          </div>
        </>
      )}
    </div>
  );
}

function GainBeat({ beta, setBeta, vBase = 0.9, vCC = 9, onView, kids }) {
  const ref = useInViewCallback(onView);
  // Mirror the scene's model so the numbers match the animation exactly:
  // I_B = baseFraction × 40 mA, then I_C = β × I_B (capped by the supply).
  const baseFrac = Math.max(0, Math.min(1, (vBase - 0.6) / 1.2));
  const iBaseMa = Math.round(baseFrac * 40 * 10) / 10;        // mA, 1 decimal
  const iCrawMa = Math.round(iBaseMa * beta);                  // β · I_B, mA
  const capMa = vCC * 1000;                                    // supply ceiling
  const iCMa = Math.min(capMa, iCrawMa);
  const saturated = iCrawMa > capMa;
  const Ledger = () => (
    <div className="card" style={{ background: "var(--bg-deeper)", marginTop: 16, padding: "16px 18px" }}>
      <div className="eyebrow" style={{ marginBottom: 10 }}>
        {kids ? "live · the multiply" : "live · same units, so the ×β shows"}
      </div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 10, flexWrap: "wrap",
                    fontFamily: "'IBM Plex Mono', monospace", fontSize: 16 }}>
        <span><span style={{ color: "var(--current)" }}>{kids ? "in" : "I_B"}</span> {iBaseMa} mA</span>
        <span style={{ color: "var(--ink-faint)" }}>×</span>
        <span><span style={{ color: "var(--current)" }}>β</span> {beta}</span>
        <span style={{ color: "var(--ink-faint)" }}>=</span>
        <span style={{ color: "var(--ink)", fontWeight: 500 }}>
          <span style={{ color: "var(--current)" }}>{kids ? "out" : "I_C"}</span> {iCMa} mA
          <span style={{ color: "var(--ink-faint)", fontSize: 13 }}> &nbsp;({(iCMa / 1000).toFixed(2)} A)</span>
        </span>
      </div>
      <div className="marg" style={{ marginTop: 10 }}>
        {iBaseMa < 0.05
          ? (kids ? "The handle is shut — no trickle in, so nothing to multiply. Open it in the section above." : "I_B ≈ 0 (handle below 0.6 V) — nothing to amplify. Set the handle above.")
          : saturated
            ? (kids ? <>That would be {iCrawMa} mA, but the supply tank can only give {iCMa} mA — so it's <span className="mono">maxed out</span>.</> : <>β·I_B = {iCrawMa} mA would exceed the supply ceiling ({iCMa} mA) — the transistor is <span className="mono">saturated</span>.</>)
          : (kids ? <>That's the {iBaseMa} mA trickle, multiplied {beta}× by the valve.</> : <>The collector simply mirrors the base, scaled by β. Both shown in mA so the multiply is plain.</>)}
      </div>
    </div>
  );
  if (kids) {
    return (
      <div className="beat" id="gain" data-screen-label="04 Big times bigger" ref={ref}>
        <div className="beat-marker">§ 04 · big times bigger</div>
        <h2 className="serif">A whisper<br/>becomes a <em>shout</em>.</h2>
        <p className="lede">
          The magic of the transistor is the multiplier: a little wiggle of
          the handle turns into a HUGE wiggle of the output.
        </p>
        <p>
          How big is the multiplier? Try changing β (greek letter "beta") —
          that's the name of the multiplier.
        </p>
        <div className="rule">slide it</div>
        <Slider name="β · multiplier" value={beta} min={10} max={250} step={5}
                unit="×" accent="current" onChange={setBeta} />
        <p style={{ marginTop: 14 }}>
          A typical small transistor has β around 100 — meaning {beta}
          milliamps of output for every 1 milliamp of input.
        </p>
        <Ledger />
      </div>
    );
  }
  return (
    <div className="beat" id="gain" data-screen-label="04 Gain" ref={ref}>
      <div className="beat-marker">§ 04 · current gain</div>
      <h2 className="serif">The multiplier:<br/><em>β</em>.</h2>
      <p className="lede">
        The defining quantity of a BJT is its <em>current gain</em>, called
        β (sometimes <Eq>h_FE</Eq>). It's how many times bigger the collector
        current is than the base current.
      </p>
      <div className="eq" style={{ fontSize: 30, margin: "14px 0 18px" }}>
        I<sub style={{ fontSize: "0.55em" }}>C</sub>
        <span className="op">=</span>
        <span style={{ fontStyle: "italic" }}>β</span>
        <span className="op">·</span>
        I<sub style={{ fontSize: "0.55em" }}>B</sub>
      </div>
      <EqEase kids={kids}>
        (Read it plainly: collector current = β times base current. The
        subscripts only name which current — C for collector, B for base.)
      </EqEase>
      <p>
        Typical small-signal transistors have β between 50 and 500. β isn't a
        precisely-controlled number — it varies part to part — so good designs
        don't depend on its exact value. They use <em>feedback</em> to make
        the circuit robust against β drift. (That's a chapter unto itself.)
      </p>
      <p>
        One ceiling to know about now, because it comes up the moment you do
        real math: β only rules while the transistor has headroom. The
        collector current can never exceed what the supply and the{" "}
        <em>load</em> — the thing being driven, a lamp or motor — physically
        allow (<Eq>I_max ≈ V_CC ÷ R_load</Eq>). Drive the base past that
        point and the transistor <em>saturates</em>: the valve is simply wide
        open, and pushing the handle harder changes nothing. β stops
        mattering. For switching, that's exactly where you want to be.
      </p>
      <div className="rule">try it · pick a part</div>
      <Slider name="β · current gain" value={beta} min={10} max={250} step={5}
              unit="×" accent="current" onChange={setBeta} />
      <div className="marg" style={{ marginTop: 12 }}>
        Note that with bigger β, smaller base currents are needed to drive
        the same load. That's why high-β transistors are useful for sensing
        tiny signals.
      </div>
      <Ledger />
    </div>
  );
}

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

      <PredictReveal
        question={kids
          ? "Your transistor has β = 100. You feed 1 mA into the base. About how much current comes out the other side?"
          : "β = 100. I_B = 1 mA. What's I_C?"
        }
        options={[
          "10 mA",
          "100 mA",
          "1 A (1000 mA)",
          "1 mA (same)",
        ]}
        correct={1}
        explanation={kids
          ? "β tells you how much bigger the output is than the input. 1 milliamp × 100 = 100 milliamps. The transistor amplified your tiny signal by 100."
          : "I_C = β · I_B = 100 · 1 mA = 100 mA. Note this can't exceed what the supply can provide — if V_CC and R_load allow only 50 mA max, the transistor saturates at 50 mA regardless of β."
        }
        accent="current"
      />

      <PredictReveal
        question={kids
          ? "You want to use a transistor as a SWITCH (off or on, no in-between). Where should the handle (V_base) be?"
          : "Switching application. Where should you bias V_base?"
        }
        options={[
          "Right in the middle, around 1 V",
          "Always at 0.6 V (just barely on)",
          "Either at 0 V or above 1.5 V",
          "Always above 2 V",
        ]}
        correct={2}
        explanation={kids
          ? "For switching you want fully off or fully on — never in-between. So push the handle either all the way down (0V) or all the way up (above the saturation point). The in-between is for amplifying, not switching."
          : "For digital use you want the transistor saturated or cut off — sharp transitions, no analog smear. Biasing in the linear region wastes power and is what amplifiers want, not logic. A logic 0 drives V_base ≈ 0; logic 1 drives V_base well above the saturation point."
        }
        accent="water"
      />
    </div>
  );
}

function PlaygroundBeat({ vCC, setVCC, vBase, setVBase, beta, setBeta, onView, kids }) {
  const ref = useInViewCallback(onView);
  const baseFrac = Math.max(0, Math.min(1, (vBase - 0.6) / 1.2));
  const iBase = baseFrac * 0.04;
  const iColl = Math.min(vCC, iBase * beta);
  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
          ? "Three sliders, one transistor, lots of fun. Try to make the bulb as bright as possible."
          : "The transistor has three operating regions — cutoff, active, saturation. Slide the handle to feel each one."}
      </p>
      <div style={{ marginTop: 22, display: "flex", flexDirection: "column", gap: 6 }}>
        <Slider name={kids ? "Supply · big tank" : <Eq>V_CC · supply</Eq>} value={vCC} min={1} max={12} step={0.5}
                unit="V" accent="water" onChange={setVCC} />
        <Slider name={kids ? "Handle · the control" : <Eq>V_base · the handle</Eq>} value={vBase} min={0} max={2} step={0.05}
                unit="V" accent="current" onChange={setVBase} />
        <Slider name={kids ? "Multiplier" : "β · current gain"} value={beta} min={10} max={250} step={5}
                unit="×" accent="" onChange={setBeta} />
      </div>
      <div className="card" style={{ background: "transparent", marginTop: 22, padding: "16px 20px" }}>
        <div className="eyebrow" style={{ marginBottom: 10 }}>{kids ? "what's happening" : "operating region"}</div>
        {kids ? (
          <p style={{ margin: 0, fontSize: 17 }}>
            {vBase < 0.6 ? <>The gate is <span className="mono">SHUT</span> — nothing flows.</>
             : iColl > vCC * 0.9 ? <>The gate is <span className="mono">WIDE OPEN</span> — as much flow as the tank can give.</>
             : <>The gate is <span className="mono">PART-WAY</span> open — a little handle makes a big flow.</>}
          </p>
        ) : (
          <p style={{ margin: 0, fontSize: 17 }}>
            {vBase < 0.6 ? <><span className="mono">CUT-OFF</span> — transistor is off. <Eq>I_C</Eq> ≈ 0.</>
             : iColl > vCC * 0.9 ? <><span className="mono">SATURATED</span> — gate fully open. Output limited by <Eq>V_CC</Eq> and load.</>
             : <><span className="mono">ACTIVE</span> — operating in the amplifying region. <Eq>I_C</Eq> = <span className="mono" style={{ color: "var(--current)" }}>{fmt(iColl, 2)} A</span>.</>}
          </p>
        )}
      </div>
    </div>
  );
}

/* ─── LessonScrollyteller ───────────────────────────────────────────────── */
function LessonScrollyteller({ showCircuit, kids }) {
  const [vCC, setVCC] = useState(9);
  const [vBase, setVBase] = useState(0.9);
  const [beta, setBeta] = useState(100);
  const [mode, setMode] = useState("begin");
  const visHeight = showCircuit ? 340 : 540;
  return (
    <section className="lesson">
      <div className="lesson-scroll">
        <BigIdeaBeat onView={() => setMode("begin")} kids={kids} />
        <ControlBeat vBase={vBase} setVBase={setVBase} beta={beta}
                     onView={() => setMode("control")} kids={kids} />
        <SwitchVsAmpBeat onView={() => setMode("modes")} kids={kids} />
        <GainBeat beta={beta} setBeta={setBeta} vBase={vBase} vCC={vCC}
                  onView={() => setMode("gain")} kids={kids} />
        <PredictBeat onView={() => setMode("predict")} kids={kids} />
        <PlaygroundBeat vCC={vCC} setVCC={setVCC} vBase={vBase} setVBase={setVBase}
                        beta={beta} setBeta={setBeta}
                        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 · little stream, big valve</div>
          <TransistorWaterScene vCC={vCC} vBase={vBase} beta={beta} height={visHeight} kids={kids} />
        </div>
        {showCircuit && (
          <div className="vis-block">
            <div className="stage-label">{kids ? "THE LOOP · tiny in opens a big gate" : "THE LOOP · small I_B gates a big I_C"}</div>
            <LoopScene6 vCC={vCC} vBase={vBase} beta={beta} kids={kids} />
          </div>
        )}
        <div className="vis-readout">
          <div className="ro-v">
            <span className="ro-name">{kids ? "Supply" : <Eq>V_CC</Eq>}</span>
            <span className="ro-val">{fmt(vCC, 1)}<span className="ro-unit">V</span></span>
          </div>
          <div className="ro-r">
            <span className="ro-name">{kids ? "Handle" : <Eq>V_base</Eq>}</span>
            <span className="ro-val">{fmt(vBase, 2)}<span className="ro-unit">V</span></span>
          </div>
          <div className="ro-i">
            <span className="ro-name">{kids ? "Multiplier" : "β"}</span>
            <span className="ro-val">{fmt(beta, 0)}<span className="ro-unit">×</span></span>
          </div>
          <div className="ro-p ro-active">
            <span className="ro-name">{kids ? "Out" : <Eq>I_out</Eq>}</span>
            <span className="ro-val">{fmt(Math.max(0, Math.min(1, (vBase - 0.6) / 1.2)) * 0.04 * beta, 2)}<span className="ro-unit">A</span></span>
          </div>
        </div>
      </aside>
    </section>
  );
}

/* ─── Worked example (adult): MOSFETs, billions of switches ────────────── */
function WorkedExampleSection({ kids }) {
  if (kids) return null;
  return (
    <section className="section" id="example" data-screen-label="07 Scale">
      <div className="marker">§ 07 · the scale of it</div>
      <div className="section-inner">
        <div className="two-col">
          <div>
            <h2 className="serif">The unspoken<br/><em>scale</em>.</h2>
            <p className="lede">
              Everything we've shown is a single transistor — the kind you
              can buy for $0.10 and hold in your hand. Now scale it up.
            </p>
            <p>
              Modern chips don't use BJTs; they use <em>MOSFETs</em> — a
              cousin that's smaller, faster, and barely uses any base
              current. Worth keeping the two straight:
            </p>
            <div style={{ display: "grid", gap: 12, marginTop: 16 }}>
              <div className="card" style={{ background: "transparent", padding: "16px 18px" }}>
                <div className="eyebrow" style={{ marginBottom: 8, color: "var(--current)" }}>BJT · driven by current</div>
                <p style={{ margin: 0, fontSize: 15, lineHeight: 1.55 }}>
                  The one this chapter animates: a small base <em>current</em>{" "}
                  steadily opens the gate — β times bigger at the collector.
                  Where you'll meet it: hobby boards driving an LED, relay, or
                  buzzer (the classic 2N2222), audio amplifier stages, the
                  Beacon's lamp driver.
                </p>
              </div>
              <div className="card" style={{ background: "transparent", padding: "16px 18px" }}>
                <div className="eyebrow" style={{ marginBottom: 8, color: "var(--water)" }}>MOSFET · driven by voltage</div>
                <p style={{ margin: 0, fontSize: 15, lineHeight: 1.55 }}>
                  No trickle needed — just voltage <em>presence</em> at the gate,
                  like a finger resting on a touch-lamp. Almost zero control
                  power, so you can pack billions together. Where you'll meet
                  it: every chip in your phone, laptop power supplies, EV motor
                  controllers, LED dimmers.
                </p>
              </div>
            </div>
            <p style={{ marginTop: 16 }}>
              Same idea in both — small signal gates big flow. You can fit a
              single MOSFET in roughly <span className="mono">3 nm × 3 nm</span>.
              That's a few atoms wide. And there are <em>billions</em> on a CPU.
            </p>
          </div>
          <div>
            <div className="card" style={{ padding: "24px 26px" }}>
              <div className="eyebrow" style={{ marginBottom: 14 }}>orders of magnitude</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr auto", gap: "8px 14px", fontSize: 15, lineHeight: 1.5 }}>
                <span>One discrete transistor</span><span className="mono">1</span>
                <span>4-bit microprocessor (1971)</span><span className="mono">2,300</span>
                <span>Original Macintosh CPU (1984)</span><span className="mono">68,000</span>
                <span>Pentium 4 (2000)</span><span className="mono">42 M</span>
                <span>Modern desktop CPU (2024)</span><span className="mono">~25 B</span>
                <span>Apple M3 Ultra</span><span className="mono" style={{ color: "var(--current)" }}>~134 B</span>
              </div>
              <p className="marg" style={{ marginTop: 18 }}>
                Every line in that table is a transistor doing one of the two
                jobs you just learned — switching, or amplifying. Every photo
                you take, every word your phone autocompletes, is just a{" "}
                <em>mind-boggling</em> number of these.
              </p>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

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

const ADULT_QUIZ = [
  {
    q: "A transistor is best described as…", kind: "concept",
    options: ["a battery", "a switch flipped by electricity", "a kind of resistor", "a water tank"],
    correct: 1,
    explain: "A small input signal controls a big output current — a switch (or valve) operated electrically.",
  },
  {
    q: "In a BJT, a small _ controls a large _.", kind: "concept",
    options: ["voltage / resistance", "base current / collector current", "color / size", "heat / light"],
    correct: 1,
    explain: "Tiny base current gates a much larger collector current. That's the amplifying action.",
  },
  {
    q: "With β = 100 and a base current of 1 mA, the collector current is about…", kind: "math",
    options: ["1 mA", "10 mA", "100 mA", "1000 mA"],
    correct: 2,
    explain: "I_C = β × I_B = 100 × 1 mA = 100 mA (as long as the supply can provide it).",
  },
  {
    q: "For a transistor used as a digital SWITCH, you want it…", kind: "concept",
    options: [
      "biased in the middle, always partly on",
      "either fully off or fully on (saturated)",
      "slightly warm",
      "disconnected",
    ],
    correct: 1,
    explain: "Digital logic wants clean cutoff or saturation — sharp 0 or 1, no in-between.",
  },
  {
    q: "Roughly how many transistors are in a modern desktop CPU?", kind: "concept",
    options: ["A few thousand", "About a million", "Tens of billions", "Exactly one"],
    correct: 2,
    explain: "Tens of billions — each one a tiny switch or amplifier, the kind you just explored.",
  },
  {
    q: "Below its turn-on voltage (~0.6 V at the base), a transistor is…", kind: "concept",
    options: ["fully on", "off — no collector current", "on fire", "amplifying"],
    correct: 1,
    explain: "Below the base turn-on voltage the gate stays shut — essentially no collector current.",
  },
  {
    q: "Used as an amplifier, the transistor is biased…", kind: "concept",
    options: ["fully off", "fully saturated", "in the middle of its range", "backwards"],
    correct: 2,
    explain: "Amplifiers sit in the active region — a small input wiggle becomes a big output wiggle.",
  },
  {
    q: "β varies a lot from part to part (50–500 for the same model). Good designs…",
    kind: "concept",
    options: [
      "measure each transistor and hand-pick them",
      "don't depend on β's exact value — they use feedback to stay robust",
      "only work with β = 100 exactly",
      "avoid transistors entirely",
    ],
    correct: 1,
    explain: "β isn't precisely controlled, so robust circuits are designed to work across the whole range — feedback makes the exact value not matter.",
  },
  {
    q: "In saturation (valve wide open), pushing MORE base current does what?",
    kind: "concept",
    options: ["Doubles the output", "Nothing — the output is maxed; β stops mattering", "Reverses the flow", "Burns the base"],
    correct: 1,
    explain: "Once fully open, harder pushing changes nothing — the load sets the current. For switching, that's exactly where you want to be.",
  },
  {
    q: "A MOSFET differs from a BJT in that its gate responds to…",
    kind: "concept",
    options: ["heat", "voltage, drawing almost no control current", "light", "sound"],
    correct: 1,
    explain: "A MOSFET is controlled by voltage at the gate — like a finger resting on a touch lamp. Nearly zero control power is why billions fit on one chip.",
  },
  {
    q: "The transistor was invented in 1947 at Bell Labs, replacing…",
    kind: "concept",
    options: ["batteries", "vacuum tubes — making electronics ~1000× smaller and more reliable", "light bulbs", "relays only, with no size benefit"],
    correct: 1,
    explain: "Bardeen, Brattain & Shockley's transistor replaced hot, bulky, fragile vacuum tubes — the step that made modern computing physically possible.",
  },
  {
    q: "Why is a HIGH-β transistor good for sensing tiny signals?",
    kind: "concept",
    options: ["It's physically bigger", "A smaller base current suffices to drive the same load", "It stores more charge", "It runs hotter"],
    correct: 1,
    explain: "Bigger multiplier means a whisper of base current is enough — ideal when the input signal is faint.",
  },
];

const KIDS_QUIZ = [
  {
    q: "A transistor is like…", kind: "concept",
    options: ["a bucket", "a magic valve that electricity opens", "a battery", "a light bulb"],
    correct: 1,
    explain: "A valve — but instead of your hand, a tiny bit of electricity opens it!",
  },
  {
    q: "A tiny trickle at the handle controls…", kind: "concept",
    options: ["nothing", "a much bigger flow", "the color", "the temperature only"],
    correct: 1,
    explain: "That's the magic: a little control trickle moves a big main flow.",
  },
  {
    q: "If the multiplier is 100, a small input becomes…", kind: "math",
    options: ["100 times bigger", "100 times smaller", "the same", "zero"],
    correct: 0,
    explain: "The multiplier makes the output that many times bigger — a whisper becomes a shout.",
  },
  {
    q: "To use it as an on/off switch, you push the handle…", kind: "concept",
    options: ["halfway", "all the way down OR all the way up", "only halfway up", "in circles"],
    correct: 1,
    explain: "Fully shut or fully open — never in-between. In-between is for making things louder, not switching.",
  },
  {
    q: "How many of these tiny valves are inside a phone or computer chip?", kind: "concept",
    options: ["about ten", "a few hundred", "billions", "just one big one"],
    correct: 2,
    explain: "Billions! Each one is a tiny version of the valve you just played with.",
  },
  {
    q: "What moves the handle on this magic valve?", kind: "concept",
    options: ["your hand", "a tiny bit of electricity", "water", "a magnet"],
    correct: 1,
    explain: "Electricity itself moves the handle — no human needed. That's the magic.",
  },
  {
    q: "A whisper-sized input becomes a shout-sized output. That's called…", kind: "concept",
    options: ["shrinking", "amplifying", "freezing", "storing"],
    correct: 1,
    explain: "Making a small thing big is amplifying — how speakers and mics work.",
  },
  {
    q: "The valve is already open ALL the way. Pushing the handle even harder…",
    kind: "concept",
    options: ["makes even more flow", "does nothing — it's already wide open", "closes it", "makes it hotter"],
    correct: 1,
    explain: "Wide open is wide open! For on/off switching, that's exactly what you want.",
  },
  {
    q: "Before this valve was invented, computers used big glass tubes that…",
    kind: "concept",
    options: ["worked better", "were huge, hot, and broke all the time", "were too small to see", "ran on water"],
    correct: 1,
    explain: "The transistor replaced them in 1947 — a thousand times smaller and way more reliable. That's why computers fit in your pocket now!",
  },
];

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

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  useCrossChapterPersistence(t, setTweak);
  useEffect(() => { document.body.setAttribute("data-theme", t.theme); }, [t.theme]);
  const kids = t.audience === "kids";
  const navItems = [
    { id: "cover", label: "Cover" },
    { id: "begin", label: "The magic valve" },
    { id: "control", label: "Handle" },
    { id: "modes", label: kids ? "Two ways" : "Two modes" },
    { id: "gain", label: kids ? "Bigger" : "Gain (β)" },
    { id: "predict", label: "Predict" },
    { id: "playground", label: "Playground" },
    ...(kids ? [] : [{ id: "example", label: "Scale" }]),
    { id: "practice", label: "Practice" },
    { id: "quiz", label: "Quiz" },
    { id: "whats-next", label: "What's next" },
  ];
  return (
    <>
      <ChapterStartMarker chapterN="06" />
      <ProgressBar />
      <TopBar currentN="06" chapterLabel="Ch. 06 — The Transistor"
              audience={t.audience}
              setAudience={(v) => setTweak("audience", v)} />
      <ChapterNav items={navItems} />
      <main>
        <CoverPage chapterN="06"
                   chapterTitle={<>The <em>Transistor</em>.</>}
                   chapterSub="Chapter 6 · A valve made of electricity"
                   kids={kids}
                   lede={kids
                     ? <>The last chapter had a switch — but a human had to flip it. What if a tiny stream of electricity could flip the switch instead? That's the magic device that built every computer you've ever used.</>
                     : <>One device. Two regimes. Three terminals. Roughly a hundred billion of them in the laptop you're staring at. This is the punchline — and the launchpad for everything else.</>
                   } />
        <LessonScrollyteller showCircuit={t.showCircuit} kids={kids} />

        <CheckpointQuiz kids={kids} label="Checkpoint 1" pick={2}
          title={kids ? "Quick check!" : "Did it stick?"}
          questions={[
            {
              q: kids ? "The transistor's tiny control trickle moves…" : "The transistor's small base current controls…",
              options: ["The gate on the MAIN pipe — a small flow steers a big one", "The barrel's height", "The wheel at the end", "Nothing — it's decoration"],
              correct: 0,
              explain: kids ? "A dribble of water pushes the gate, and the gate decides whether the BIG river flows. Small hand, big door."
                            : "The base–emitter trickle opens the collector–emitter gate. A milliamp of control steering a hundred milliamps of payload — that's the whole trick.",
            },
            {
              q: "With NO control trickle at all, the main gate sits…",
              options: ["Shut — no main flow", "Wide open", "Half open", "Vibrating"],
              correct: 0,
              explain: kids ? "No push on the gate means the gate stays closed and the big pipe stays dry. The transistor rests OFF."
                            : "Zero base current = cutoff: the collector path is open-circuit. The device defaults to off, which is exactly what you want from a switch.",
            },
            {
              q: kids ? "'Amplify' means…" : "Amplification means…",
              options: ["A small signal shapes a much bigger flow", "Making energy from nothing", "Heating the pipe on purpose", "Slowing everything down"],
              correct: 0,
              explain: kids ? "The big flow's strength comes from the big barrel — the little signal just steers it. Nothing is created from thin air!"
                            : "The output power comes from the supply, not the signal — the signal only modulates it. β tells you how many collector milliamps each base milliamp commands.",
            },
            {
              q: kids ? "The transistor's three legs have names. They are…" : "The BJT's three terminals are named…",
              options: ["Base, collector, emitter", "Top, middle, bottom", "Anode, cathode, gate", "In, out, ground"],
              correct: 0,
              explain: kids ? "The BASE is the little control handle, the COLLECTOR is where the big flow comes in, and the EMITTER is where it all pours out."
                            : "Base (the control trickle), collector (where the main current enters), emitter (where it exits). Pin diagrams, datasheets, and chapter L2-05 all speak in these three names.",
            },
            {
              q: "Used as a SWITCH, a transistor is happiest kept…",
              options: ["Fully off or fully on — never lingering in between", "Half open all the time", "Disconnected", "Slightly leaky"],
              correct: 0,
              explain: kids ? "All-the-way open or all-the-way shut wastes almost nothing. Half open makes the gate itself fight the flow — and get hot."
                            : "In saturation or cutoff the transistor drops little power. The half-open middle is where V × I across the device — and the heat — is largest.",
            },
          ]} />

        <WorkedExampleSection kids={kids} />

        <CheckpointQuiz kids={kids} label="Checkpoint 2" pick={2}
          title={kids ? "Spot it in real life!" : "Out in the wild."}
          intro={kids ? "Small-steers-big is running your whole house." : "Small-steers-big, everywhere you look."}
          questions={[
            {
              q: "A feather-light button turns on a big noisy fan. What's likely sitting between them?",
              options: ["A transistor (or relay) — the button only carries the control trickle", "A thicker wire to the button", "Nothing — the button takes the full blast", "A bigger battery in the button"],
              correct: 0,
              explain: kids ? "The little button just whispers to the gate-keeper; the gate-keeper handles the big river to the motor."
                            : "Letting a logic-level signal command a heavy load is THE transistor job: the switch handles milliamps while the device routes amps.",
            },
            {
              q: "Your phone's chip holds billions of transistors because…",
              options: ["Each is a tiny switch — combined, they compute", "They store water", "They make heat on purpose", "More parts look impressive"],
              correct: 0,
              explain: kids ? "Each one is an on/off gate from last chapter — shrunk smaller than a germ. Billions of yes/no gates working together can think through anything!"
                            : "Transistors are chapter 5's switches, automated and miniaturized. Wired into logic gates, they're sufficient for all of computation.",
            },
            {
              q: "A microphone's whisper-weak signal ends up filling a stadium because…",
              options: ["Amplifier stages let small steer big, over and over", "The speakers add energy from nowhere", "Sound speeds up inside wires", "The crowd imagines it"],
              correct: 0,
              explain: kids ? "The whisper steers a bigger flow, which steers an even BIGGER flow — like a small hand opening bigger and bigger gates in a row."
                            : "Cascaded gain: each stage uses its supply to produce a louder copy of its input. The energy comes from the wall; the shape comes from the mic.",
            },
            {
              q: "Why NOT run a doorbell's full chime current through the button itself?",
              options: ["Heavy current needs beefy contacts that spark and wear — let a transistor or relay carry it", "Buttons are allergic to electricity", "It would ring too quietly", "Current can't turn corners"],
              correct: 0,
              explain: kids ? "Big flows chew up little switches. Better to have the button whisper to something tough, and let the tough thing do the lifting."
                            : "Switching real load current means arcing, contact wear, and thick wiring to the switch point. Control-signal-plus-driver is cheaper, safer, and lasts longer.",
            },
            {
              q: kids ? "The transistor's three legs are called…" : "A BJT's three terminals are named…",
              options: ["base, collector and emitter", "top, middle and bottom", "anode, cathode and gate", "plus, minus and ground"],
              correct: 0,
              explain: kids ? "BASE is the little control handle, COLLECTOR is where the big flow comes in, EMITTER is where it leaves. Knowing the names matters when you wire one for real!"
                            : "Base (control), collector (main flow in), emitter (main flow out). Datasheets, pinouts, and every schematic assume you know which is which.",
            },
            {
              q: kids ? "The thing your circuit is powering — the lamp, the fan, the buzzer — is called the…" : "The device being driven — lamp, motor, buzzer — is, in engineer-speak, the…",
              options: ["load", "source", "base", "supply"],
              correct: 0,
              explain: kids ? "Whatever does the useful work at the end of the pipe is the LOAD. The battery that pushes is the SOURCE."
                            : "Load = what consumes the power; source = what provides it. 'Driving a load' is the phrase you'll meet in every datasheet from here on.",
            },
          ]} />

        <PracticeProblems chapterN="06" kids={kids} problems={[
          (rng) => {
            const beta = rng.pick([50, 100, 150, 200]), ib = rng.pick([0.2, 0.5, 1, 1.5]);
            const ic = +(beta * ib).toFixed(1);
            return {
              q: { adult: `A transistor has a current gain β of ${beta}. If ${ib} mA flows into the base, what collector current can it carry? (Answer in mA.)`, kids: `The transistor multiplies the small control flow by ${beta}. The control flow is ${ib}. What's the big flow? (in mA)` },
              unit: "mA", answer: ic, tol: 0.04,
              hint: "I_C = β × I_B.",
              solution: { adult: `I_C = β × I_B = ${beta} × ${ib} mA = ${ic} mA.`, kids: `${beta} × ${ib} = ${ic}.` } };
          },
          (rng) => {
            const beta = rng.pick([50, 100, 200]), ic = rng.pick([100, 150, 200, 300]);
            const ib = +(ic / beta).toFixed(2);
            return {
              q: { adult: `You need ${ic} mA of collector current from a transistor with β = ${beta}. What is the minimum base current? (Answer in mA.)`, kids: `You want a big flow of ${ic}, and the transistor multiplies by ${beta}. How much control flow do you need? (in mA)` },
              unit: "mA", answer: ib, tol: 0.04,
              hint: "I_B = I_C ÷ β.",
              solution: { adult: `I_B = I_C ÷ β = ${ic} mA ÷ ${beta} = ${ib} mA.`, kids: `${ic} ÷ ${beta} = ${ib}.` } };
          },
          (rng) => {
            const v = rng.int(5, 12, 1), ib = rng.pick([1, 2, 2.5, 4, 5]);
            const r = Math.round((v - 0.7) / (ib / 1000));
            return {
              q: { adult: `Driving the base from ${v} V with a 0.7 V base-emitter drop, what resistor gives ${ib} mA of base current?`, kids: `Push is ${v}, but the transistor 'uses up' 0.7 getting in — leaving ${+(v - 0.7).toFixed(1)} for the pinch. You want a flow of ${ib} thousandths. Pinch = leftover ÷ flow.` },
              unit: "Ω", answer: r, tol: 0.05,
              hint: `R = (${v} − 0.7) V ÷ ${ib / 1000} A.`,
              solution: { adult: `R = (${v} − 0.7) ÷ ${ib / 1000} = ${+(v - 0.7).toFixed(1)} ÷ ${ib / 1000} = ${r} Ω.`, kids: `(${v} − 0.7) ÷ ${ib / 1000} = ${+(v - 0.7).toFixed(1)} ÷ ${ib / 1000} = ${r}.` } };
          },
        ]} />

        <ChapterQuiz
          chapterN="06"
          title={kids ? "Quick quiz!" : "Check your understanding."}
          intro={kids
            ? "Five quick questions about the magic valve. Try as often as you like."
            : "Five questions on transistors, gain, and scale. 70% to pass; retry freely."}
          questions={kids ? KIDS_QUIZ : ADULT_QUIZ}
          pick={5}
        />
        <div className="section" style={{ paddingTop: 0 }}>
          <div className="section-inner">
            <p className="lede" style={{ maxWidth: "46em", color: "var(--ink-soft)" }}>
              {kids
                ? <>Try it: open <b>The Sandbox</b> and load <b>“Transistor switch”</b> — tap the little switch and watch a tiny base current let a big flow through to the light.</>
                : <>See it work: in <b>The Sandbox</b>, the <b>Transistor switch</b> example shows a small base current (through R<sub>B</sub>) turning on the much larger collector→emitter current — the valve in action. Toggle the base switch and watch the LED.</>}
            </p>
            <a className="wn-link" href="flow-sandbox.html?ex=npn" style={{ display: "inline-block", marginTop: 8 }}>Open The Sandbox →</a>
          </div>
        </div>
        <WhatsNext currentN="06" kids={kids}
          summary={kids
            ? <>You met the valve that built the modern world! Next up: a part that only lets flow go <em>one way</em> — the diode.</>
            : <>You've got the transistor — amplifier and switch in one. Next: the diode, a one-way valve for current, and the trick that turns AC into usable DC.</>}
          prevHref="chapter5.html"
          prevLabel="Chapter 5"
          nextHref="chapter7.html"
          nextLabel="Chapter 7 · The One-Way Valve" />
      </main>
      <TweaksPanel title="Tweaks">
        <CommonTweaks t={t} setTweak={setTweak}
          animationToggles={[{ key: "showCircuit", label: "Show circuit" }]} />
      </TweaksPanel>
      <GlossaryFab />
    </>
  );
}

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