/* chapter-l2-power.jsx — Level 2 · Chapter 3: Sizing It Up.
   Applies Chapter 3 (power & heat): choose a resistor VALUE and WATTAGE
   that lights the LED without overheating. */

const { useState, useEffect, useRef } = React;

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

/* Resistor choices: value (Ω) × rating (W). With 9 V, 2 V LED → 7 V across R.
   - 100Ω: I=70mA → pops the LED (too much current)
   - 220Ω: I=32mA → bright, P_R = 0.032²... actually I²R = 0.0318²*220 ≈ 0.22W (ok on ¼W, hot)
   - 330Ω: I=21mA → good, P_R ≈ 0.021²*330 ≈ 0.15W (fine)
   - 1kΩ:  I=7mA  → dim
   We give two ratings (1/8 W and 1/4 W) so wattage matters:
   220Ω @ 1/8W (0.125): P=0.22W > 0.125 → cooks. 220Ω @ 1/4W: ok. */
const PW_TOOLS = (kids) => [
  { id: "battery", label: kids ? "Battery (9V)" : "Battery 9V", hint: "+ leg first, then −" },
  { id: "led", label: "LED", hint: "+ (long leg) first, then −" },
  { id: "wire", label: kids ? "Jumper wire" : "Jumper", hint: "connects two holes" },
  { id: "r100", label: "100Ω ⅛W", hint: "low value, small rating", part: { type: "resistor", R: 100, rating: 0.125 } },
  { id: "r220", label: "220Ω ⅛W", hint: "low value, small rating", part: { type: "resistor", R: 220, rating: 0.125 } },
  { id: "r330", label: "330Ω ¼W", hint: "mid value, bigger rating", part: { type: "resistor", R: 330, rating: 0.25 } },
  { id: "r1k", label: "1kΩ ¼W", hint: "high value", part: { type: "resistor", R: 1000, rating: 0.25 } },
];
// each resistor tool maps to the same underlying "resistor" type for limits
const PW_LIMITS = { battery: 1, led: 1, wire: 8, r100: 1, r220: 1, r330: 1, r1k: 1 };

function describePower(r, kids) {
  switch (r.state) {
    case "no-batt": return ["warn", kids ? "Add a battery first!" : "No battery placed."];
    case "open": return ["warn", kids ? "The loop isn't finished — connect + through a resistor and the LED back to −." : "Open circuit. Complete the loop: + → resistor → LED → −."];
    case "backwards": return ["warn", kids ? "The LED is backwards — flip it." : "LED reversed. Anode must face +."];
    case "short": return ["fail", kids ? "Short circuit! No LED in the loop." : "Short / no LED in the conducting path."];
    case "pop": return ["fail", kids
      ? "Pop! 💥 Too much flow for the LED. Use a bigger resistor value."
      : `LED popped at ${(r.I||0).toFixed(0)} mA — the resistor value is too low. Raise the resistance to limit current.`];
    case "cooked": return ["fail", kids
      ? "The resistor cooked! 🔥 It got too hot. Pick one with a bigger wattage rating."
      : `Resistor overheated: it dissipates ${r.Pr.toFixed(2)} W but is rated for only ${r.rating} W. Pick a higher-wattage part (or a bigger resistance to cut the current).`];
    case "lit":
      if (r.ledState === "good") return ["pass", kids
        ? "Perfect glow, and the resistor stays cool. That's good engineering!"
        : `Lit at ${r.I.toFixed(0)} mA with the resistor safely within its power rating. Correct value AND wattage — textbook.`];
      if (r.ledState === "bright") return ["pass", kids
        ? "It glows nice and bright, and nothing's overheating. Works!"
        : `Lit at ${r.I.toFixed(0)} mA — bright but safe, resistor within rating.`];
      if (r.ledState === "dim") return ["warn", kids
        ? "It glows, but dimly — that resistor value is a bit high."
        : `Only ${r.I.toFixed(1)} mA — safe, but dim. A lower resistance gives more light.`];
      return ["warn", kids ? "Barely glowing." : `Just ${r.I.toFixed(1)} mA — too dim to be useful.`];
    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: "sizing", label: kids ? "Two numbers" : "Value & watts" },
    { 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-03" />
      <ProgressBar />
      <TopBar currentN="L2-03" chapterLabel="Level 2 · Sizing It Up"
              audience={t.audience}
              setAudience={(v) => setTweak("audience", v)} />
      <ChapterNav items={navItems} />

      <main>
        <section className="cover-page" id="cover" data-screen-label="L2-03 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 3</span>
            </div>
            <h1 className="serif cover-title">Sizing It <em>Up</em>.</h1>
            <div className="eyebrow" style={{ marginTop: 36, marginBottom: 16, color: "var(--current)" }}>
              Applying Chapter 3 · Power & Heat
            </div>
            <div className="cover-lede">
              {kids
                ? <>A resistor doesn't just slow the flow — it gets <em>warm</em> doing it. Pick one too small and it cooks. This time you choose the resistor yourself.</>
                : <>Until now the resistor was a given. Now <em>you</em> pick it — both its resistance <em>and</em> its power rating. Choose wrong and you'll pop the LED or cook the resistor. Welcome to real component selection.</>}
            </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 3</div>
          <div className="section-inner">
            <h2 className="serif">{kids ? "Squeezing makes heat." : "Power turns into heat."}</h2>
            <p className="lede" style={{ maxWidth: "42em" }}>
              {kids
                ? <>Every resistor turns some flow into <em>heat</em> — that's its job. A little resistor can only handle a little heat before it burns up. Bigger resistors (in size) can take more.</>
                : <>A resistor dissipates <span className="mono">P = I²R</span> as heat. Every real resistor has a <em>power rating</em> — ⅛ W, ¼ W, ½ W, 1 W… Exceed it and the part discolors, drifts, then fails. Sizing means meeting the circuit's needs <em>and</em> staying under that rating.</>}
            </p>
            <div className="card" style={{ background: "transparent", padding: "20px 22px", marginTop: 18, maxWidth: 640 }}>
              <div className="eyebrow" style={{ marginBottom: 10 }}>{kids ? "the heat formula" : "resistor power"}</div>
              <div className="eq" style={{ fontSize: 30 }}>
                <span style={{ color: "var(--ink)" }}>P</span>
                <span className="op">=</span>
                <span className="I">I</span>
                <span style={{ fontSize: "0.6em", verticalAlign: "super" }}>2</span>
                <span className="op">·</span>
                <span className="R">R</span>
              </div>
              <div className="marg" style={{ marginTop: 8 }}>
                {kids
                  ? <>More flow through a resistor = lots more heat (it's the flow times itself!).</>
                  : <>Current is squared — double the current is 4× the heat. That's why current-limiting matters twice over.</>}
              </div>
            </div>
          </div>
        </section>

        <section className="section" id="sizing" data-screen-label="Value and watts"
                 style={{ background: "var(--bg-deeper)" }}>
          <div className="marker">§ 02 · two numbers on every resistor</div>
          <div className="section-inner">
            <h2 className="serif">{kids ? "Value AND size." : "Two specs, not one."}</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(--water)" }}>The value (Ω)</div>
                <p style={{ margin: 0, fontSize: 17 }}>
                  {kids
                    ? <>How hard it squeezes. Too small → too much flow → the LED <b>pops</b>. Too big → barely glows.</>
                    : <>Sets the current via Ohm's law. Too low pops the LED (over-current); too high starves it. For a 2 V LED at ~15 mA off 9 V, you want roughly 330–470 Ω.</>}
                </p>
              </div>
              <div className="card" style={{ background: "transparent", padding: "22px" }}>
                <div className="eyebrow" style={{ marginBottom: 12, color: "var(--current)" }}>The rating (W)</div>
                <p style={{ margin: 0, fontSize: 17 }}>
                  {kids
                    ? <>How much heat it can take. Pick one rated for <b>more</b> watts than it actually makes, or it <b>burns up</b>.</>
                    : <>The max heat it can shed safely. Compute P = I²R, then pick a rating comfortably above it (2× is a good rule). A correct value on an under-rated part still fails.</>}
                </p>
              </div>
            </div>
            <p className="note" style={{ marginTop: 22, maxWidth: "42em" }}>
              {kids
                ? <>In the builder you'll pick from real resistors — each shows its value and its size. Find one that lights the LED <em>and</em> stays cool.</>
                : <>The builder offers four real parts. One pops the LED, one cooks itself, one's too dim, and at least one is just right. Reason it out before you power on.</>}
            </p>
          </div>
        </section>

        <section className="section" id="build" data-screen-label="Build it">
          <div className="marker">§ 03 · your turn · pick the right resistor</div>
          <div className="section-inner" style={{ maxWidth: 1180 }}>
            <h2 className="serif" style={{ marginBottom: 10 }}>{kids ? "Light it — keep it cool." : "Light it, keep it cool."}</h2>
            <p className="lede" style={{ marginBottom: 24, maxWidth: "42em" }}>
              {kids
                ? <>Build the LED circuit, but this time choose which resistor to use. Get a good glow without popping the LED or cooking the resistor!</>
                : <>Same loop as before, but you choose the resistor. Aim for a healthy ~15–25 mA with the resistor staying within its wattage rating. Only some choices satisfy both.</>}
            </p>
            <DesignGate kids={kids} chapterN="L2-03"
              spec={{ adult: "Spec: one red LED (drops 2 V) at 15 mA, from a 9 V supply.", kids: "Goal: an LED (2 V) glowing at 15 mA, from 9 V." }}
              prompt={{ adult: "Size the series resistor for this LED.", kids: "What resistor gives 15 mA?" }}
              formula={{ adult: "R = (9 V − 2 V) ÷ 0.015 A", kids: "R = leftover volts ÷ flow" }}
              unit="Ω" answer={467} tol={0.07}
              hint={{ adult: "Leftover voltage is 9 − 2 = 7 V. Divide by 0.015 A (≈ a 470 Ω standard part).", kids: "7 volts left ÷ 0.015 ≈ 470." }}
              solution={{ adult: "R = 7 V ÷ 0.015 A = 467 Ω → use a 470 Ω resistor.", kids: "7 ÷ 0.015 ≈ 470 Ω." }}>
              <BreadboardBuilder
                kids={kids}
                sim={simulatePower}
                tools={PW_TOOLS(kids)}
                limits={PW_LIMITS}
                describe={describePower}
                goalAdult="Light the LED at a healthy current with a resistor that stays within its power rating. Wrong value → pops the LED; under-rated → cooks the resistor."
                goalKids="Light the LED with a good glow — and pick a resistor that won't get too hot and burn up!"
              />
            </DesignGate>
          </div>
        </section>

        <PracticeProblems chapterN="L2-03" kids={kids}
          intro={kids ? "Power and heat puzzles for real parts." : "Resistor sizing and power-rating math. Enter a number and check it."}
          problems={[
          (rng) => {
            const v = rng.int(6, 12, 1), ma = rng.pick([10, 15, 20]);
            const r = Math.round((v - 2) / (ma / 1000));
            return {
              q: { adult: `An LED (2 V) should run at ${ma} mA from ${v} V. What series resistor?`, kids: `LED at 2 V, want ${ma} mA, from ${v} V. What resistor?` },
              unit: "\u03a9", answer: r, tol: 0.06,
              hint: `R = (${v} − 2) ÷ ${ma / 1000}.`,
              solution: { adult: `R = ${v - 2} ÷ ${ma / 1000} = ${r} \u03a9.`, kids: `${v - 2} ÷ ${ma / 1000} ≈ ${r}.` } };
          },
          (rng) => {
            const r = rng.pick([330, 470, 680]), ma = rng.pick([10, 15, 20]);
            const mw = +(Math.pow(ma / 1000, 2) * r * 1000).toFixed(0);
            return {
              q: { adult: `A ${r} \u03a9 resistor carries ${ma} mA. How much power does it dissipate? (Answer in milliwatts.)`, kids: `${r} \u03a9 with ${ma} mA through it. How much heat (in milliwatts)?` },
              unit: "mW", answer: mw, tol: 0.1,
              hint: `P = I²R = ${ma / 1000}² × ${r}, then ×1000 for mW.`,
              solution: { adult: `P = I²R = ${+Math.pow(ma / 1000, 2).toFixed(6)} × ${r} ≈ ${mw} mW.`, kids: `${ma / 1000} × ${ma / 1000} × ${r} ≈ ${mw} mW.` } };
          },
          (rng) => {
            const ratingMw = rng.pick([125, 250]), heat = rng.pick([105, 180, 95, 220]);
            const ok = ratingMw >= heat ? 1 : 0;
            return {
              q: { adult: `A resistor dissipates ${heat} mW. Is a ${ratingMw === 125 ? "\u215b W (125 mW)" : "\u00bc W (250 mW)"} resistor safe for it? Enter 1 for yes, 0 for no.`, kids: `A resistor makes ${heat} mW of heat. Can a ${ratingMw} mW resistor handle it? Type 1 for yes, 0 for no.` },
              unit: "", answer: ok,
              hint: `${ratingMw} mW rating vs ${heat} mW actual — is the rating bigger?`,
              solution: { adult: `${heat} mW ${ok ? "<" : ">"} ${ratingMw} mW, so ${ok ? "yes — it's within rating" : "no — pick a bigger rating"}.`, kids: ok ? `${heat} is less than ${ratingMw}, so yes!` : `${heat} is more than ${ratingMw} — too much, so no.` } };
          },
        ]} />

        <ChapterQuiz
          chapterN="L2-03"
          title={kids ? "Quick quiz!" : "Check your understanding."}
          intro={kids ? "Five questions about picking resistors." : "Resistor sizing & power. 70% to pass; retry freely."}
          questions={kids ? PW_QUIZ_KIDS : PW_QUIZ_ADULT}
          pick={5}
        />

        <WhatsNext
          currentN="L2-03"
          kids={kids}
          summary={kids
            ? <>You can pick the right resistor now — value AND size. Next in Level 2: making an LED blink all by itself.</>
            : <>You sized a resistor for both current and heat — a daily engineering task. Next: add a capacitor and make the circuit do something over time.</>}
          prevHref="chapter-l2-series.html"
          prevLabel="L2 · Two LEDs"
          nextHref="map.html"
          nextLabel="Back to course"
        />
      </main>

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

const PW_QUIZ_ADULT = [
  { q: "A resistor's power dissipation is given by…", kind: "concept", options: ["P = V + I", "P = I²R", "P = R / I", "P = I / R²"], correct: 1, explain: "P = I²R (equivalently VI or V²/R). Current is squared, so it dominates." },
  { q: "You compute a resistor will dissipate 0.22 W. Which rating is safe?", kind: "math", options: ["⅛ W (0.125 W)", "¼ W (0.25 W)", "neither", "any of them"], correct: 1, explain: "0.22 W exceeds ⅛ W but fits under ¼ W — ideally with a bit of margin." },
  { q: "Your LED pops the instant you power on. Most likely the resistor value was…", kind: "concept", options: ["too high", "too low (too little current limiting)", "the right value", "irrelevant"], correct: 1, explain: "Too low a resistance lets too much current through — the LED over-currents and dies." },
  { q: "Doubling the current through a resistor changes its heat by…", kind: "math", options: ["2×", "4×", "half", "no change"], correct: 1, explain: "P = I²R — squaring means 2× current is 4× the power dissipated." },
  { q: "Why pick a resistor rated well above the power it'll dissipate?", kind: "concept", options: ["for looks", "margin — heat, tolerance, and lifespan", "to use more current", "it's required by law"], correct: 1, explain: "Headroom keeps the part cool, stable, and long-lived. ~2× rating is a common rule." },
  { q: "A correct-value resistor that's under-rated for wattage will…", kind: "concept", options: ["work forever", "overheat and eventually fail", "pop the LED", "draw no current"], correct: 1, explain: "Right current, wrong thermal spec — it cooks. Both numbers matter." },
  {
    q: "Your LED circuit draws 28 mA from a 550 mAh battery. Roughly how long does it run?",
    kind: "math",
    options: ["2 hours", "20 hours", "55 hours", "200 hours"],
    correct: 1,
    explain: "Life = capacity ÷ draw = 550 ÷ 28 ≈ 20 h. Brightness costs current; current costs hours.",
  },
  {
    q: "A resistor dissipating 40 mW needs a rating of at least (with 2× margin)…",
    kind: "math",
    options: ["1/16 W", "80 mW — ⅛ W is fine", "5 W minimum", "ratings don't matter"],
    correct: 1,
    explain: "2 × 40 mW = 80 mW. An ⅛ W (125 mW) part clears it; ¼ W is the common pick.",
  },
  {
    q: "Two identical resistors, same current. One is rated ⅛ W, the other 2 W. Which runs cooler?",
    kind: "concept",
    options: ["Neither — same current means same heat generated", "The 2 W one — a bigger rating radiates heat better", "The ⅛ W one", "Rating doesn't affect temperature"],
    correct: 0,
    explain: "The power DISSIPATED (P=I²R) is identical for both — the wattage rating only says how much heat a part can survive, not how much it makes. Same I and R means same heat; the bigger-rated part just has more margin.",
  },
];
const PW_QUIZ_KIDS = [
  { q: "What does a resistor turn extra flow into?", kind: "concept", options: ["light", "heat", "sound", "water"], correct: 1, explain: "Heat! That's why it can burn up if it makes too much." },
  { q: "If the resistor value is too SMALL, the LED…", kind: "concept", options: ["glows softly", "pops from too much flow", "stays off", "turns blue"], correct: 1, explain: "Too little squeeze = too much flow = pop!" },
  { q: "If the resistor value is too BIG, the LED…", kind: "concept", options: ["pops", "barely glows", "gets hot", "explodes"], correct: 1, explain: "Lots of squeeze = little flow = dim glow." },
  { q: "The wattage rating tells you…", kind: "concept", options: ["the color", "how much heat it can handle", "the price", "how long it is"], correct: 1, explain: "Bigger rating = can take more heat before burning up." },
  { q: "The best resistor is one that…", kind: "concept", options: ["is the cheapest", "lights the LED AND stays cool", "is the biggest", "has no value"], correct: 1, explain: "You want a good glow and a resistor that doesn't overheat. Both!" },
  {
    q: "A bigger battery (more mAh) means your light…",
    kind: "concept",
    options: ["glows brighter", "lasts longer", "changes color", "blinks"],
    correct: 1,
    explain: "mAh is the barrel's size — more water, more hours. (Brightness comes from current, not capacity.)",
  },
  {
    q: "A resistor that gets too much heat will…",
    kind: "concept",
    options: ["work better", "cook and fail", "turn into a wire", "cool down"],
    correct: 1,
    explain: "Every part has a heat budget. Go past it and the part burns up.",
  },
  {
    q: "To make the battery last LONGER, you want the circuit to sip…",
    kind: "concept",
    options: ["more flow", "less flow", "hotter flow", "no flow ever"],
    correct: 1,
    explain: "Less current = slower drain = more hours of glow.",
  },
  {
    q: "Two resistors get the same flow. One is a tough big one, one is a tiny delicate one. Which feels hotter?",
    kind: "concept",
    options: ["Neither — same flow makes the same heat in both", "The tiny one, always", "The big one, always", "Heat depends only on size"],
    correct: 0,
    explain: "Same flow through the same value makes the same heat — the size/rating just says how much heat each one can SURVIVE, not how much it makes.",
  },
];

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