/* chapter-l2-series.jsx — Level 2 · Chapter 2: Series & Parallel on the board.
   Applies Chapter 2 theory as a physical build: light TWO LEDs. */

const { useState, useEffect, useRef } = React;

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

/* Builder config for the two-LED challenge */
const L2_TOOLS = (kids) => [
  { id: "battery", label: kids ? "Battery (9V)" : "Battery 9V", hint: "+ leg first, then −" },
  { id: "resistor", label: kids ? "Resistor" : "Resistor 330Ω", hint: "either way round" },
  { id: "led", label: kids ? "LED ×2" : "LED", hint: "+ (long leg) first, then −" },
  { id: "wire", label: kids ? "Jumper wire" : "Jumper", hint: "connects two holes" },
];
const L2_LIMITS = { battery: 1, resistor: 3, led: 2, wire: 10 };

function describeMulti(r, kids) {
  if (r.state === "no-batt") return ["warn", kids ? "Add a battery first!" : "No battery placed."];
  if (r.state === "short") return ["fail", kids ? "Short circuit! + tied straight to −." : "Dead short: + tied to − with no load."];
  if (r.ledTotal < 2) return ["warn", kids ? "Place BOTH LEDs — the goal is to light two." : "Place two LEDs to complete the challenge."];
  if (r.anyPop) return ["fail", kids
    ? "Pop! 💥 An LED got too much flow. In parallel, each LED needs its OWN resistor."
    : "An LED exceeded its current limit. Parallel LEDs each need their own series resistor — one shared resistor won't protect both."];
  if (r.anyBack) return ["warn", kids ? "An LED is in backwards — flip it so + faces the push." : "An LED is reversed. Check orientation: anode toward +."];
  if (r.litCount === 2) return ["pass", kids
    ? "Both glowing! 🎉 You built a two-LED circuit — series or parallel, it works."
    : "Both LEDs lit within spec. Whether you went series (shared current, drops add) or parallel (each its own branch), you applied Chapter 2 correctly."];
  if (r.litCount === 1) return ["warn", kids ? "One down, one to go — get the second LED into the loop too." : "Only one LED is lit. Make sure the second has a complete forward path with current limiting."];
  return ["warn", kids ? "No glow yet — trace the path from + through each LED back to −." : "No LEDs lit. Trace each LED's path from + through a resistor back to −."];
}

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: "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-02" />
      <ProgressBar />
      <TopBar currentN="L2-02" chapterLabel="Level 2 · Series & Parallel"
              audience={t.audience}
              setAudience={(v) => setTweak("audience", v)} />
      <ChapterNav items={navItems} />

      <main>
        <section className="cover-page" id="cover" data-screen-label="L2-02 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 2</span>
            </div>
            <h1 className="serif cover-title">Two <em>LEDs</em>.</h1>
            <div className="eyebrow" style={{ marginTop: 36, marginBottom: 16, color: "var(--current)" }}>
              Applying Chapter 2 · Series & Parallel
            </div>
            <div className="cover-lede">
              {kids
                ? <>You lit one LED. Now light <em>two</em> — and there's more than one way to wire them. Series, or parallel? Build it and find out.</>
                : <>You lit one LED on the board. Now apply Chapter 2: wire <em>two</em>. Series shares one current and adds the voltage drops; parallel gives each its own branch. Both can work — if you respect current limiting.</>}
            </div>
            <div className="cover-cta">
              <a href="#recall" className="arrow-link"><span>Begin chapter</span><span className="arrow-glyph">↓</span></a>
            </div>
          </div>
        </section>

        {/* Recall */}
        <section className="section" id="recall" data-screen-label="Recall">
          <div className="marker">§ 01 · remember from Chapter 2</div>
          <div className="section-inner">
            <h2 className="serif">{kids ? "One road, or two roads." : "Series adds. Parallel splits."}</h2>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginTop: 26, maxWidth: 900 }}>
              <div className="card" style={{ background: "transparent", padding: "22px" }}>
                <div className="eyebrow" style={{ marginBottom: 12, color: "var(--water)" }}>Series · one loop</div>
                <p style={{ margin: 0, fontSize: 17 }}>
                  {kids
                    ? <>Both LEDs in <b>one loop</b>. The same flow goes through both. They share the current, and the battery has to push past <b>both</b>.</>
                    : <>Both LEDs in one loop: same current through each, and their ~2 V drops <b>add</b>. With 9 V you have headroom for two (4 V left for the resistor).</>}
                </p>
              </div>
              <div className="card" style={{ background: "transparent", padding: "22px" }}>
                <div className="eyebrow" style={{ marginBottom: 12, color: "var(--current)" }}>Parallel · two branches</div>
                <p style={{ margin: 0, fontSize: 17 }}>
                  {kids
                    ? <>Each LED on its <b>own branch</b> off the rails. Each needs its <b>own resistor</b> — or one will hog the flow and pop!</>
                    : <>Each LED on its own branch across the rails. Each branch needs its <b>own</b> series resistor — sharing one lets the lower-drop LED hog current and pop.</>}
                </p>
              </div>
            </div>
            <p className="note" style={{ marginTop: 22, maxWidth: "40em" }}>
              {kids
                ? <>Either way is allowed in the builder — try both and watch what happens!</>
                : <>The builder accepts either topology. Try series first (fewer parts), then parallel (more robust — one LED dying doesn't kill the other).</>}
            </p>
          </div>
        </section>

        {/* Build */}
        <section className="section" id="build" data-screen-label="Build it"
                 style={{ background: "var(--bg-deeper)" }}>
          <div className="marker">§ 02 · your turn · light two LEDs</div>
          <div className="section-inner" style={{ maxWidth: 1180 }}>
            <h2 className="serif" style={{ marginBottom: 10 }}>{kids ? "Light BOTH LEDs." : "Light both LEDs."}</h2>
            <p className="lede" style={{ marginBottom: 24, maxWidth: "42em" }}>
              {kids
                ? <>Place both LEDs and get them both glowing. Series (one loop) or parallel (two branches) — your choice. Just don't pop them!</>
                : <>Get both LEDs lit and safe. Series uses one resistor and one loop; parallel needs a resistor per branch. The sim judges each LED's current independently.</>}
            </p>
            <DesignGate kids={kids} chapterN="L2-02"
              spec={{ adult: "Spec: two red LEDs in series (each drops 2 V) at 10 mA, from 9 V.", kids: "Goal: two LEDs in a row, each using 2 V, with 10 mA flowing, from a 9 V battery." }}
              prompt={{ adult: "Both LEDs sit in one loop. Size the single series resistor.", kids: "One resistor controls the whole loop. What size?" }}
              formula={{ adult: "R = (9 V − 2 V − 2 V) ÷ 0.010 A", kids: "R = leftover volts ÷ flow" }}
              unit="Ω" answer={500} tol={0.06}
              hint={{ adult: "Both LEDs drop 2 V, so 4 V is used by the LEDs; 5 V is left for R. Divide by 0.010 A.", kids: "9 − 2 − 2 = 5 volts left. Divide by 0.010." }}
              solution={{ adult: "R = (9 − 4) ÷ 0.010 = 5 ÷ 0.010 = 500 Ω.", kids: "5 ÷ 0.010 = 500 Ω." }}>
              <BreadboardBuilder
                kids={kids}
                sim={simulateMulti}
                tools={L2_TOOLS(kids)}
                limits={L2_LIMITS}
                describe={describeMulti}
                goalAdult="Light BOTH LEDs without popping either. Series (one loop, drops add) or parallel (a resistor per branch) — both are valid."
                goalKids="Get BOTH LEDs glowing! Try one loop (series) or two branches (parallel). Each branch in parallel needs its own resistor."
              />
            </DesignGate>
          </div>
        </section>

        <PracticeProblems chapterN="L2-02" kids={kids}
          intro={kids ? "Wiring-math puzzles, just like you'll do for real builds." : "Applied series/parallel design math. Enter a number and check it."}
          problems={[
          (rng) => {
            const v = rng.int(8, 12, 1), ma = rng.pick([10, 15, 20]);
            const r = Math.round((v - 4) / (ma / 1000));
            return {
              q: { adult: `Two LEDs (2 V each) in series at ${ma} mA from ${v} V. What series resistor do you need?`, kids: `Two LEDs in a row, each 2 V, ${ma} mA, from ${v} V. What resistor?` },
              unit: "\u03a9", answer: r, tol: 0.05,
              hint: `Leftover = ${v} − 2 − 2 = ${v - 4} V; R = ${v - 4} ÷ ${ma / 1000}.`,
              solution: { adult: `R = (${v} − 4) ÷ ${ma / 1000} = ${r} \u03a9.`, kids: `${v - 4} ÷ ${ma / 1000} = ${r}.` } };
          },
          (rng) => {
            const ma = rng.pick([8, 10, 12, 15]), n = rng.int(2, 3, 1);
            return {
              q: { adult: `Now wire ${n} LEDs in PARALLEL, each at ${ma} mA. What total current does the battery supply?`, kids: `${n} LEDs side by side, each pulling ${ma} mA. How much from the battery total?` },
              unit: "mA", answer: ma * n, tol: 0.02,
              hint: `Parallel branch currents add: ${Array(n).fill(ma).join(" + ")}.`,
              solution: { adult: `Parallel currents add: ${Array(n).fill(ma).join(" + ")} = ${ma * n} mA.`, kids: `${Array(n).fill(ma).join(" + ")} = ${ma * n}.` } };
          },
          (rng) => {
            const v = rng.int(8, 12, 1), ma = rng.pick([10, 15, 20]);
            const r = Math.round((v - 2) / (ma / 1000));
            return {
              q: { adult: `Each parallel branch (LED at 2 V, ${ma} mA) needs its own resistor from ${v} V. What value?`, kids: `Each branch LED is 2 V at ${ma} mA from ${v} V. What resistor per branch?` },
              unit: "\u03a9", answer: r, tol: 0.05,
              hint: `Per branch: (${v} − 2) ÷ ${ma / 1000}.`,
              solution: { adult: `R = (${v} − 2) ÷ ${ma / 1000} = ${r} \u03a9 each.`, kids: `${v - 2} ÷ ${ma / 1000} = ${r}.` } };
          },
        ]} />

        <ChapterQuiz
          chapterN="L2-02"
          title={kids ? "Quick quiz!" : "Check your understanding."}
          intro={kids ? "Five questions about wiring two LEDs." : "Series vs parallel on the board. 70% to pass; retry freely."}
          questions={kids ? L2_QUIZ_KIDS : L2_QUIZ_ADULT}
          pick={5}
        />

        <WhatsNext
          currentN="L2-02"
          kids={kids}
          summary={kids
            ? <>You wired two LEDs — series and parallel, for real. Next in Level 2: how much heat your resistors make, and picking the right one.</>
            : <>You applied series and parallel on a real board. Next: power and resistor sizing — making sure your parts can take the heat. More Level 2 coming.</>}
          prevHref="breadboard.html"
          prevLabel="L2 · Breadboard"
          nextHref="map.html"
          nextLabel="Back to course"
        />
      </main>

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

const L2_QUIZ_ADULT = [
  { q: "Two LEDs in series share the same…", kind: "concept", options: ["voltage drop", "current", "color", "resistor wattage"], correct: 1, explain: "Series = one path = identical current through both. Their voltage drops add." },
  { q: "Wiring two LEDs in parallel, how many current-limiting resistors do you need?", kind: "concept", options: ["zero", "one shared is fine", "one per branch (two)", "three"], correct: 2, explain: "Each branch needs its own resistor; sharing one lets the lower-Vf LED hog current and pop." },
  { q: "Two 2 V LEDs in series off a 9 V supply leave how much for the resistor?", kind: "math", options: ["9 V", "7 V", "5 V", "4 V"], correct: 2, explain: "Two LED drops use 2 + 2 = 4 V, leaving 9 − 4 = 5 V across the resistor." },
  { q: "Why might you choose parallel over series for indicator LEDs?", kind: "concept", options: ["it uses fewer parts", "if one fails open, the others stay lit", "it needs no resistors", "it's always brighter"], correct: 1, explain: "Parallel branches are independent — one open LED doesn't break the others." },
  { q: "Put both legs of one LED in the same breadboard column. That LED will…", kind: "concept", options: ["be brightest", "be shorted out / not light", "pop", "turn the others off"], correct: 1, explain: "Same column = same node = both legs shorted together. No voltage across it." },
  { q: "In series, adding a second LED makes the current…", kind: "concept", options: ["double", "drop (more total voltage is used up)", "stay identical", "reverse"], correct: 1, explain: "The extra 2 V drop leaves less across the resistor, so I = V_R/R falls." },
  {
    q: "Three LEDs in SERIES on a 9 V battery share…",
    kind: "concept",
    options: ["the current — each gets a third", "the voltage — their drops add up", "nothing", "the same resistor rating"],
    correct: 1,
    explain: "Series parts share the push: 3 × 2 V of LED drops leaves 3 V for the resistor.",
  },
  {
    q: "One LED in a PARALLEL bank burns out. The others…",
    kind: "concept",
    options: ["all go dark", "keep glowing", "get dimmer", "reverse"],
    correct: 1,
    explain: "Each branch is its own loop — losing one doesn't break the others.",
  },
  {
    q: "Your bench multimeter reads across a lit LED's legs and shows ~2 V. Adding a THIRD series LED, that reading…",
    kind: "concept",
    options: ["stays about 2 V — each LED still drops its own ~2 V regardless of how many are in the chain", "triples to 6 V", "drops to 0.67 V", "becomes unpredictable"],
    correct: 0,
    explain: "Each diode's forward drop is set by its own physics (~2 V for a typical LED), not by how many others share the loop — series just means the drops ADD to the total, not that any one LED's drop changes.",
  },
];
const L2_QUIZ_KIDS = [
  { q: "Two LEDs in ONE loop (series) share the same…", kind: "concept", options: ["color", "flow (current)", "battery", "wire color"], correct: 1, explain: "Same loop = same flow through both. They take turns with the same water!" },
  { q: "Two LEDs on TWO branches (parallel) each need…", kind: "concept", options: ["nothing", "their own resistor", "two batteries", "a switch"], correct: 1, explain: "Each branch needs its own resistor so neither LED hogs the flow and pops." },
  { q: "If one parallel LED burns out, the other…", kind: "concept", options: ["also dies", "keeps glowing", "gets brighter forever", "explodes"], correct: 1, explain: "Parallel branches are independent — the other keeps going. That's why it's handy!" },
  { q: "Both legs of an LED in the SAME column means…", kind: "concept", options: ["it glows bright", "it's shorted and won't light", "it pops", "magic"], correct: 1, explain: "Both legs touch the same connected line, so the LED gets skipped over." },
  { q: "To light two LEDs you should place…", kind: "concept", options: ["one LED", "both LEDs with a complete path each", "no LEDs", "only resistors"], correct: 1, explain: "Both LEDs need a full path from + back to −, with a resistor to stay safe." },
  {
    q: "Lights in a line (series) all share…",
    kind: "concept",
    options: ["the push", "the snacks", "the colors", "nothing"],
    correct: 0,
    explain: "Each light uses part of the push — together they use it all.",
  },
  {
    q: "Lights side-by-side (parallel) each get…",
    kind: "concept",
    options: ["a little push", "the FULL push", "no push", "someone else's push"],
    correct: 1,
    explain: "Every branch connects straight across the battery — full push each.",
  },
  {
    q: "Old-style holiday lights all went dark when one died because they were wired…",
    options: ["in parallel", "in series", "upside down", "with no battery"],
    correct: 1,
    explain: "In series there's only one road — break it anywhere and everything stops.",
  },
];

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