/* capstone.jsx — Master Engineer Lv.1 final exam shell.
   Sequences the four design briefs, tracks results, issues a certificate. */

const { useState, useEffect, useRef } = React;

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

const ALL_BRIEFS = [
  { id: "led",   comp: BriefLED },
  { id: "div",   comp: BriefDivider },
  { id: "rc",    comp: BriefRC },
  { id: "tx",    comp: BriefTransistor },
  { id: "diode", comp: BriefDiode },
  { id: "ind",   comp: BriefInductor },
];
function drawBriefs() {
  // Always include the LED (anchor), then 3 random others → 4 total, shuffled.
  const rest = ALL_BRIEFS.slice(1).sort(() => Math.random() - 0.5).slice(0, 3);
  return [ALL_BRIEFS[0], ...rest].sort(() => Math.random() - 0.5);
}

/* ─── Certificate ───────────────────────────────────────────────────────── */
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 1 ·</div>
          <div className="cert-body">
            This certifies that the bearer has completed the field guide —
            from a barrel of water to a working transistor — and passed the
            capstone design exam by building real circuits to spec.
          </div>
          <div className="cert-score">{score} / {total} briefs 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.1</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>
  );
}

/* ─── App ───────────────────────────────────────────────────────────────── */
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 [started, setStarted] = useState(false);
  const [briefs, setBriefs] = useState(() => drawBriefs());
  const [idx, setIdx] = useState(0);
  const BRIEFS = briefs;
  const [results, setResults] = useState({});   // { briefId: bool }
  const [done, setDone] = useState(false);
  const [runKey, setRunKey] = useState(0);       // bump to remount briefs fresh

  const score = Object.values(results).filter(Boolean).length;

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

  const current = BRIEFS[idx];

  const handleResult = (passed) => {
    setResults(prev => ({ ...prev, [current.id]: passed }));
  };

  const next = () => {
    if (idx < BRIEFS.length - 1) setIdx(idx + 1);
    else setDone(true);
  };

  const replay = () => {
    setResults({});
    setBriefs(drawBriefs());
    setIdx(0);
    setDone(false);
    setStarted(true);
    setRunKey(k => k + 1);
  };

  const answeredCurrent = results[current?.id] !== undefined;

  return (
    <>
      <ProgressBar />
      <TopBar currentN="capstone" chapterLabel="Capstone · Final 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">
              <ChapterStrip currentN="" />
              <div className="eyebrow" style={{ marginTop: 28, color: "var(--current)" }}>The Capstone</div>
              <h1 className="serif cap-h1">Design something<br/>that <em>works</em>.</h1>
              <p className="lede" style={{ marginTop: 20 }}>
                {kids
                  ? <>You've learned all the ideas. Now put them together! Four challenges, drawn fresh each time — pick the parts, and the circuit tells you if it works. Pop an LED if you're not careful.</>
                  : <>Nine chapters of theory come down to this: can you build a circuit that meets a spec? Four briefs drawn from a larger pool, real component values, real consequences. Three of four earns your certificate — and the set reshuffles each attempt.</>}
              </p>
              <div className="cap-brief-list">
                {[
                  { n: "?", t: kids ? "Light an LED safely" : "LED current-limiting", c: "Ch 1 · 3" },
                  { n: "?", t: kids ? "Split the voltage" : "Voltage divider", c: "Ch 2" },
                  { n: "?", t: kids ? "Afterglow timer" : "RC timing", c: "Ch 4" },
                  { n: "?", t: kids ? "Control a big motor" : "Transistor switch", c: "Ch 5 · 6" },
                  { n: "?", t: kids ? "Block the backflow" : "Diode one-way", c: "Ch 7" },
                  { n: "?", t: kids ? "Steady the flow" : "Inductor smoothing", c: "Ch 9" },
                ].map((b, i) => (
                  <div key={i} className="cap-brief-card">
                    <span className="cap-brief-n">{b.n}</span>
                    <span className="cap-brief-t">{b.t}</span>
                    <span className="cap-brief-c">{b.c}</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="chapter6.html">← Review Chapter 6</a>
              </div>
            </div>
          </section>
        )}

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

            <div key={`${current.id}-${runKey}`}>
              {React.createElement(current.comp, { kids, onResult: handleResult })}
            </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">Brief {idx + 1} of {BRIEFS.length}</span>
              <button className="cta cta-primary"
                      onClick={next}
                      disabled={!answeredCurrent}
                      style={{ opacity: answeredCurrent ? 1 : 0.4 }}>
                {idx < BRIEFS.length - 1 ? "Next brief →" : "Finish exam →"}
              </button>
            </div>
          </section>
        )}

        {done && (
          <section className="capstone-done">
            {score >= 3 ? (
              <>
                <div className="cap-done-head">
                  <div className="eyebrow" style={{ color: "var(--current)" }}>Exam complete</div>
                  <h1 className="serif cap-h1">You passed.</h1>
                  <p className="lede" style={{ marginTop: 12 }}>
                    {kids
                      ? <>You built real circuits that work. You're officially a Level 1 Master Engineer!</>
                      : <>You designed working circuits to spec under real constraints. That's the whole job. Welcome to Level 1.</>}
                  </p>
                </div>
                <Certificate score={score} total={BRIEFS.length} onReplay={replay} />
              </>
            ) : (
              <div className="cap-done-head">
                <div className="eyebrow" style={{ color: "var(--current)" }}>Almost there</div>
                <h1 className="serif cap-h1">{score} / {BRIEFS.length} passed.</h1>
                <p className="lede" style={{ marginTop: 12 }}>
                  {kids
                    ? <>So close! You need 3 to earn your certificate. Give it another go — the numbers change each time.</>
                    : <>You need 3 of 4 to certify. Revisit the briefs you missed — the parameters reshuffle on replay, so it's fresh practice, not memorization.</>}
                </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 />);
