/* explorer.jsx — The Explorer Route: a complete, finishable arc for younger
   learners (and anyone who wants the ideas before the math). It does NOT fork
   the course — every stop is a normal page in Explorer reading mode. The route
   runs Story → Primer → Chapters 1–5 → the matching builds → a checkpoint quiz
   → an Explorer certificate. After that, the trail continues into Ch6+ with a
   signpost to the Math for Builders stream. Names exr*. */

const { useState: exrUseState, useEffect: exrUseEffect, useMemo: exrUseMemo } = React;

/* ─── checkpoint bank — kid-level, covers ch1–5 + the story ─────────────── */
const EXR_BANK = [
  { q: "In the water picture, VOLTAGE is…", opts: ["the push (how hard the pump squeezes)", "the pipe itself", "the colour of the water"], a: 0, why: "Voltage is the push — pressure from the battery-pump." },
  { q: "CURRENT is…", opts: ["how much charge flows past each second", "how hot the wire is", "the length of the wire"], a: 0, why: "Current counts the flow — charge passing by per second." },
  { q: "A RESISTOR is like…", opts: ["a pinch in the hose", "a bigger pump", "a bucket"], a: 0, why: "Pinch the hose and less water flows. Resistance fights flow." },
  { q: "If the loop is broken anywhere, what flows?", opts: ["nothing at all", "half as much", "only the fast charges"], a: 0, why: "Charge needs a complete round trip — one gap stops everything." },
  { q: "Make the resistor BIGGER and the flow…", opts: ["gets smaller", "gets bigger", "stays the same"], a: 0, why: "More pinch, less flow — that's Ohm's rule in words." },
  { q: "Turn the battery UP and the flow…", opts: ["gets bigger", "gets smaller", "turns around"], a: 0, why: "More push, more flow." },
  { q: "Two resistors in a row (series) — the current through them is…", opts: ["the same through both", "bigger in the first one", "zero in the second one"], a: 0, why: "One path = one flow. The same charges pass through both." },
  { q: "Two resistors side by side (parallel) — the charges…", opts: ["split up, more taking the easy path", "all take the hard path", "stop and wait"], a: 0, why: "Parallel paths share the flow; the easier path gets more." },
  { q: "A resistor doing lots of work gets…", opts: ["warm", "colder", "heavier"], a: 0, why: "Pushing charge through a pinch makes heat — that's power." },
  { q: "A capacitor is like…", opts: ["a bucket that stores charge", "a one-way door", "a faster pump"], a: 0, why: "It fills up, holds charge, and can pour it back out later." },
  { q: "A bigger bucket (capacitor) fills…", opts: ["slower", "faster", "at the same speed"], a: 0, why: "More room to fill = more time — that's the RC idea." },
  { q: "An open switch…", opts: ["breaks the path so nothing flows", "makes the flow faster", "stores the charge"], a: 0, why: "Open = a gap in the loop. Closed = path complete." },
  { q: "Two switches in a ROW both have to be on. That's…", opts: ["AND", "OR", "NOT"], a: 0, why: "In a row = AND: both gates must be open." },
  { q: "Two switches SIDE BY SIDE — either one works. That's…", opts: ["OR", "AND", "NEITHER"], a: 0, why: "Side by side = OR: either path completes the loop." },
  { q: "An LED lets charge through…", opts: ["one way only", "both ways", "only when it's dark"], a: 0, why: "It's a one-way light — backwards, it blocks." },
  { q: "A schematic is…", opts: ["a clean drawing of a real circuit", "a photo of a breadboard", "a kind of battery"], a: 0, why: "The drawing and the board are the same circuit, two ways." },
];

function exrShuffle(arr) {
  const a = arr.slice();
  for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; }
  return a;
}

/* ─── the checkpoint quiz ────────────────────────────────────────────────── */
const EXR_PICK = 8, EXR_PASS = 6;

function ExrQuiz({ onPass, kids }) {
  const [seed, setSeed] = exrUseState(0);
  const qs = exrUseMemo(() => exrShuffle(EXR_BANK).slice(0, EXR_PICK).map(q => {
    const order = exrShuffle(q.opts.map((_, i) => i));
    return { ...q, order, aAt: order.indexOf(q.a) };
  }), [seed]);
  const [answers, setAnswers] = exrUseState({});   // qIdx -> chosen opt position
  const answered = Object.keys(answers).length;
  const score = qs.reduce((s, q, i) => s + (answers[i] === q.aAt ? 1 : 0), 0);
  const done = answered === qs.length;
  const passed = done && score >= EXR_PASS;

  exrUseEffect(() => { if (passed) onPass(); }, [passed]);

  return (
    <div>
      {qs.map((q, i) => {
        const chosen = answers[i];
        return (
          <div key={seed + "-" + i} style={{ background: "var(--bg-card)", border: "1px solid var(--rule)", borderRadius: 12, padding: "16px 20px", marginBottom: 12 }}>
            <div style={{ display: "flex", gap: 10, alignItems: "baseline", marginBottom: 10 }}>
              <span style={{ fontFamily: "IBM Plex Mono, monospace", fontSize: 12.5, color: "var(--current)", fontWeight: 600 }}>{String(i + 1).padStart(2, "0")}</span>
              <span style={{ fontSize: 15.5, color: "var(--ink)", fontWeight: 500 }}>{q.q}</span>
            </div>
            <div style={{ display: "grid", gap: 7 }}>
              {q.order.map((optIdx, pos) => {
                const isChosen = chosen === pos, isRight = pos === q.aAt;
                let border = "var(--rule)", bg = "transparent";
                if (chosen != null && isChosen) { border = isRight ? "#1fc463" : "#d23f34"; bg = isRight ? "rgba(31,196,99,0.08)" : "rgba(210,63,52,0.08)"; }
                if (chosen != null && !isChosen && isRight) border = "#1fc463";
                return (
                  <button key={pos} disabled={chosen != null} onClick={() => setAnswers(prev => ({ ...prev, [i]: pos }))}
                          style={{ textAlign: "left", cursor: chosen == null ? "pointer" : "default", fontSize: 14, color: "var(--ink-soft)",
                                   fontFamily: "Geist, system-ui, sans-serif", padding: "9px 13px", borderRadius: 8, background: bg,
                                   border: `1.5px solid ${border}` }}>
                    {q.opts[optIdx]}
                  </button>
                );
              })}
            </div>
            {chosen != null && (
              <div style={{ marginTop: 9, fontSize: 13, color: chosen === q.aAt ? "#1f8a4c" : "var(--ink-soft)" }}>
                {chosen === q.aAt ? "✓ " : "✗ "}{q.why}
              </div>
            )}
          </div>
        );
      })}
      {done && (
        <div style={{ background: "var(--bg-card)", border: `1.5px solid ${passed ? "#1fc463" : "var(--rule-strong)"}`, borderRadius: 12, padding: "18px 22px", display: "flex", gap: 16, alignItems: "center", flexWrap: "wrap" }}>
          <span style={{ fontFamily: "IBM Plex Mono, monospace", fontSize: 20, fontWeight: 600, color: passed ? "#1f8a4c" : "var(--ink)" }}>{score} / {qs.length}</span>
          <span style={{ fontSize: 14.5, color: "var(--ink-soft)", flex: 1, minWidth: 200 }}>
            {passed ? "You passed the Explorer Checkpoint! Your certificate is below." : `You need ${EXR_PASS} to pass — the questions reshuffle every try.`}
          </span>
          {!passed && (
            <button className="cta cta-secondary" onClick={() => { setAnswers({}); setSeed(s => s + 1); }}>Try again</button>
          )}
        </div>
      )}
    </div>
  );
}

/* ─── the certificate (capstone.css classes) ─────────────────────────────── */
function ExrCertificate({ date }) {
  return (
    <div className="cert-wrap">
      <div className="cert" id="certificate">
        <div className="cert-border">
          <div className="cert-eyebrow">Fathohm</div>
          <div className="cert-title">Explorer Engineer</div>
          <div className="cert-level">· The Explorer Route ·</div>
          <div className="cert-body">
            This certifies that the bearer has walked the Explorer Route —
            the story, the ideas of push, flow, pinch, buckets and switches,
            real circuits built and working — and passed the Explorer Checkpoint.
          </div>
          <div className="cert-score">Checkpoint 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" strokeDasharray="3 4" />
                <text x="40" y="49" textAnchor="middle" fontFamily="Newsreader, serif" fontSize="26" fill="var(--current)">Ω</text>
              </svg>
            </div>
          </div>
        </div>
      </div>
      <div className="cert-actions">
        <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>
  );
}

/* ─── route step list ────────────────────────────────────────────────────── */
function ExrStep({ num, title, note, items, progress }) {
  return (
    <div style={{ display: "flex", gap: 18, marginBottom: 26 }}>
      <div style={{ flex: "0 0 34px", display: "flex", flexDirection: "column", alignItems: "center" }}>
        <span style={{ width: 34, height: 34, borderRadius: "50%", border: "2px solid var(--current)", display: "flex", alignItems: "center", justifyContent: "center",
                       fontFamily: "IBM Plex Mono, monospace", fontSize: 14, fontWeight: 600, color: "var(--current)", background: "var(--bg-card)" }}>{num}</span>
        <span style={{ flex: 1, width: 2, background: "var(--rule)", marginTop: 6 }}></span>
      </div>
      <div style={{ flex: 1, paddingBottom: 4 }}>
        <h3 style={{ fontFamily: "Newsreader, serif", fontWeight: 500, fontSize: 21, margin: "4px 0 4px" }}>{title}</h3>
        {note && <p style={{ fontSize: 14, color: "var(--ink-soft)", margin: "0 0 12px", maxWidth: "40em", lineHeight: 1.5 }}>{note}</p>}
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          {items.map(it => {
            const st = progress[it.n];
            return (
              <a key={it.href} href={it.href}
                 style={{ display: "flex", alignItems: "center", gap: 8, textDecoration: "none", fontFamily: "IBM Plex Mono, monospace", fontSize: 12.5,
                          padding: "8px 13px", borderRadius: 8, border: `1.5px solid ${st === "done" ? "#1fc463" : "var(--rule-strong)"}`,
                          color: st === "done" ? "#1f8a4c" : "var(--ink-soft)", background: st === "done" ? "rgba(31,196,99,0.07)" : "var(--bg-card)" }}>
                {st === "done" ? "✓" : st === "in-progress" ? "…" : "○"} {it.t}
              </a>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function ExplorerRoute() {
  const [t, setTweak] = window.useTweaks({ audience: "kids", theme: "paper" });
  window.useCrossChapterPersistence(t, setTweak);
  exrUseEffect(() => { document.body.setAttribute("data-theme", t.theme); }, [t.theme]);
  const kids = t.audience === "kids";
  const progress = window.useProgressState();

  const [cert, setCert] = exrUseState(() => {
    try { return JSON.parse(localStorage.getItem("hte-explorer") || "null"); } catch { return null; }
  });
  const onPass = () => {
    if (cert && cert.passed) return;
    const c = { passed: true, date: new Date().toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric" }) };
    try { localStorage.setItem("hte-explorer", JSON.stringify(c)); } catch {}
    setCert(c);
  };

  const L0 = window.L0_CHAPTERS.filter(c => c.ready !== false);
  const primer = [{ n: "L0-00", t: "Before You Start", href: "primer.html" }];
  const theory = window.ALL_CHAPTERS.slice(0, 5);
  const builds = window.L2_CHAPTERS.filter(c => c.ready !== false && (c.n === "L2-00" || (c.applies && parseInt(c.applies, 10) <= 5)));
  const tools = [{ n: "_lab", t: "Circuit Lab", href: "circuit-lab.html" }, { n: "_wb", t: "The Workbench", href: "sandbox.html" }];

  return (
    <>
      <window.ProgressBar />
      <window.TopBar chapterLabel="The Explorer Route" audience={t.audience} setAudience={(v) => setTweak("audience", v)} />
      <main style={{ maxWidth: 880, margin: "0 auto", padding: "34px 26px 80px" }}>
        <div className="eyebrow" style={{ marginBottom: 8 }}>a complete trail · no heavy math</div>
        <h1 style={{ fontFamily: "Newsreader, serif", fontWeight: 500, fontSize: 38, margin: "0 0 10px" }}>The Explorer Route</h1>
        <p style={{ color: "var(--ink-soft)", fontSize: 15.5, lineHeight: 1.6, maxWidth: "44em", margin: "0 0 8px" }}>
          {kids
            ? <>A start-to-finish adventure: the story of how people tamed electricity, the five big ideas, and real circuits you build and light up yourself. Finish the trail, pass the checkpoint, and the Explorer Engineer certificate is yours.</>
            : <>A guaranteed-finishable arc for younger learners: the story, chapters 1–5 in Explorer reading mode, and the matching hands-on builds — everything before the course starts leaning on algebra. It ends with its own checkpoint and certificate.</>}
        </p>
        <p style={{ color: "var(--ink-faint)", fontSize: 13.5, lineHeight: 1.55, maxWidth: "44em", margin: "0 0 30px" }}>
          {kids
            ? <>Tip: every page has an <b>Explorer / Engineer</b> switch at the top. Explorer keeps it plain — flip to Engineer any time you're curious.</>
            : <>The route doesn't fork the course — every stop is a normal page with the Explorer/Engineer toggle. A kid who outgrows Explorer flips one switch and the same pages deepen.</>}
        </p>

        <ExrStep num="1" title="Hear the story" note={kids ? "Five short tales — sparks, arguments, and the people who figured this all out." : "Level 0 — ungated narrative history. Sets the stage."} items={L0} progress={progress} />
        <ExrStep num="2" title="Get your bearings" note={kids ? "What's in the box, and how not to zap anything (including you)." : "The primer: safety, parts, and how the course works."} items={primer} progress={progress} />
        <ExrStep num="3" title="Learn the five big ideas" note={kids ? "Push, flow, pinch, buckets, switches — with water you can actually watch." : "Chapters 1–5 in Explorer mode: voltage, current & resistance; series & parallel; power; capacitors; switches & logic."} items={theory} progress={progress} />
        <ExrStep num="4" title="Build them for real" note={kids ? "Real breadboard, real LED, really yours." : "The Level 2 builds that apply chapters 1–5."} items={builds} progress={progress} />
        <ExrStep num="5" title="Play in the tools" note={kids ? "The Circuit Lab shows one circuit two ways at once. The Workbench lets you wire anything." : "Free play cements it — no goals, no grades."} items={tools} progress={progress} />

        {/* checkpoint */}
        <div id="checkpoint" style={{ display: "flex", gap: 18 }}>
          <div style={{ flex: "0 0 34px", display: "flex", flexDirection: "column", alignItems: "center" }}>
            <span style={{ width: 34, height: 34, borderRadius: "50%", border: "2px solid var(--current)", background: "var(--current)", display: "flex", alignItems: "center", justifyContent: "center",
                           fontFamily: "IBM Plex Mono, monospace", fontSize: 14, fontWeight: 600, color: "#fff" }}>★</span>
          </div>
          <div style={{ flex: 1 }}>
            <h3 style={{ fontFamily: "Newsreader, serif", fontWeight: 500, fontSize: 21, margin: "4px 0 4px" }}>The Explorer Checkpoint</h3>
            <p style={{ fontSize: 14, color: "var(--ink-soft)", margin: "0 0 16px", maxWidth: "40em", lineHeight: 1.5 }}>
              {kids ? <>Eight questions, all ideas — no math. Get six right and you've earned it. Try as many times as you like.</>
                    : <>Eight concept questions drawn from a larger bank, {EXR_PASS} to pass, unlimited retries. Passing stores the certificate on this device.</>}
            </p>
            {cert && cert.passed ? <ExrCertificate date={cert.date} /> : <ExrQuiz onPass={onPass} kids={kids} />}
          </div>
        </div>

        {/* where the trail continues */}
        <div style={{ marginTop: 40, background: "var(--bg-card)", border: "1px solid var(--rule)", borderRadius: 12, padding: "20px 24px" }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>the trail continues</div>
          <p style={{ fontSize: 14.5, color: "var(--ink-soft)", lineHeight: 1.6, margin: 0, maxWidth: "46em" }}>
            {kids
              ? <>Chapter 6 is where the real magic starts — the transistor, the tiny valve inside every computer. It uses a bit more number-work. When you're ready, warm up with <a href="math1.html" style={{ color: "var(--water)" }}>Math for Builders</a> (short and friendly, promise), then head to <a href="chapter6.html" style={{ color: "var(--water)" }}>Chapter 6</a>.</>
              : <>From Chapter 6 the course starts using light algebra (Ohm's law rearrangement, powers of ten). The <a href="math1.html" style={{ color: "var(--water)" }}>Math for Builders</a> stream (5 × 10 min) covers exactly that toolkit — take it alongside, then continue to <a href="chapter6.html" style={{ color: "var(--water)" }}>Chapter 6 · The Transistor</a>. Explorer mode stays available the whole way.</>}
          </p>
        </div>
      </main>
      <window.TweaksPanel title="Tweaks">
        <window.CommonTweaks t={t} setTweak={setTweak} />
      </window.TweaksPanel>
      <window.GlossaryFab />
    </>
  );
}

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