/* chapter-l2-switch.jsx — Level 2 · Chapter 5: The Button (switches & logic). */

const { useState, useEffect, useRef } = React;

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

const SW_TOOLS = (kids) => [
  { id: "battery", label: kids ? "Battery (9V)" : "Battery 9V", hint: "+ leg first, then −" },
  { id: "resistor", label: "Resistor 330Ω", hint: "either way round" },
  { id: "led", label: "LED", hint: "+ (long leg) first, then −" },
  { id: "switch", label: kids ? "Switch ×2" : "Switch", hint: "tap it on the board to flip on/off", part: { type: "switch" } },
  { id: "wire", label: kids ? "Jumper wire" : "Jumper", hint: "connects two holes" },
];
const SW_LIMITS = { battery: 1, resistor: 2, led: 1, switch: 2, wire: 10 };

function describeLogic(r, kids) {
  switch (r.state) {
    case "no-batt": return ["warn", kids ? "Add a battery first!" : "No battery placed."];
    case "open": return ["warn", kids ? "Finish the loop — and remember you need at least one switch in it." : "Open circuit. Put a switch (and a resistor + LED) in a complete loop."];
    case "backwards": return ["warn", kids ? "The LED is backwards — flip it." : "LED reversed."];
    case "short": return ["fail", kids ? "Short circuit!" : "Short / no LED in the path."];
    case "switch-open": return ["warn", kids
      ? "A switch in the path is OFF. Tap the switches on the board to turn them on — then power on again."
      : "A switch in the conducting path is open. Tap switches to close them, then re-test. (Series switches = AND: all must be closed.)"];
    case "pop": return ["fail", kids ? "Pop! 💥 Don't forget the resistor." : `LED over-current. Keep current limiting.`];
    case "lit":
      return ["pass", kids
        ? "The LED is on — your switches let the flow through! Flip one off and watch it die."
        : `Lit at ${r.I.toFixed(0)} mA through the closed switch path. Open any series switch and it goes dark — that's an AND gate. Two parallel switches would be an OR.`];
    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: "logic", label: kids ? "AND / OR" : "Logic" },
    { 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-05" />
      <ProgressBar />
      <TopBar currentN="L2-05" chapterLabel="Level 2 · The Button"
              audience={t.audience}
              setAudience={(v) => setTweak("audience", v)} />
      <ChapterNav items={navItems} />

      <main>
        <section className="cover-page" id="cover" data-screen-label="L2-05 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 5</span>
            </div>
            <h1 className="serif cover-title">The <em>Button</em>.</h1>
            <div className="eyebrow" style={{ marginTop: 36, marginBottom: 16, color: "var(--current)" }}>
              Applying Chapter 5 · Switches & Logic
            </div>
            <div className="cover-lede">
              {kids
                ? <>Now you control the circuit. Add switches you can tap on and off — and combine two of them to make the LED obey simple rules.</>
                : <>Add switches you can actually toggle on the board. Two in series is an AND gate; two in parallel is an OR. You're building the first logic of a computer, by hand.</>}
            </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 5</div>
          <div className="section-inner">
            <h2 className="serif">{kids ? "Open or closed." : "A switch is a gap you control."}</h2>
            <p className="lede" style={{ maxWidth: "42em" }}>
              {kids
                ? <>A switch is just a gap in the wire you can open or close. Closed → flow gets through. Open → flow stops. On the board, tap a switch to flip it.</>
                : <>A switch makes or breaks the conducting path. Closed = wire; open = no current. In this builder, tap a placed switch to toggle it, then power on to see the result.</>}
            </p>
          </div>
        </section>

        <section className="section" id="logic" data-screen-label="Logic"
                 style={{ background: "var(--bg-deeper)" }}>
          <div className="marker">§ 02 · two switches, two rules</div>
          <div className="section-inner">
            <h2 className="serif">{kids ? "Both, or either." : "AND vs OR."}</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)" }}>Series = AND</div>
                <p style={{ margin: 0, fontSize: 17 }}>
                  {kids
                    ? <>Two switches in a row. The LED lights only if <b>both</b> are on. One off → dark.</>
                    : <>Two switches in series: the loop conducts only when <b>both</b> are closed. Open either and current stops. Output = A AND B.</>}
                </p>
              </div>
              <div className="card" style={{ background: "transparent", padding: "22px" }}>
                <div className="eyebrow" style={{ marginBottom: 12, color: "var(--current)" }}>Parallel = OR</div>
                <p style={{ margin: 0, fontSize: 17 }}>
                  {kids
                    ? <>Two switches side by side. The LED lights if <b>either</b> one is on. Both off → dark.</>
                    : <>Two switches in parallel: <b>either</b> closed switch completes the loop. Output = A OR B. Only both-open kills it.</>}
                </p>
              </div>
            </div>
            <p className="note" style={{ marginTop: 22, maxWidth: "42em" }}>
              {kids ? <>Build either one in the builder and tap the switches to test all the combinations!</>
                    : <>Build either topology below, then toggle the switches through all four input combinations and watch the truth table come alive.</>}
            </p>
          </div>
        </section>

        <section className="section" id="build" data-screen-label="Build it">
          <div className="marker">§ 03 · your turn · gate the LED</div>
          <div className="section-inner" style={{ maxWidth: 1180 }}>
            <h2 className="serif" style={{ marginBottom: 10 }}>{kids ? "Control the LED with switches." : "Gate the LED with switches."}</h2>
            <p className="lede" style={{ marginBottom: 24, maxWidth: "42em" }}>
              {kids
                ? <>Build the LED loop, but put switches in the path. After you power on, tap the switches right on the board to flip them on and off.</>
                : <>Place one or two switches in the loop (series for AND, parallel for OR). Tap a switch on the board to toggle it; the LED responds live. Keep the current-limiting resistor.</>}
            </p>
            <DesignGate kids={kids} chapterN="L2-05"
              spec={{ adult: "You'll wire two enable switches into the LED loop.", kids: "You'll put two switches in the loop." }}
              prompt={{ adult: "Each switch is on or off. How many distinct combinations can two switches make?", kids: "Each switch is on or off. How many different combos for two switches?" }}
              formula={{ adult: "combinations = 2 × 2", kids: "2 × 2" }}
              unit="" answer={4} tol={0.01}
              hint={{ adult: "Each switch doubles the count: 2 states × 2 states.", kids: "2 times 2." }}
              solution={{ adult: "2 × 2 = 4 combinations (off-off, off-on, on-off, on-on).", kids: "2 × 2 = 4." }}>
              <BreadboardBuilder
                kids={kids}
                sim={simulateLogic}
                tools={SW_TOOLS(kids)}
                limits={SW_LIMITS}
                describe={describeLogic}
                goalAdult="Light the LED through a switch path: battery → switch(es) → resistor → LED → back. Tap switches on the board to toggle them. Series = AND, parallel = OR."
                goalKids="Build the loop with switches in it. Tap the switches on the board to turn them on, and get the LED to glow!"
              />
            </DesignGate>
            <p className="note" style={{ marginTop: 14 }}>
              {kids ? <>Tip: the round switch on the board shows 0 (off) or 1 (on). Tap it to flip!</>
                    : <>Tip: placed switches render as a 0/1 token — tap to toggle, then re-power.</>}
            </p>
          </div>
        </section>

        <PracticeProblems chapterN="L2-05" kids={kids}
          intro={kids ? "Switch-logic counting puzzles." : "Boolean logic counting. Enter a number and check it."}
          problems={[
          (rng) => {
            const n = rng.int(2, 4, 1);
            return {
              q: { adult: `${n} switches, each on or off. How many distinct combinations?`, kids: `${n} switches, each on/off. How many combos?` },
              unit: "", answer: Math.pow(2, n),
              hint: `${Array(n).fill(2).join(" × ")}.`,
              solution: { adult: `2^${n} = ${Math.pow(2, n)} combinations.`, kids: `${Array(n).fill(2).join(" × ")} = ${Math.pow(2, n)}.` } };
          },
          (rng) => {
            const n = rng.int(2, 4, 1);
            return {
              q: { adult: `${n} switches in SERIES (AND). Of the ${Math.pow(2, n)} combinations, how many light the LED?`, kids: `All ${n} must be on (AND). How many of the ${Math.pow(2, n)} combos work?` },
              unit: "", answer: 1,
              hint: "AND needs every switch closed — only one combination.",
              solution: { adult: `Only all-on conducts: 1 of ${Math.pow(2, n)}.`, kids: "Only 'all on' — just 1." } };
          },
          (rng) => {
            const n = rng.int(2, 4, 1);
            return {
              q: { adult: `${n} switches in PARALLEL (OR). Of the ${Math.pow(2, n)} combinations, how many light the LED?`, kids: `Any one on works (OR). How many of the ${Math.pow(2, n)}?` },
              unit: "", answer: Math.pow(2, n) - 1,
              hint: "OR fails only when every switch is open.",
              solution: { adult: `It lights unless all are open: ${Math.pow(2, n) - 1} of ${Math.pow(2, n)}.`, kids: `Only 'all off' fails — ${Math.pow(2, n) - 1} work.` } };
          },
        ]} />

        <ChapterQuiz
          chapterN="L2-05"
          title={kids ? "Quick quiz!" : "Check your understanding."}
          intro={kids ? "Five questions about switches and logic." : "Switches & logic on the board. 70% to pass; retry freely."}
          questions={kids ? SW_QUIZ_KIDS : SW_QUIZ_ADULT}
          pick={5}
        />

        <WhatsNext
          currentN="L2-05"
          kids={kids}
          summary={kids
            ? <>You built real logic with switches — AND and OR! One Level 2 chapter left: letting electricity flip the switch by itself.</>
            : <>You built AND and OR by hand — the atoms of digital logic. The finale: replace the finger-flipped switch with a transistor, so electricity controls electricity.</>}
          prevHref="chapter-l2-rc.html"
          prevLabel="L2 · The Blink"
          nextHref="map.html"
          nextLabel="Back to course"
        />
      </main>

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

const SW_QUIZ_ADULT = [
  { q: "Two switches in series light the LED when…", kind: "concept", options: ["either is closed", "both are closed", "both are open", "never"], correct: 1, explain: "Series = AND. Both must be closed to complete the loop." },
  { q: "Two switches in parallel light the LED when…", kind: "concept", options: ["both are open", "either (or both) is closed", "both are closed only", "never"], correct: 1, explain: "Parallel = OR. Any closed switch completes the loop." },
  { q: "An open switch in a series path means the current is…", kind: "concept", options: ["maximum", "zero", "half", "reversed"], correct: 1, explain: "Open = broken loop = no current, regardless of the other components." },
  { q: "Series switches implement which logic gate?", kind: "concept", options: ["OR", "AND", "NOT", "XOR"], correct: 1, explain: "All inputs required → AND." },
  { q: "Why still include a resistor with switches and an LED?", kind: "concept", options: ["for decoration", "to limit current and protect the LED", "to slow the switch", "no reason"], correct: 1, explain: "The LED still needs current limiting whenever the path is closed." },
  { q: "AND, OR and NOT together can build…", kind: "concept", options: ["only lights", "any digital logic function", "nothing useful", "only switches"], correct: 1, explain: "They're functionally complete — the basis of all digital circuits." },
  {
    q: "Two buttons in SERIES light the LED when…",
    kind: "concept",
    options: ["either is pressed", "both are pressed — AND", "neither is pressed", "the battery is low"],
    correct: 1,
    explain: "Series switches = AND. The loop only closes if every switch closes.",
  },
  {
    q: "Two buttons in PARALLEL light the LED when…",
    kind: "concept",
    options: ["both are pressed only", "either one is pressed — OR", "neither is pressed", "they're pressed in order"],
    correct: 1,
    explain: "Parallel switches = OR. Any closed branch completes the loop.",
  },
  {
    q: "You wire the SAME two switches once in series and once in parallel. Same parts — why does the LED behave differently?",
    kind: "concept",
    options: ["It doesn't, wiring never matters", "Topology IS the logic — series demands both, parallel accepts either", "Parallel switches are secretly faster", "Series switches use less power always"],
    correct: 1,
    explain: "Nothing about the switches themselves changed — only how they're connected. That's the big idea of Chapter 5: logic lives in the WIRING, not the parts.",
  },
];
const SW_QUIZ_KIDS = [
  { q: "A switch that's CLOSED lets the flow…", kind: "concept", options: ["stop", "go through", "reverse", "get hot"], correct: 1, explain: "Closed = connected = flow goes through!" },
  { q: "Two switches in a row (series): the LED lights when…", kind: "concept", options: ["both are on", "either is on", "both are off", "never"], correct: 0, explain: "Both must be on — that's AND." },
  { q: "Two switches side-by-side (parallel): the LED lights when…", kind: "concept", options: ["both are off", "either one is on", "only both on", "never"], correct: 1, explain: "Either one will do — that's OR." },
  { q: "An OPEN switch in the only path means…", kind: "concept", options: ["bright LED", "no flow, LED off", "the LED pops", "nothing changes"], correct: 1, explain: "Open = gap = no flow = dark." },
  { q: "Switches let you build…", kind: "concept", options: ["rules / logic", "heat only", "water", "nothing"], correct: 0, explain: "Rules! AND and OR are the start of all computer logic." },
  {
    q: "Two buttons in a row: the light comes on when…",
    kind: "concept",
    options: ["you press BOTH", "you press either one", "you press neither", "you clap"],
    correct: 0,
    explain: "One road, two gates — both must open. That's an AND.",
  },
  {
    q: "Two buttons side by side: the light comes on when…",
    kind: "concept",
    options: ["you press both at once only", "you press EITHER one", "you unplug it", "never"],
    correct: 1,
    explain: "Two roads — either one works. That's an OR.",
  },
  {
    q: "A switch can be…",
    kind: "concept",
    options: ["on, off, or maybe", "only on or off", "any color of flow", "half pressed forever"],
    correct: 1,
    explain: "All or nothing — that yes/no is the seed of binary.",
  },
  {
    q: "Same two switches, wired two different ways, act like two different rules (AND vs OR). Why?",
    kind: "concept",
    options: ["The switches themselves change", "The WIRING is the rule — nothing about the switches changed", "It's random each time", "Only expensive switches do this"],
    correct: 1,
    explain: "The switches are identical both times — only the shape of the wiring changed. That shape IS the logic.",
  },
];

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