/* chapter-l2-rc.jsx — Level 2 · Chapter 4: The Blink (RC delay).
   Applies Chapter 4: place a capacitor across the LED so it turns on
   after a delay τ = R·C. */

const { useState, useEffect, useRef } = React;

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

const RC_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: "wire", label: kids ? "Jumper wire" : "Jumper", hint: "connects two holes" },
  { id: "capSmall", label: kids ? "Small bucket" : "Cap · small", hint: "across the LED for a short delay", part: { type: "capacitor", C: 1 } },
  { id: "capBig", label: kids ? "Big bucket" : "Cap · big", hint: "across the LED for a long delay", part: { type: "capacitor", C: 4 } },
];
const RC_LIMITS = { battery: 1, resistor: 2, led: 1, wire: 8, capSmall: 1, capBig: 1 };

function describeRC(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 — + through a resistor and LED back to −." : "Open circuit. Complete the 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 "pop": return ["fail", kids ? "Pop! 💥 Too much flow — you still need a resistor to limit it." : `LED over-current (${(r.I||0).toFixed(0)} mA). Keep the series resistor.`];
    case "lit-nodelay": return ["warn", kids
      ? "It lights — but instantly! To get a delay, put the bucket (capacitor) ACROSS the LED's two ends."
      : "Lit, but with no delay. For an RC turn-on, the capacitor must sit in parallel with the LED (across its two nodes) so it charges through the resistor first."];
    case "lit":
      return ["pass", kids
        ? `Watch it — the LED fades in after about ${r.delay.toFixed(1)} seconds! The bucket fills, then the LED glows. That's RC timing.`
        : `RC delay working: the cap charges through R, and the LED ramps on over ~${r.delay.toFixed(1)} s (τ = R·C). Bigger R or C → longer delay.`];
    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 trick" : "RC delay" },
    { 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-04" />
      <ProgressBar />
      <TopBar currentN="L2-04" chapterLabel="Level 2 · The Blink"
              audience={t.audience}
              setAudience={(v) => setTweak("audience", v)} />
      <ChapterNav items={navItems} />

      <main>
        <section className="cover-page" id="cover" data-screen-label="L2-04 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 4</span>
            </div>
            <h1 className="serif cover-title">The <em>Delay</em>.</h1>
            <div className="eyebrow" style={{ marginTop: 36, marginBottom: 16, color: "var(--current)" }}>
              Applying Chapter 4 · Capacitors & Time
            </div>
            <div className="cover-lede">
              {kids
                ? <>Add a bucket (a capacitor) to your circuit and something new happens: the LED waits, then fades in. You've added <em>time</em> to your circuit.</>
                : <>So far everything happened instantly. Add a capacitor and the circuit gains a sense of <em>time</em> — the LED ramps on after a delay set by τ = R·C. Your first timed circuit.</>}
            </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 4</div>
          <div className="section-inner">
            <h2 className="serif">{kids ? "Buckets fill over time." : "A capacitor fills over time."}</h2>
            <p className="lede" style={{ maxWidth: "42em" }}>
              {kids
                ? <>A capacitor is a tiny bucket for electricity. Water (charge) flows in through the pipe (resistor) and slowly fills it. The bigger the bucket or the tighter the pipe, the longer it takes.</>
                : <>A capacitor charges toward the supply voltage through whatever resistance feeds it, on an exponential curve. The time constant τ = R·C sets the pace: after one τ it's ~63% charged.</>}
            </p>
            <div className="card" style={{ background: "transparent", padding: "20px 22px", marginTop: 18, maxWidth: 560 }}>
              <div className="eyebrow" style={{ marginBottom: 10 }}>{kids ? "fill time" : "time constant"}</div>
              <div className="eq" style={{ fontSize: 30 }}>
                <span style={{ fontStyle: "italic" }}>τ</span>
                <span className="op">=</span>
                <span className="R">R</span>
                <span className="op">·</span>
                <span style={{ color: "var(--water)" }}>C</span>
              </div>
              <div className="marg" style={{ marginTop: 8 }}>
                {kids ? <>Bigger pipe-squeeze (R) or bigger bucket (C) → longer wait.</>
                      : <>Bigger R or bigger C → longer delay. Same idea you scrubbed through in Level 1.</>}
              </div>
            </div>
          </div>
        </section>

        <section className="section" id="how" data-screen-label="The trick"
                 style={{ background: "var(--bg-deeper)" }}>
          <div className="marker">§ 02 · the wiring trick</div>
          <div className="section-inner">
            <h2 className="serif">{kids ? "Put the bucket across the LED." : "Capacitor in parallel with the LED."}</h2>
            <p className="lede" style={{ maxWidth: "42em" }}>
              {kids
                ? <>Here's the trick: connect the bucket (capacitor) across the LED's two ends. When you power on, the water fills the bucket <em>first</em> — so the LED waits, then glows.</>
                : <>Wire the capacitor in parallel with the LED. On power-up, current diverts into charging the cap, holding the LED's voltage low; as the cap fills, voltage rises and the LED ramps on. The resistor in series sets how fast.</>}
            </p>
            <div className="card" style={{ background: "transparent", padding: "18px 20px", marginTop: 16, maxWidth: 560 }}>
              <div className="eyebrow" style={{ marginBottom: 8 }}>{kids ? "remember" : "placement matters"}</div>
              <p style={{ margin: 0, fontSize: 16, color: "var(--ink-soft)" }}>
                {kids
                  ? <>The bucket's two legs must touch the SAME two columns as the LED's two legs. Otherwise it lights instantly with no wait.</>
                  : <>The cap must share both of the LED's nodes. Place it elsewhere and the circuit still lights — just with no delay. The builder will tell you.</>}
              </p>
            </div>
          </div>
        </section>

        <section className="section" id="build" data-screen-label="Build it">
          <div className="marker">§ 03 · your turn · make it fade in</div>
          <div className="section-inner" style={{ maxWidth: 1180 }}>
            <h2 className="serif" style={{ marginBottom: 10 }}>{kids ? "Make the LED wait." : "Build the delayed LED."}</h2>
            <p className="lede" style={{ marginBottom: 24, maxWidth: "42em" }}>
              {kids
                ? <>Build the LED loop, then add a bucket across the LED. Power on and watch it fade in! Try the small bucket vs the big one — which waits longer?</>
                : <>Build the LED loop with current limiting, then add a capacitor across the LED. Power on to watch the timed ramp. Swap the small cap for the big one to lengthen τ.</>}
            </p>
            <DesignGate kids={kids} chapterN="L2-04"
              spec={{ adult: "Your loop uses a 330 Ω resistor and a 470 µF capacitor across the LED.", kids: "You'll use a 330 Ω pipe and a 470 µF bucket." }}
              prompt={{ adult: "Before you build it: how long is the turn-on delay (one time constant)?", kids: "How long until the LED fades in? (one fill-time)" }}
              formula={{ adult: "\u03c4 = R × C = 330 Ω × 470 µF", kids: "time = pipe × bucket" }}
              unit="s" answer={0.155} tol={0.12}
              hint={{ adult: "470 µF = 0.00047 F. Multiply by 330 Ω.", kids: "330 × 0.00047 ≈ 0.15." }}
              solution={{ adult: "\u03c4 = 330 × 0.00047 = 0.155 s — the LED reaches ~63% after that.", kids: "330 × 0.00047 ≈ 0.15 seconds." }}>
              <BreadboardBuilder
                kids={kids}
                sim={simulateRC}
                tools={RC_TOOLS(kids)}
                limits={RC_LIMITS}
                describe={describeRC}
                goalAdult="Make the LED ramp on after a delay: battery → resistor → LED loop, with a capacitor in parallel with the LED. Bigger cap = longer delay."
                goalKids="Make the LED fade in slowly! Build the loop, then put a bucket (capacitor) across the LED. Power on and watch it wait, then glow."
              />
            </DesignGate>
          </div>
        </section>

        <PracticeProblems chapterN="L2-04" kids={kids}
          intro={kids ? "Timing puzzles for your delay circuit." : "RC timing design math. Enter a number and check it."}
          problems={[
          (rng) => {
            const r = rng.pick([220, 330, 470, 680]), uf = rng.pick([100, 220, 470]);
            const tau = +(r * uf * 1e-6).toFixed(3);
            return {
              q: { adult: `A ${r} \u03a9 resistor charges a ${uf} \u00b5F capacitor. What is the time constant \u03c4? (Answer in seconds.)`, kids: `A ${r} \u03a9 pipe fills a ${uf} \u00b5F bucket. How long is one fill-time? (seconds)` },
              unit: "s", answer: tau, tol: 0.08,
              hint: `\u03c4 = R × C; ${uf} \u00b5F = ${+(uf * 1e-6).toPrecision(6)} F.`,
              solution: { adult: `\u03c4 = ${r} × ${+(uf * 1e-6).toPrecision(6)} = ${tau} s.`, kids: `${r} × ${+(uf * 1e-6).toPrecision(6)} ≈ ${tau}.` } };
          },
          (rng) => {
            const sec = rng.pick([0.5, 1, 1.5, 2]), uf = rng.pick([220, 470, 1000]);
            const k = +(sec / (uf * 1e-6) / 1000).toFixed(2);
            return {
              q: { adult: `You want a ${sec} s delay using a ${uf} \u00b5F cap. What resistor do you need? (Answer in k\u03a9.)`, kids: `You want a ${sec}-second wait with a ${uf} \u00b5F bucket. What pipe-size (kilo-ohms)?` },
              unit: "k\u03a9", answer: k, tol: 0.08,
              hint: `R = \u03c4 ÷ C = ${sec} ÷ ${+(uf * 1e-6).toPrecision(6)}, then ÷1000 for k\u03a9.`,
              solution: { adult: `R = ${sec} ÷ ${+(uf * 1e-6).toPrecision(6)} = ${Math.round(sec / (uf * 1e-6))} \u03a9 ≈ ${k} k\u03a9.`, kids: `${sec} ÷ ${+(uf * 1e-6).toPrecision(6)} ≈ ${k} k\u03a9.` } };
          },
          (rng) => {
            const n = rng.pick([1, 2, 3]);
            const pctMap = { 1: 63, 2: 86, 3: 95 };
            return {
              q: { adult: `After ${n === 1 ? "one full time constant" : n + " time constants"}, what percent of the supply voltage has the capacitor reached?`, kids: `After ${n} fill-time${n > 1 ? "s" : ""}, about how full is the bucket (percent)?` },
              unit: "%", answer: pctMap[n], tol: 0.12,
              hint: "Each \u03c4 closes ~63% of the remaining gap: 63%, 86%, 95%…",
              solution: { adult: `~${pctMap[n]}% after ${n} \u03c4.`, kids: `About ${pctMap[n]}% full.` } };
          },
        ]} />

        <ChapterQuiz
          chapterN="L2-04"
          title={kids ? "Quick quiz!" : "Check your understanding."}
          intro={kids ? "Five questions about timing with capacitors." : "RC timing on the board. 70% to pass; retry freely."}
          questions={kids ? RC_QUIZ_KIDS : RC_QUIZ_ADULT}
          pick={5}
        />

        <WhatsNext
          currentN="L2-04"
          kids={kids}
          summary={kids
            ? <>Your circuit can wait now — that's how timers and blinkers work! Next in Level 2: buttons you press, and logic.</>
            : <>You built a timed circuit — the basis of every blinker, debounce, and oscillator. Next: bring in the switch and combine inputs with logic.</>}
          prevHref="chapter-l2-power.html"
          prevLabel="L2 · Sizing It Up"
          nextHref="map.html"
          nextLabel="Back to course"
        />
      </main>

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

const RC_QUIZ_ADULT = [
  { q: "The RC time constant τ equals…", kind: "concept", options: ["R + C", "R · C", "R / C", "C / R"], correct: 1, explain: "τ = R·C. After one τ the capacitor reaches ~63% of the supply." },
  { q: "To make the LED's turn-on delay LONGER, you could…", kind: "math", options: ["use a smaller capacitor", "use a bigger capacitor or bigger resistor", "remove the resistor", "add more battery"], correct: 1, explain: "Delay scales with R·C — increase either to wait longer." },
  { q: "For a visible turn-on delay, the capacitor must be placed…", kind: "concept", options: ["anywhere on the board", "in parallel with the LED", "in series with the battery only", "on the power rail alone"], correct: 1, explain: "Across the LED's nodes — it charges through R and holds the LED off until it fills." },
  { q: "After about 5 time constants, the capacitor is…", kind: "math", options: ["barely charged", "~63% charged", "essentially fully charged", "discharging"], correct: 2, explain: "5τ ≈ >99% charged — effectively done." },
  { q: "Capacitors store energy as…", kind: "concept", options: ["heat", "charge / an electric field", "light", "motion"], correct: 1, explain: "A capacitor stores charge across its plates — an electric field. No heat like a resistor." },
  { q: "You keep the resistor but double the capacitor. The delay…", kind: "math", options: ["halves", "stays the same", "doubles", "disappears"], correct: 2, explain: "τ = RC, so doubling C doubles the delay." },
  {
    q: "τ = R·C with R = 100 kΩ and C = 10 µF gives…",
    kind: "math",
    options: ["0.1 s", "1 s", "10 s", "100 s"],
    correct: 1,
    explain: "100 000 × 0.00001 = 1 second. After one τ the cap is ~63% charged.",
  },
  {
    q: "To make the LED fade in more SLOWLY, you could…",
    kind: "math",
    options: ["shrink the capacitor", "use a bigger capacitor or bigger resistor", "remove the resistor", "add a second battery"],
    correct: 1,
    explain: "τ = R·C — grow either one and the fill takes longer.",
  },
  {
    q: "You disconnect the battery entirely, but the charged capacitor is still wired across the LED. What happens?",
    kind: "concept",
    options: ["Nothing — LEDs need a battery", "The LED briefly glows anyway, powered by the capacitor's stored charge", "The capacitor resets to zero instantly", "The LED lights up brighter than before"],
    correct: 1,
    explain: "A charged capacitor is a tiny reservoir of its own — it will drive the LED for a moment as it discharges through it, exactly like the camera-flash idea from Chapter 4.",
  },
];
const RC_QUIZ_KIDS = [
  { q: "A capacitor is like a…", kind: "concept", options: ["pipe", "bucket for electricity", "switch", "battery"], correct: 1, explain: "A bucket! It fills up with charge over time." },
  { q: "A BIGGER bucket takes…", kind: "concept", options: ["less time to fill", "more time to fill", "no time", "negative time"], correct: 1, explain: "More room = longer to fill = longer delay." },
  { q: "To make the LED wait before glowing, put the bucket…", kind: "concept", options: ["in your pocket", "across the LED", "in the trash", "on the battery only"], correct: 1, explain: "Across the LED, so it fills first and the LED waits." },
  { q: "While the bucket is filling, the LED is…", kind: "concept", options: ["bright", "waiting / dim", "broken", "backwards"], correct: 1, explain: "It waits until the bucket fills enough, then fades in." },
  { q: "This kind of waiting circuit is how we make…", kind: "concept", options: ["toast", "timers and blinkers", "ice", "music only"], correct: 1, explain: "Timers, blinkers, and delays all use this RC trick!" },
  {
    q: "A bigger bucket on the light makes it turn on…",
    kind: "concept",
    options: ["quicker", "more slowly and gently", "backwards", "never"],
    correct: 1,
    explain: "The bucket has to fill first — bigger bucket, longer fill, softer glow-up.",
  },
  {
    q: "After you cut the power, the bucket…",
    kind: "concept",
    options: ["keeps the light going a moment", "explodes", "fills up", "does nothing"],
    correct: 0,
    explain: "The stored water pours back out — the light fades instead of snapping off.",
  },
  {
    q: "The fill time of the bucket depends on…",
    kind: "concept",
    options: ["the pipe AND the bucket size", "the color of the wire", "the time of day", "how new the battery is"],
    correct: 0,
    explain: "Tight pipe or big bucket = slow fill. That's τ = R × C.",
  },
  {
    q: "You unplug the battery, but the full bucket is still connected to the light. What happens?",
    kind: "concept",
    options: ["Nothing happens at all", "The light glows for a moment anyway, fed by the bucket's stored water", "The bucket instantly empties with no light", "The light gets brighter than ever"],
    correct: 1,
    explain: "A full bucket can feed the light all on its own for a little while, even with the battery gone — just like a camera flash!",
  },
];

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