/* chapter-l2-transistor.jsx — Level 2 · Chapter 6: The Driver. */

const { useState, useEffect, useRef } = React;

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

const TX_TOOLS = (kids) => [
  { id: "battery", label: kids ? "Battery (9V)" : "Battery 9V", hint: "+ leg first, then −" },
  { id: "transistor", label: kids ? "Transistor" : "Transistor (NPN)", hint: "tap 3 holes: Base, Collector, Emitter", legs: 3, part: { type: "transistor" } },
  { id: "resistor", label: "Resistor 330Ω", hint: "either way round" },
  { id: "led", label: kids ? "LED (the load)" : "LED load", hint: "+ (long leg) first, then −" },
  { id: "switch", label: kids ? "Switch" : "Base switch", hint: "tap on the board to flip", part: { type: "switch" } },
  { id: "wire", label: kids ? "Jumper wire" : "Jumper", hint: "connects two holes" },
];
const TX_LIMITS = { battery: 1, transistor: 1, resistor: 2, led: 1, switch: 1, wire: 12 };

function describeTx(r, kids) {
  switch (r.state) {
    case "no-batt": return ["warn", kids ? "Add a battery first!" : "No battery placed."];
    case "no-tx": return ["warn", kids ? "Place the transistor — it's the star of this chapter!" : "No transistor placed. Add one (Base, Collector, Emitter)."];
    case "no-load": return ["warn", kids ? "Build the big loop: + through a resistor and the LED into the transistor's Collector." : "No load path. Wire + → resistor → LED → transistor Collector."];
    case "no-emitter": return ["warn", kids ? "The transistor's Emitter leg needs to reach − (ground)." : "Emitter not returned to ground. Wire the Emitter leg to the − rail."];
    case "short": return ["fail", kids ? "Short circuit!" : "Dead short across the battery."];
    case "no-base": return ["warn", kids
      ? "Nothing is connected to the transistor's Base — it can't turn on. Run a wire (through the switch) from + to the Base."
      : "Base floating. Drive it from + through the switch (and ideally a base resistor) to turn the transistor on."];
    case "base-low": return ["warn", kids
      ? "The Base switch is OFF, so the transistor is closed. Tap the switch to ON and power on again — watch the big LED obey the little switch!"
      : "Base is low (switch open) → transistor in cutoff → load off. Close the base switch and re-power: a tiny base signal will switch the whole load."];
    case "pop": return ["fail", kids ? "Pop! 💥 The load LED needs a resistor too." : `Load LED over-current. Keep a series resistor on the collector load.`];
    case "lit":
      return ["pass", kids
        ? "YES! The little switch turned on the transistor, and the transistor lit the big LED. Electricity flipping a switch — that's the whole secret of computers!"
        : `Load lit at ${r.I.toFixed(0)} mA via the transistor. A small base signal switched a much larger load current — the foundational act of all digital electronics. Flip the base switch off to cut it instantly.`];
    default: return ["warn", "Hmm."];
  }
}

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: "recall", label: kids ? "Remember" : "Recall" },
    { id: "idea", label: kids ? "The trick" : "Control" },
    { id: "build", label: kids ? "Build it!" : "Build" },
    { id: "practice", label: "Practice" },
    { id: "quiz", label: "Quiz" },
    { id: "whats-next", label: "What's next" },
  ];

  return (
    <>
      <ChapterStartMarker chapterN="L2-06" />
      <ProgressBar />
      <TopBar currentN="L2-06" chapterLabel="Level 2 · The Driver"
              audience={t.audience}
              setAudience={(v) => setTweak("audience", v)} />
      <ChapterNav items={navItems} />

      <main>
        <section className="cover-page" id="cover" data-screen-label="L2-06 Cover">
          <div className="hero-grid"></div>
          <div className="cover-inner">
            <div style={{ display: "flex", alignItems: "baseline", gap: 16, marginBottom: 28 }}>
              <span className="eyebrow" style={{ color: "var(--current)" }}>Level 2 · applied</span>
              <span className="eyebrow" style={{ color: "var(--ink-faint)" }}>·</span>
              <span className="eyebrow">Chapter 6 · finale</span>
            </div>
            <h1 className="serif cover-title">The <em>Driver</em>.</h1>
            <div className="eyebrow" style={{ marginTop: 36, marginBottom: 16, color: "var(--current)" }}>
              Applying Chapter 6 · The Transistor
            </div>
            <div className="cover-lede">
              {kids
                ? <>The big finish: a transistor lets a <em>tiny</em> signal switch a <em>big</em> load. Electricity flipping its own switch — the idea behind every computer chip.</>
                : <>The capstone of Level 2's applied track: wire a transistor so a small base signal switches a larger load. This is the device that lets electricity control electricity — repeated billions of times, it's a computer.</>}
            </div>
            <div className="cover-cta">
              <a href="#recall" className="arrow-link"><span>Begin chapter</span><span className="arrow-glyph">↓</span></a>
            </div>
          </div>
        </section>

        <section className="section" id="recall" data-screen-label="Recall">
          <div className="marker">§ 01 · remember from Chapter 6</div>
          <div className="section-inner">
            <h2 className="serif">{kids ? "A valve electricity opens." : "A switch flipped by current."}</h2>
            <p className="lede" style={{ maxWidth: "42em" }}>
              {kids
                ? <>A transistor has three legs. A tiny trickle into the <b>Base</b> leg opens a big valve between the <b>Collector</b> and <b>Emitter</b> legs — letting a much bigger flow through.</>
                : <>An NPN transistor's three terminals: Base (control), Collector (load in), Emitter (out to ground). A small base current switches a much larger collector–emitter current. No moving parts, no finger required.</>}
            </p>
            <div className="card" style={{ background: "transparent", padding: "18px 20px", marginTop: 16, maxWidth: 560 }}>
              <div className="eyebrow" style={{ marginBottom: 8 }}>three legs</div>
              <p style={{ margin: 0, fontSize: 16, color: "var(--ink-soft)" }}>
                <b style={{ color: "var(--current)" }}>B</b>ase — the handle ·
                <b> C</b>ollector — load comes in ·
                <b> E</b>mitter — out to −
              </p>
            </div>
          </div>
        </section>

        <section className="section" id="idea" data-screen-label="The trick"
                 style={{ background: "var(--bg-deeper)" }}>
          <div className="marker">§ 02 · small controls big</div>
          <div className="section-inner">
            <h2 className="serif">{kids ? "Little switch, big light." : "A tiny signal, a big load."}</h2>
            <p className="lede" style={{ maxWidth: "42em" }}>
              {kids
                ? <>You'll wire a little switch to the Base. When you flip it on, the transistor opens and the big LED lights — but the switch itself only carries a trickle. The transistor does the heavy lifting.</>
                : <>You'll drive the Base from + through a switch. Closing the switch sends a small base current; the transistor turns on and lets the load LED's current flow Collector→Emitter→ground. The switch only handles the tiny base current — the transistor carries the load.</>}
            </p>
            <p className="note" style={{ marginTop: 18, maxWidth: "42em" }}>
              {kids ? <>This is why one tiny chip can control huge machines — the transistor multiplies your control.</>
                    : <>This current-gain is why a logic chip's micro-amp output can switch motors, relays, and other chips. Stack the idea and you get processors.</>}
            </p>
          </div>
        </section>

        <section className="section" id="build" data-screen-label="Build it">
          <div className="marker">§ 03 · your turn · let electricity flip the switch</div>
          <div className="section-inner" style={{ maxWidth: 1180 }}>
            <h2 className="serif" style={{ marginBottom: 10 }}>{kids ? "Drive the big LED." : "Build the transistor driver."}</h2>
            <p className="lede" style={{ marginBottom: 24, maxWidth: "44em" }}>
              {kids
                ? <>Place the transistor (tap 3 holes: Base, then Collector, then Emitter). Wire the big LED + resistor from + into the Collector, the Emitter to −, and a switch from + to the Base. Flip the switch and watch!</>
                : <>Place the transistor (tap Base, Collector, Emitter in order). Build the load: + → resistor → LED → Collector. Emitter → − rail. Drive the Base from + through the switch. Then toggle the base switch and power on.</>}
            </p>
            <DesignGate kids={kids} chapterN="L2-06"
              spec={{ adult: "You'll drive the transistor's base from 9 V through a 4.7 kΩ resistor (V_be ≈ 0.7 V).", kids: "You'll feed the base from 9 V through a 4.7 kΩ resistor." }}
              prompt={{ adult: "How much base current does that set?", kids: "How much control-current flows into the base?" }}
              formula={{ adult: "I_b = (9 V − 0.7 V) ÷ 4.7 kΩ", kids: "I_b = leftover volts ÷ resistor" }}
              unit="mA" answer={1.766} tol={0.1}
              hint={{ adult: "Leftover is 8.3 V. Divide by 4700 Ω, then ×1000 for mA.", kids: "8.3 ÷ 4700 × 1000 ≈ 1.8." }}
              solution={{ adult: "I_b = 8.3 ÷ 4700 = 1.77 mA — plenty to saturate the transistor.", kids: "8.3 ÷ 4700 ≈ 1.8 mA." }}>
              <BreadboardBuilder
                kids={kids}
                sim={simulateTransistor}
                tools={TX_TOOLS(kids)}
                limits={TX_LIMITS}
                describe={describeTx}
                goalAdult="Use a small base signal to switch a load LED. Load: + → resistor → LED → Collector; Emitter → −; Base driven from + through the switch. Toggle the base switch to control the load."
                goalKids="Make a tiny switch turn on a big LED — using the transistor! Wire the LED loop into the Collector, the Emitter to −, and the switch to the Base."
              />
            </DesignGate>
            <p className="note" style={{ marginTop: 14 }}>
              {kids ? <>Tip: place the transistor first. Tap 3 holes in order — Base, Collector, Emitter.</>
                    : <>Tip: the transistor needs three taps (Base, Collector, Emitter). Its legs are labeled on the board once placed.</>}
            </p>
          </div>
        </section>

        <PracticeProblems chapterN="L2-06" kids={kids}
          intro={kids ? "Transistor-control puzzles." : "Transistor driver design math. Enter a number and check it."}
          problems={[
          (rng) => {
            const v = rng.int(5, 12, 1), rk = rng.pick([2.2, 3.3, 4.7, 10]);
            const ib = +((v - 0.7) / (rk * 1000) * 1000).toFixed(2);
            return {
              q: { adult: `Base driven from ${v} V through ${rk} k\u03a9, V_be = 0.7 V. What base current? (mA)`, kids: `${v} V through ${rk} k\u03a9 into the base (0.7 V used getting in). Control-current? (mA)` },
              unit: "mA", answer: ib, tol: 0.08,
              hint: `I_b = (${v} − 0.7) ÷ ${rk * 1000}, ×1000 for mA.`,
              solution: { adult: `I_b = ${+(v - 0.7).toFixed(1)} ÷ ${rk * 1000} = ${ib} mA.`, kids: `${+(v - 0.7).toFixed(1)} ÷ ${rk * 1000} ≈ ${ib} mA.` } };
          },
          (rng) => {
            const beta = rng.pick([50, 100, 150, 200]), ib = rng.pick([1, 1.5, 1.8, 2]);
            const ic = +(beta * ib).toFixed(0);
            return {
              q: { adult: `With \u03b2 = ${beta}, what's the most collector current ${ib} mA of base can carry? (mA)`, kids: `The transistor multiplies by ${beta}. ${ib} mA in → how much out? (mA)` },
              unit: "mA", answer: ic, tol: 0.05,
              hint: `I_c = \u03b2 × I_b = ${beta} × ${ib}.`,
              solution: { adult: `I_c = ${beta} × ${ib} = ${ic} mA.`, kids: `${beta} × ${ib} = ${ic}.` } };
          },
          (rng) => {
            const load = rng.pick([100, 150, 200, 300]), beta = rng.pick([50, 100, 200]);
            const ib = +(load / beta).toFixed(2);
            return {
              q: { adult: `To switch a ${load} mA load with \u03b2 = ${beta}, what's the minimum base current? (mA)`, kids: `To push ${load} mA with a ×${beta} transistor, least control-current? (mA)` },
              unit: "mA", answer: ib, tol: 0.05,
              hint: `I_b = I_c ÷ \u03b2 = ${load} ÷ ${beta}.`,
              solution: { adult: `I_b = ${load} ÷ ${beta} = ${ib} mA (use 2× for margin).`, kids: `${load} ÷ ${beta} = ${ib} mA.` } };
          },
        ]} />

        <ChapterQuiz
          chapterN="L2-06"
          title={kids ? "Quick quiz!" : "Check your understanding."}
          intro={kids ? "Five questions about transistors." : "The transistor as a switch. 70% to pass; retry freely."}
          questions={kids ? TX_QUIZ_KIDS : TX_QUIZ_ADULT}
          pick={5}
        />

        <WhatsNext
          currentN="L2-06"
          kids={kids}
          summary={kids
            ? <>You finished Level 2 — you can build real circuits AND make electricity control itself. Next up: the Level 2 certification, where you put it all together!</>
            : <>You've completed Level 2's applied chapters. You can build, size, time, gate, and now switch loads with a transistor. One thing remains: the Level 2 certification exam.</>}
          prevHref="chapter-l2-switch.html"
          prevLabel="L2 · The Button"
          nextHref="map.html"
          nextLabel="Back to course"
        />
      </main>

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

const TX_QUIZ_ADULT = [
  { q: "An NPN transistor's three terminals are…", kind: "concept", options: ["Base, Collector, Emitter", "Anode, Cathode, Gate", "Plus, Minus, Ground", "Input, Output, Power"], correct: 0, explain: "Base (control), Collector (load in), Emitter (out). A small base current gates a large C→E current." },
  { q: "In a transistor switch, the base signal is…", kind: "concept", options: ["larger than the load current", "much smaller than the load current", "equal to it", "not needed"], correct: 1, explain: "That's the point — a tiny base current controls a much larger load current (current gain β)." },
  { q: "With the base switch OPEN (base low), the transistor is…", kind: "concept", options: ["saturated/on", "in cutoff/off — load dark", "amplifying", "broken"], correct: 1, explain: "No base drive → cutoff → no collector current → load off." },
  { q: "Where does the load (resistor + LED) connect?", kind: "concept", options: ["across the base only", "+ → resistor → LED → Collector, Emitter → −", "between base and emitter", "directly across the battery"], correct: 1, explain: "The load is in the collector path; the emitter returns to ground." },
  { q: "Why is a transistor better than a finger-flipped switch here?", kind: "concept", options: ["it's prettier", "electricity itself can flip it — fast, tiny, automatic", "it needs no power", "it removes the LED"], correct: 1, explain: "Electronic control means billions of switchings per second with no moving parts — the basis of computing." },
  { q: "Billions of transistors switching together make a…", kind: "concept", options: ["resistor", "processor / computer chip", "battery", "single LED"], correct: 1, explain: "Stacked and interconnected, transistor switches become logic, memory, and processors." },
  {
    q: "The three legs of an NPN transistor are…",
    kind: "concept",
    options: ["plus, minus, ground", "base, collector, emitter", "in, out, shake", "left, right, middle"],
    correct: 1,
    explain: "Base is the control tap; the big flow runs collector → emitter.",
  },
  {
    q: "Why drive the LED through a transistor instead of straight from the button?",
    kind: "concept",
    options: ["it looks cooler", "a tiny control current can switch a much bigger load current", "transistors are cheaper than wire", "LEDs require it by law"],
    correct: 1,
    explain: "That's the whole point of the valve: small signal in, big current handled.",
  },
  {
    q: "A microcontroller pin can only supply a few mA. How does it drive a motor that needs an amp?",
    kind: "concept",
    options: ["It can't — motors need their own chip", "The pin drives the transistor's BASE; the transistor's collector/emitter path carries the motor's real current from a separate supply", "The pin is secretly rated for an amp", "Motors don't need much current"],
    correct: 1,
    explain: "This is the transistor's core job in real builds: a delicate control signal (from a chip pin) switches a much heftier load current, drawn from whatever supply the load actually needs.",
  },
];
const TX_QUIZ_KIDS = [
  { q: "How many legs does the transistor have?", kind: "concept", options: ["one", "two", "three", "ten"], correct: 2, explain: "Three: Base, Collector, and Emitter." },
  { q: "Which leg is the 'handle' that turns it on?", kind: "concept", options: ["Base", "Collector", "Emitter", "none"], correct: 0, explain: "The Base! A tiny trickle there opens the big valve." },
  { q: "A transistor lets a SMALL signal control a…", kind: "concept", options: ["small flow", "BIG flow", "nothing", "color"], correct: 1, explain: "Small controls big — that's the magic." },
  { q: "If the Base switch is OFF, the big LED is…", kind: "concept", options: ["on", "off", "blue", "hot"], correct: 1, explain: "No signal to the Base = transistor closed = LED off." },
  { q: "Lots of transistors together make a…", kind: "concept", options: ["sandwich", "computer chip", "battery", "wire"], correct: 1, explain: "Billions of them switching = a computer!" },
  {
    q: "The transistor's little side pipe (the base) is for…",
    kind: "concept",
    options: ["the big flow", "the tiny control trickle", "water storage", "decoration"],
    correct: 1,
    explain: "A tiny trickle in the side pipe opens the big main valve.",
  },
  {
    q: "With NO trickle at the base, the big flow…",
    kind: "concept",
    options: ["runs anyway", "stays off", "reverses", "gets bigger"],
    correct: 1,
    explain: "No control signal, no flow — the valve stays shut.",
  },
  {
    q: "A transistor lets something tiny control something…",
    kind: "concept",
    options: ["tinier", "BIG", "invisible", "purple"],
    correct: 1,
    explain: "Small controls big — that's why computers can think!",
  },
  {
    q: "A tiny chip can only push a whisper of flow. How does it run a big, thirsty motor?",
    kind: "concept",
    options: ["It can't — motors need a totally different chip", "The chip's whisper opens the transistor's valve, and the transistor lets the BIG flow through from its own supply", "It secretly stores extra power", "Motors barely need any flow"],
    correct: 1,
    explain: "That's exactly the transistor's job: a tiny signal from a chip opens the valve, and a much bigger flow (from wherever the motor gets its own power) rushes through.",
  },
];

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