/* capstone-l2.jsx — Master Engineer Lv.2 applied final exam.
   Four breadboard BUILD challenges (not design briefs). Reuses
   BreadboardBuilder + the L2 sim engines. 3 of 4 passes → Lv.2 certificate. */

const { useState, useEffect } = React;

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

/* ── build challenges (reuse engines + tool sets from the L2 chapters) ──── */
const BUILD_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" },
];
const TWO_LED_TOOLS = (kids) => [
  { id: "battery", label: kids ? "Battery (9V)" : "Battery 9V", hint: "+ first, then −" },
  { id: "resistor", label: "Resistor 330Ω", hint: "either way" },
  { id: "led", label: kids ? "LED ×2" : "LED", hint: "+ long leg first" },
  { id: "wire", label: kids ? "Jumper" : "Jumper", hint: "connects holes" },
];
const SW_TOOLS = (kids) => [
  { id: "battery", label: kids ? "Battery (9V)" : "Battery 9V", hint: "+ first, then −" },
  { id: "resistor", label: "Resistor 330Ω", hint: "either way" },
  { id: "led", label: "LED", hint: "+ long leg first" },
  { id: "switch", label: kids ? "Switch ×2" : "Switch", hint: "tap on board to flip", part: { type: "switch" } },
  { id: "wire", label: kids ? "Jumper" : "Jumper", hint: "connects holes" },
];
const TX_TOOLS = (kids) => [
  { id: "battery", label: kids ? "Battery (9V)" : "Battery 9V", hint: "+ first, then −" },
  { id: "transistor", label: kids ? "Transistor" : "Transistor (NPN)", hint: "tap 3: Base, Collector, Emitter", legs: 3, part: { type: "transistor" } },
  { id: "resistor", label: "Resistor 330Ω", hint: "either way" },
  { id: "led", label: kids ? "LED (load)" : "LED load", hint: "+ long leg first" },
  { id: "switch", label: kids ? "Switch" : "Base switch", hint: "tap on board", part: { type: "switch" } },
  { id: "wire", label: kids ? "Jumper" : "Jumper", hint: "connects holes" },
];

// describe fns reused from chapters (re-declared minimally here)
function descSingle(r, kids) {
  if (r.state === "lit") return ["pass", kids ? "Lit and safe — nice!" : `Lit at ${(r.I||0).toFixed(0)} mA, within spec.`];
  if (r.state === "pop") return ["fail", kids ? "Pop! 💥 Add/raise the resistor." : "LED over-current — needs proper current limiting."];
  if (r.state === "short") return ["fail", kids ? "Short circuit!" : "Dead short — add a load."];
  if (r.state === "backwards") return ["warn", kids ? "LED is backwards." : "LED reversed."];
  return ["warn", kids ? "Finish the loop: + → resistor → LED → −." : "Incomplete — complete the current-limited loop."];
}
function descTwo(r, kids) {
  if (r.ledTotal < 2) return ["warn", kids ? "Light BOTH LEDs." : "Place and light two LEDs."];
  if (r.anyPop) return ["fail", kids ? "Pop! 💥 Each parallel LED needs its own resistor." : "An LED popped — parallel LEDs each need a resistor."];
  if (r.anyBack) return ["warn", kids ? "An LED is backwards." : "An LED is reversed."];
  if (r.litCount === 2) return ["pass", kids ? "Both glowing! 🎉" : "Both LEDs lit within spec."];
  return ["warn", kids ? "Keep going — get both lit." : "Not both lit yet."];
}
function descSwitch(r, kids) {
  if (r.state === "lit") return ["pass", kids ? "The switches let it through!" : `Lit through the closed switch path at ${(r.I||0).toFixed(0)} mA.`];
  if (r.state === "switch-open") return ["warn", kids ? "A switch is OFF — tap it on, then power on." : "A series switch is open. Close it (AND needs all closed)."];
  if (r.state === "pop") return ["fail", kids ? "Pop! 💥 Keep the resistor." : "Over-current — keep limiting."];
  if (r.state === "short") return ["fail", "Short circuit."];
  return ["warn", kids ? "Build the loop with a switch in it." : "Put a switch (with resistor + LED) in a complete loop."];
}
function descTx(r, kids) {
  if (r.state === "lit") return ["pass", kids ? "Tiny switch, big LED — transistor magic!" : `Load switched on via the transistor at ${(r.I||0).toFixed(0)} mA.`];
  if (r.state === "base-low") return ["warn", kids ? "Base switch OFF — tap it on, then power on." : "Base low — close the base switch."];
  if (r.state === "no-base") return ["warn", kids ? "Connect the switch to the Base leg." : "Base floating — drive it from + via the switch."];
  if (r.state === "no-load") return ["warn", kids ? "Wire the LED loop into the Collector." : "No collector load path."];
  if (r.state === "no-emitter") return ["warn", kids ? "Emitter must reach −." : "Emitter not grounded."];
  if (r.state === "no-tx") return ["warn", kids ? "Place the transistor." : "Place a transistor."];
  if (r.state === "pop") return ["fail", kids ? "Pop! 💥 Load needs a resistor." : "Load over-current."];
  return ["warn", kids ? "Keep wiring the driver." : "Incomplete driver."];
}
const RECT_TOOLS = (kids) => [
  { id: "battery", label: kids ? "Rough source" : "Source 9V", hint: "+ first, then −" },
  { id: "diode", label: kids ? "One-way valve" : "Diode", hint: "▷ anode first, then | cathode" },
  { id: "resistor", label: "Resistor 330Ω", hint: "either way" },
  { id: "led", label: "LED", hint: "+ long leg first" },
  { id: "capacitor", label: kids ? "Smoothing bucket" : "Cap (smoothing)", hint: "across the rail", part: { type: "capacitor", C: 3 } },
  { id: "wire", label: kids ? "Jumper" : "Jumper", hint: "connects holes" },
];
function descRect(r, kids) {
  if (r.state === "no-diode") return ["warn", kids ? "Add the one-way valve (diode)." : "No diode — add one to rectify."];
  if (r.state === "diode-backwards") return ["warn", kids ? "Flip the valve so ▷ faces away from +." : "Diode reversed: anode toward source +."];
  if (r.state === "diode-floating") return ["warn", kids ? "Put the valve right after +." : "Diode not in the feed — anode on the + rail."];
  if (r.state === "no-load") return ["warn", kids ? "Add the LED + resistor after the valve." : "No load after the diode."];
  if (r.state === "pop") return ["fail", kids ? "Pop! 💥 Keep the resistor." : "Over-current — keep the resistor."];
  if (r.state === "short") return ["fail", "Short circuit."];
  if (r.state === "lit") return r.smoothed
    ? ["pass", kids ? "Clean, steady power! 🎉" : `Rectified AND smoothed — a real DC supply (${(r.I||0).toFixed(0)} mA).`]
    : ["warn", kids ? "It lights but it's rough — add the smoothing bucket across the rail." : "Rectified but rough — add a cap across the rail to smooth."];
  return ["warn", kids ? "Source → valve → LED + resistor, plus the bucket." : "Build source → diode → load, with a smoothing cap."];
}

function CHALLENGES(kids) {
  return [
    { id: "led", title: kids ? "Light one LED, safely" : "Build a current-limited LED",
      brief: kids ? "Light a single LED without popping it. Battery → resistor → LED → back."
                  : "Light one LED safely on the board: battery → resistor → LED → return. No pop, healthy current.",
      sim: simulate, tools: BUILD_TOOLS(kids), limits: { battery:1, resistor:2, led:1, wire:6 }, describe: descSingle },
    { id: "two", title: kids ? "Light TWO LEDs" : "Two LEDs, your choice of topology",
      brief: kids ? "Get both LEDs glowing — series (one loop) or parallel (two branches, a resistor each)."
                  : "Light two LEDs. Series shares current; parallel needs a resistor per branch. Don't pop either.",
      sim: simulateMulti, tools: TWO_LED_TOOLS(kids), limits: { battery:1, resistor:3, led:2, wire:10 }, describe: descTwo },
    { id: "logic", title: kids ? "Switch-controlled LED" : "Gate an LED with switches",
      brief: kids ? "Put a switch in the loop. Power on, then tap the switch to turn the LED on."
                  : "Place a switch (or two) in the loop. Tap to close, then light the LED. Series = AND, parallel = OR.",
      sim: simulateLogic, tools: SW_TOOLS(kids), limits: { battery:1, resistor:2, led:1, switch:2, wire:10 }, describe: descSwitch },
    { id: "tx", title: kids ? "Transistor driver" : "Switch a load with a transistor",
      brief: kids ? "Use a tiny switch on the Base to turn on a big LED through the transistor."
                  : "Drive a load LED via an NPN transistor: load on the collector, emitter to −, base switched from +.",
      sim: simulateTransistor, tools: TX_TOOLS(kids), limits: { battery:1, transistor:1, resistor:2, led:1, switch:1, wire:12 }, describe: descTx },
    { id: "rect", title: kids ? "Make smooth power" : "Build a rectifier + smoother",
      brief: kids ? "Source → one-way valve → LED + resistor, plus a smoothing bucket across the rail. Make it clean and steady."
                  : "Build a smoothed DC supply: source → diode (anode to +) → LED + resistor load, with a capacitor across the rail. Pass = rectified AND smoothed.",
      sim: simulateRectifier, tools: RECT_TOOLS(kids), limits: { battery:1, diode:1, resistor:2, led:1, capacitor:1, wire:10 }, describe: descRect },
  ];
}

/* ── Certificate (Lv.2) ─────────────────────────────────────────────────── */
function Certificate({ score, total, onReplay }) {
  const date = new Date().toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric" });
  return (
    <div className="cert-wrap">
      <div className="cert" id="certificate">
        <div className="cert-border">
          <div className="cert-eyebrow">Fathohm</div>
          <div className="cert-title">Master Engineer</div>
          <div className="cert-level">· Level 2 · The Build ·</div>
          <div className="cert-body">
            This certifies that the bearer has not only learned the theory but
            <em> applied</em> it — building real circuits on a breadboard, from a
            current-limited LED to a transistor driver, and passing the Level 2
            applied exam.
          </div>
          <div className="cert-score">{score} / {total} builds passed</div>
          <div className="cert-row">
            <div>
              <div className="cert-line"></div>
              <div className="cert-cap">Awarded {date}</div>
            </div>
            <div className="cert-seal">
              <svg viewBox="0 0 80 80" width="72" height="72">
                <circle cx="40" cy="40" r="36" fill="none" stroke="var(--current)" strokeWidth="2" />
                <circle cx="40" cy="40" r="29" fill="none" stroke="var(--current)" strokeWidth="1" opacity="0.5" />
                <path d="M40 16 L44 34 L62 34 L48 45 L53 63 L40 52 L27 63 L32 45 L18 34 L36 34 Z"
                      fill="var(--current)" opacity="0.9" />
                <text x="40" y="74" fontFamily="IBM Plex Mono, monospace" fontSize="7"
                      fill="var(--ink-faint)" textAnchor="middle" letterSpacing="0.2em">LV.2</text>
              </svg>
            </div>
          </div>
        </div>
      </div>
      <div className="cert-actions">
        <button className="cta cta-secondary" onClick={onReplay}>Replay the exam</button>
        <button className="cta cta-primary" onClick={() => window.print()}>Print / save certificate</button>
        <a className="cta cta-secondary" href="index.html">Back to course</a>
      </div>
    </div>
  );
}

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 challenges = CHALLENGES(kids);
  const [started, setStarted] = useState(false);
  const [idx, setIdx] = useState(0);
  const [results, setResults] = useState({});
  const [done, setDone] = useState(false);
  const [runKey, setRunKey] = useState(0);

  const score = Object.values(results).filter(Boolean).length;
  const current = challenges[idx];

  useEffect(() => {
    if (done) {
      try {
        const cur = JSON.parse(localStorage.getItem("hte-progress") || "{}");
        cur["capstone-l2"] = score >= 3 ? "done" : "in-progress";
        localStorage.setItem("hte-progress", JSON.stringify(cur));
        window.dispatchEvent(new Event("hte-progress-changed"));
      } catch {}
    }
  }, [done]);

  // Record the best result per challenge (a pass sticks).
  const handleResult = (passed) => {
    setResults(prev => ({ ...prev, [current.id]: prev[current.id] || passed }));
  };
  const next = () => { if (idx < challenges.length - 1) setIdx(idx + 1); else setDone(true); };
  const replay = () => { setResults({}); setIdx(0); setDone(false); setStarted(true); setRunKey(k => k + 1); };
  const answered = results[current?.id] !== undefined;

  return (
    <>
      <ProgressBar />
      <TopBar currentN="capstone-l2" chapterLabel="Level 2 Capstone · Applied Exam"
              audience={t.audience}
              setAudience={(v) => setTweak("audience", v)} />

      <main className="capstone-main">
        {!started && !done && (
          <section className="capstone-intro">
            <div className="hero-grid"></div>
            <div className="capstone-intro-inner">
              <div className="eyebrow" style={{ marginTop: 28, color: "var(--current)" }}>The Level 2 Capstone</div>
              <h1 className="serif cap-h1">Build it<br/>for <em>real</em>.</h1>
              <p className="lede" style={{ marginTop: 20 }}>
                {kids
                  ? <>You learned the ideas AND built them on a breadboard. Now prove it: five builds, on a real board, no hints. Get 3 right to become a Level 2 Master Engineer!</>
                  : <>Level 1 tested theory. This tests <em>application</em>: five breadboard builds, judged by the same connectivity engine you've been using. Place real parts, power on, meet the spec. Three earns the Level 2 certificate.</>}
              </p>
              <div className="cap-brief-list">
                {challenges.map((c, i) => (
                  <div key={c.id} className="cap-brief-card">
                    <span className="cap-brief-n">{i + 1}</span>
                    <span className="cap-brief-t">{c.title}</span>
                    <span className="cap-brief-c">build</span>
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 32, display: "flex", gap: 12, flexWrap: "wrap" }}>
                <button className="cta cta-primary" onClick={() => setStarted(true)}>Begin the exam →</button>
                <a className="cta cta-secondary" href="chapter-l2-transistor.html">← Review L2 · The Driver</a>
              </div>
            </div>
          </section>
        )}

        {started && !done && (
          <section className="capstone-run">
            <div className="capstone-progress">
              {challenges.map((c, i) => (
                <div key={c.id}
                     className={`cap-dot ${i === idx ? "active" : ""} ${results[c.id] === true ? "pass" : results[c.id] === false ? "fail" : ""}`}>
                  {i + 1}
                </div>
              ))}
            </div>

            <div className="cap-build-head">
              <div className="eyebrow">Build {idx + 1} of {challenges.length}</div>
              <h2 className="serif" style={{ margin: "6px 0 8px" }}>{current.title}</h2>
              <p className="lede" style={{ maxWidth: "44em" }}>{current.brief}</p>
              {results[current.id] === true && (
                <div className="bb-verdict pass" style={{ marginTop: 14 }}>
                  <span className="v-icon">✓</span>
                  <span>{kids ? "Passed! Move on whenever you're ready." : "Build passed — advance when ready."}</span>
                </div>
              )}
            </div>

            <div key={`${current.id}-${runKey}`} style={{ marginTop: 18 }}>
              <BreadboardBuilder
                kids={kids}
                sim={current.sim}
                tools={current.tools}
                limits={current.limits}
                describe={current.describe}
                onResult={handleResult}
                goalAdult={current.brief}
                goalKids={current.brief}
              />
            </div>

            <div className="capstone-nav">
              <button className="cta cta-secondary"
                      onClick={() => idx > 0 && setIdx(idx - 1)}
                      disabled={idx === 0} style={{ opacity: idx === 0 ? 0.4 : 1 }}>
                ← Previous
              </button>
              <span className="cap-counter">{score} passed so far</span>
              <button className="cta cta-primary" onClick={next}
                      disabled={!answered} style={{ opacity: answered ? 1 : 0.4 }}>
                {idx < challenges.length - 1 ? "Next build →" : "Finish exam →"}
              </button>
            </div>
            <p className="note" style={{ textAlign: "center", marginTop: 10 }}>
              {kids ? "Tip: you can move on after any Power on — but you need 3 passes to earn the badge."
                    : "You may advance after any power-on attempt; a pass on a build is locked in even if you revisit it."}
            </p>
          </section>
        )}

        {done && (
          <section className="capstone-done">
            {score >= 3 ? (
              <>
                <div className="cap-done-head">
                  <div className="eyebrow" style={{ color: "var(--current)" }}>Applied exam complete</div>
                  <h1 className="serif cap-h1">You built it.</h1>
                  <p className="lede" style={{ marginTop: 12 }}>
                    {kids
                      ? <>You built real working circuits on the board. You're a Level 2 Master Engineer!</>
                      : <>You applied every Level 1 idea on a real breadboard, under real constraints. That's engineering. Welcome to Level 2.</>}
                  </p>
                </div>
                <Certificate score={score} total={challenges.length} onReplay={replay} />
              </>
            ) : (
              <div className="cap-done-head">
                <div className="eyebrow" style={{ color: "var(--current)" }}>Almost there</div>
                <h1 className="serif cap-h1">{score} / {challenges.length} built.</h1>
                <p className="lede" style={{ marginTop: 12 }}>
                  {kids
                    ? <>So close! You need 3 builds working to earn the badge. Give it another go.</>
                    : <>You need 3 passing builds to certify. Revisit the ones you missed — power on until the spec is met.</>}
                </p>
                <div style={{ marginTop: 24, display: "flex", gap: 12, flexWrap: "wrap" }}>
                  <button className="cta cta-primary" onClick={replay}>Try the exam again</button>
                  <a className="cta cta-secondary" href="index.html">Back to course</a>
                </div>
              </div>
            )}
          </section>
        )}
      </main>

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

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