/* chapter-l2-rectifier.jsx — Level 2 · Chapter 7: The Rectifier.
   Applies Ch7 (diode) + Ch4 (cap): turn a rough source into clean DC. */

const { useState, useEffect } = React;

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

const RECT_TOOLS = (kids) => [
  { id: "battery", label: kids ? "Rough source" : "Source 9V", hint: "+ leg first, then −" },
  { id: "diode", label: kids ? "One-way valve" : "Diode", hint: "▷ anode first, then | cathode" },
  { id: "resistor", label: "Resistor 330Ω", hint: "either way round" },
  { id: "led", label: "LED", hint: "+ (long leg) first, then −" },
  { id: "capacitor", label: kids ? "Smoothing bucket" : "Cap (smoothing)", hint: "across the rail to ground", part: { type: "capacitor", C: 3 } },
  { id: "wire", label: kids ? "Jumper wire" : "Jumper", hint: "connects two holes" },
];
const RECT_LIMITS = { battery: 1, diode: 1, resistor: 2, led: 1, capacitor: 1, wire: 10 };

function describeRect(r, kids) {
  switch (r.state) {
    case "no-batt": return ["warn", kids ? "Add the source first." : "No source placed."];
    case "no-diode": return ["warn", kids ? "Add the one-way valve (diode) — it's the star here." : "No diode placed. The diode does the rectifying."];
    case "diode-backwards": return ["warn", kids ? "The valve is backwards — flip it so ▷ points away from +." : "Diode reversed: anode must face the source +. As-is it blocks everything."];
    case "diode-floating": return ["warn", kids ? "Put the valve right after the + source." : "Diode not in the feed: put its anode on the source + rail."];
    case "no-load": return ["warn", kids ? "Add the LED + resistor after the valve." : "No load after the diode. Add resistor → LED → ground."];
    case "short": return ["fail", kids ? "Short circuit!" : "Dead short across the source."];
    case "pop": return ["fail", kids ? "Pop! 💥 Keep the resistor." : "LED over-current — keep the series resistor."];
    case "lit":
      return r.smoothed
        ? ["pass", kids
            ? "Clean and steady! 🎉 The valve makes it one-way, and the bucket smooths it out — that's a power supply!"
            : `Rectified AND smoothed: the diode passes only forward flow, and the cap across the rail fills the gaps. This is exactly how a DC adapter turns wall AC into clean DC. (${r.I.toFixed(0)} mA)`]
        : ["warn", kids
            ? "It lights — but it's rough/flickery. Add the smoothing bucket (capacitor) across the rail to make it steady."
            : "Rectified but unsmoothed — the output is choppy. Add a capacitor across the rail (to ground) to smooth the ripple into clean DC."];
    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: "how", label: kids ? "The combo" : "Rectify + smooth" },
    { 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-07" />
      <ProgressBar />
      <TopBar currentN="L2-07" chapterLabel="Level 2 · The Rectifier"
              audience={t.audience} setAudience={(v) => setTweak("audience", v)} />
      <ChapterNav items={navItems} />
      <main>
        <section className="cover-page" id="cover" data-screen-label="L2-07 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 7</span>
            </div>
            <h1 className="serif cover-title">The <em>Rectifier</em>.</h1>
            <div className="eyebrow" style={{ marginTop: 36, marginBottom: 16, color: "var(--current)" }}>
              Applying Ch 7 (diode) + Ch 4 (capacitor)
            </div>
            <div className="cover-lede">
              {kids
                ? <>Two ideas team up: the one-way valve and the bucket. Together they turn messy electricity into smooth, steady power — like the charger that powers your tablet.</>
                : <>Your first real power-supply circuit. A diode forces current one way; a capacitor fills the gaps. Together they convert a rough or alternating source into clean DC — the heart of every wall adapter.</>}
            </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 · two tools you already know</div>
          <div className="section-inner">
            <h2 className="serif">{kids ? "Valve + bucket." : "Diode + capacitor."}</h2>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 24, maxWidth: 900 }}>
              <div className="card" style={{ background: "transparent", padding: "22px" }}>
                <div className="eyebrow" style={{ marginBottom: 12, color: "var(--current)" }}>The diode (Ch 7)</div>
                <p style={{ margin: 0, fontSize: 17 }}>
                  {kids ? <>A one-way valve. Water (current) only goes through one direction.</>
                        : <>A one-way valve for current: passes forward, blocks reverse. It chops off the "wrong half" of a messy signal.</>}
                </p>
              </div>
              <div className="card" style={{ background: "transparent", padding: "22px" }}>
                <div className="eyebrow" style={{ marginBottom: 12, color: "var(--water)" }}>The capacitor (Ch 4)</div>
                <p style={{ margin: 0, fontSize: 17 }}>
                  {kids ? <>A bucket that fills and slowly empties — it holds water between refills.</>
                        : <>A bucket that charges up and releases slowly. It holds voltage up during the gaps, smoothing the bumps.</>}
                </p>
              </div>
            </div>
          </div>
        </section>

        <section className="section" id="how" data-screen-label="Rectify and smooth"
                 style={{ background: "var(--bg-deeper)" }}>
          <div className="marker">§ 02 · how the combo works</div>
          <div className="section-inner">
            <h2 className="serif">{kids ? "One-way, then smooth." : "Rectify, then smooth."}</h2>
            <p className="lede" style={{ maxWidth: "42em" }}>
              {kids
                ? <>First the valve makes the flow go one way only. But it's still bumpy. Then the bucket fills during the bumps and pours out during the gaps — so the LED sees steady light.</>
                : <>The diode rectifies: only forward pushes get through, so the output never reverses — but it still pulses. The capacitor, wired across the load, charges on each pulse and discharges into the load between pulses, filling the valleys. Net result: nearly flat DC.</>}
            </p>
            <p className="note" style={{ marginTop: 16, maxWidth: "42em" }}>
              {kids ? <>Build it below: source → valve → then the bucket and LED side by side.</>
                    : <>Placement: diode in the feed (anode to source +), then the cap across the rail-to-ground, with the LED + resistor load on the same rail.</>}
            </p>
          </div>
        </section>

        <section className="section" id="build" data-screen-label="Build it">
          <div className="marker">§ 03 · your turn · build a power supply</div>
          <div className="section-inner" style={{ maxWidth: 1180 }}>
            <h2 className="serif" style={{ marginBottom: 10 }}>{kids ? "Make smooth power." : "Build the rectifier + smoother."}</h2>
            <p className="lede" style={{ marginBottom: 24, maxWidth: "44em" }}>
              {kids
                ? <>Source → one-way valve → then the LED with a resistor, and the smoothing bucket across them. Get a clean, steady glow!</>
                : <>Feed the source through the diode (anode toward +), then power an LED + resistor load. Add the smoothing cap across the rail. A pass needs the diode forward AND the cap smoothing.</>}
            </p>
            <DesignGate kids={kids} chapterN="L2-07"
              spec={{ adult: "A 9 V source feeds your load through one diode (forward drop ≈ 0.7 V).", kids: "9 V goes through a one-way valve that uses up 0.7 V." }}
              prompt={{ adult: "What voltage actually reaches the load after the diode?", kids: "How many volts make it to the LED?" }}
              formula={{ adult: "V_out = 9 V − 0.7 V", kids: "9 − 0.7" }}
              unit="V" answer={8.3} tol={0.05}
              hint={{ adult: "A forward diode simply subtracts its ~0.7 V drop.", kids: "Just subtract 0.7 from 9." }}
              solution={{ adult: "V_out = 9 − 0.7 = 8.3 V reaches the load.", kids: "9 − 0.7 = 8.3 V." }}>
              <BreadboardBuilder
                kids={kids}
                sim={simulateRectifier}
                tools={RECT_TOOLS(kids)}
                limits={RECT_LIMITS}
                describe={describeRect}
                goalAdult="Build a smoothed supply: source → diode (anode to +) → LED + resistor load, with a capacitor across the rail to ground. Pass = rectified AND smoothed."
                goalKids="Source → one-way valve → LED + resistor, plus the smoothing bucket across them. Make the light clean and steady!"
              />
            </DesignGate>
          </div>
        </section>

        <PracticeProblems chapterN="L2-07" kids={kids}
          intro={kids ? "One-way-valve and smoothing puzzles." : "Rectifier & smoothing design math. Enter a number and check it."}
          problems={[
          (rng) => {
            const v = rng.int(5, 12, 1);
            return {
              q: { adult: `${v} V passes through one diode (0.7 V drop). What reaches the load?`, kids: `${v} V through a valve that uses 0.7 V. What's left?` },
              unit: "V", answer: +(v - 0.7).toFixed(1), tol: 0.05,
              hint: "Subtract the 0.7 V drop.",
              solution: { adult: `${v} − 0.7 = ${+(v - 0.7).toFixed(1)} V.`, kids: `${v} − 0.7 = ${+(v - 0.7).toFixed(1)}.` } };
          },
          (rng) => {
            const v = rng.int(9, 18, 1);
            return {
              q: { adult: `A full bridge sends current through TWO diodes (0.7 V each). From ${v} V peak, what's the peak output?`, kids: `Two valves in the path, each 0.7 V. From ${v} V, what's left?` },
              unit: "V", answer: +(v - 1.4).toFixed(1), tol: 0.04,
              hint: `Two drops: ${v} − 2×0.7.`,
              solution: { adult: `${v} − 1.4 = ${+(v - 1.4).toFixed(1)} V.`, kids: `${v} − 0.7 − 0.7 = ${+(v - 1.4).toFixed(1)}.` } };
          },
          (rng) => {
            const ma = rng.pick([50, 100, 150, 200]), f = rng.pick([100, 120]), uf = rng.pick([470, 1000, 2200]);
            const dv = +((ma / 1000) / (f * uf * 1e-6)).toFixed(2);
            return {
              q: { adult: `Reservoir-cap ripple is \u0394V = I ÷ (f·C). For ${ma} mA, ${f} Hz, ${uf} \u00b5F, what's the ripple? (V)`, kids: `Ripple = current ÷ (rate × bucket). ${ma / 1000} A, ${f} Hz, ${uf} \u00b5F. (volts)` },
              unit: "V", answer: dv, tol: 0.1,
              hint: `\u0394V = ${ma / 1000} ÷ (${f} × ${+(uf * 1e-6).toPrecision(6)}).`,
              solution: { adult: `\u0394V = ${ma / 1000} ÷ (${f} × ${+(uf * 1e-6).toPrecision(6)}) = ${ma / 1000} ÷ ${+(f * uf * 1e-6).toFixed(4)} = ${dv} V.`, kids: `${ma / 1000} ÷ (${f} × ${+(uf * 1e-6).toPrecision(6)}) ≈ ${dv}.` } };
          },
        ]} />

        <ChapterQuiz
          chapterN="L2-07"
          title={kids ? "Quick quiz!" : "Check your understanding."}
          intro={kids ? "Five questions about making smooth power." : "Rectifying & smoothing. 70% to pass; retry freely."}
          questions={kids ? RQ_KIDS : RQ_ADULT}
          pick={5}
        />

        <WhatsNext
          currentN="L2-07"
          kids={kids}
          summary={kids
            ? <>You built a power supply — the thing inside every charger! That's serious engineering.</>
            : <>You combined two components into a working power supply — the exact circuit inside a basic DC adapter. Real rectifiers add more diodes (a "bridge") and a regulator, but this is the core idea.</>}
          prevHref="chapter-l2-transistor.html"
          prevLabel="L2 · The Driver"
          nextHref="chapter-l2-oscillator.html"
          nextLabel="L2 · The Oscillator"
        />
      </main>
      <TweaksPanel title="Tweaks"><CommonTweaks t={t} setTweak={setTweak} /></TweaksPanel>
      <GlossaryFab />
    </>
  );
}

const RQ_ADULT = [
  { q: "A diode in a power supply is there to…", kind: "concept", options: ["store charge", "force current one direction (rectify)", "limit current", "amplify"], correct: 1, explain: "It rectifies — passes forward, blocks reverse — so the output never goes negative." },
  { q: "The smoothing capacitor goes…", kind: "concept", options: ["in series with the diode", "across the rail (output to ground)", "across the source only", "nowhere special"], correct: 1, explain: "Across the output rail to ground, so it charges on peaks and holds voltage up in the gaps." },
  { q: "Without the capacitor, the rectified output is…", kind: "concept", options: ["perfectly flat", "choppy / pulsing", "reversed", "zero"], correct: 1, explain: "Rectified but unsmoothed — a bumpy pulsing DC. The cap fills the valleys." },
  { q: "A diode drops about how much voltage when conducting?", kind: "concept", options: ["0 V", "0.7 V", "2 V", "9 V"], correct: 1, explain: "≈0.7 V for a silicon diode — its forward toll." },
  { q: "This circuit is the core of a…", kind: "concept", options: ["radio antenna", "DC power adapter", "motor", "speaker"], correct: 1, explain: "Diode + smoothing cap = the heart of every basic DC wall adapter." },
  { q: "If you flip the diode backwards, the load…", kind: "concept", options: ["runs brighter", "gets nothing (blocked)", "pops", "smooths better"], correct: 1, explain: "Reversed, the diode blocks the source — no current reaches the load." },
  {
    q: "This one-diode supply only rectifies HALF of the incoming AC wave. What does a full-bridge (four-diode) version fix?",
    kind: "concept",
    options: [
      "Nothing, they're identical",
      "It redirects the wasted reverse half forward too, giving a smoother, less-choppy result for the same capacitor",
      "It doubles the voltage",
      "It removes the need for a capacitor entirely",
    ],
    correct: 1,
    explain: "Half-wave (this circuit) throws away half the wave every cycle, leaving bigger gaps for the capacitor to fill. A bridge rectifier uses both halves, so the ripple is smaller before the cap even gets involved.",
  },
];
const RQ_KIDS = [
  { q: "A diode is a…", kind: "concept", options: ["bucket", "one-way valve", "wheel", "battery"], correct: 1, explain: "One-way valve — flow goes through only one direction!" },
  { q: "The capacitor (bucket) here makes the power…", kind: "concept", options: ["bumpy", "smooth and steady", "backward", "hot"], correct: 1, explain: "It fills the gaps so the light is steady." },
  { q: "Where does the smoothing bucket go?", kind: "concept", options: ["across the LED/rail", "in the trash", "on the battery only", "nowhere"], correct: 0, explain: "Across the rail, so it can fill in the bumps." },
  { q: "Valve + bucket together make a…", kind: "concept", options: ["radio", "power supply (like a charger)", "motor", "light switch"], correct: 1, explain: "A power supply — like what's inside your charger!" },
  { q: "If the valve is backwards, the LED…", kind: "concept", options: ["is brighter", "gets nothing", "explodes", "turns blue"], correct: 1, explain: "Backwards = blocked = no power gets through." },
  {
    q: "This valve only lets through HALF of every wobble from the wall. Chargers with FOUR valves fix that by…",
    kind: "concept",
    options: ["Doing nothing different", "Using the wasted half too, so there's less gap for the bucket to fill", "Making double the voltage", "Removing the bucket"],
    correct: 1,
    explain: "One valve wastes half the wobble every time. Four valves working together catch BOTH halves, leaving a smaller gap for the bucket to smooth.",
  },
];

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