/* map.jsx — the course map page: the full trail on one screen (Simple or
   Circuit-board view), the Beacon onramp, projects shelf and tool cards.
   The FRONT PAGE (home.jsx) tells the story; this page shows the territory. */

const { useState: mapUseState, useEffect: mapUseEffect } = React;

const MAP_TWEAK_DEFAULTS = {
  "theme": "paper",
  "audience": "adult"
};

/* ─── big progress dial for the hero ─────────────────────────────────────── */
function DailyStreakBadge() {
  let streak = 0, doneToday = false;
  try {
    const d = JSON.parse(localStorage.getItem("hte-daily") || "{}");
    streak = d.streak || 0;
    doneToday = d.lastDone === new Date().toISOString().slice(0, 10);
  } catch (e) {}
  return (
    <span className="aux-go" style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
      {streak > 0 && (
        <span style={{ fontFamily: "IBM Plex Mono, monospace", fontSize: 12,
                       color: doneToday ? "var(--current-deep)" : "var(--ink-faint)" }}>
          {streak}-day{doneToday ? " ✓" : ""}
        </span>
      )}
      →
    </span>
  );
}

function HeroProgress({ done, total, legend = true }) {
  const pct = total ? Math.round((done / total) * 100) : 0;
  const C = 2 * Math.PI * 52;
  return (
    <div className="mh-progress">
      <svg viewBox="0 0 120 120" width="116" height="116" aria-hidden="true">
        <circle cx="60" cy="60" r="52" fill="none" stroke="var(--rule)" strokeWidth="8" />
        <circle cx="60" cy="60" r="52" fill="none" stroke="var(--current)" strokeWidth="8"
                strokeLinecap="round" strokeDasharray={`${(pct / 100) * C} ${C}`}
                transform="rotate(-90 60 60)" />
        <text x="60" y="58" textAnchor="middle" fontFamily="Newsreader, serif"
              fontSize="36" fill="var(--ink)">
          {pct}<tspan fontSize="17" dx="1">%</tspan>
        </text>
        <text x="60" y="80" textAnchor="middle" fontFamily="IBM Plex Mono, monospace"
              fontSize="10.5" letterSpacing="0.12em" fill="var(--ink-faint)">
          {done}/{total} CH
        </text>
      </svg>
      {legend && (
      <div className="mh-legend">
        <span><i className="dot done"></i>Soldered</span>
        <span><i className="dot now"></i>Up next</span>
        <span><i className="dot ready"></i>Ready</span>
      </div>
      )}
    </div>
  );
}

/* ─── App ──────────────────────────────────────────────────────────────── */
function MapApp() {
  const [t, setTweak] = useTweaks(MAP_TWEAK_DEFAULTS);
  useCrossChapterPersistence(t, setTweak);
  mapUseEffect(() => { document.body.setAttribute("data-theme", t.theme); }, [t.theme]);

  const progress = useProgressState();
  const stats = courseStats(progress);

  const pjDone = (() => {
    try { return Object.keys(JSON.parse(localStorage.getItem("hte-project") || "{}").done || {}).length; }
    catch { return 0; }
  })();

  const seq = [...ALL_CHAPTERS, ...L2_CHAPTERS.filter(c => c.ready !== false)];
  const nextCh = seq.find(c => progress[c.n] !== "done");
  const resumeHref = nextCh ? nextCh.href : "chapter1.html";
  const ctaLabel = stats.done === 0
    ? "Start at Chapter 1"
    : !nextCh
      ? "Review from the top"
      : `Resume — ${nextCh.t}`;

  const onReset = () => {
    if (confirm("Reset all chapter progress? Your theme and reading-level choices will stay.")) {
      try { localStorage.removeItem("hte-progress"); } catch {}
      window.dispatchEvent(new Event("hte-progress-changed"));
    }
  };

  const [mapStyle, setMapStyle] = mapUseState(() => {
    try { return localStorage.getItem("hte-mapstyle") || "simple"; } catch { return "simple"; }
  });
  const pickMap = (m) => { setMapStyle(m); try { localStorage.setItem("hte-mapstyle", m); } catch {} };

  return (
    <>
      <TopBar audience={t.audience} setAudience={(v) => setTweak("audience", v)} />
      <main className="map-page">
        <header className="map-hero">
          <div className="mh-left">
            <div className="badges">
              <span>Fathohm</span><span>·</span>
              <span>a field guide</span>
            </div>
            <h1>The course <span style={{ color: "var(--current)" }}>map</span>.</h1>
            <p className="lede">
              Every chapter, build, project, tool and elective — one screen,
              with your progress soldered in as you go.
            </p>
            <div className="home-cta-row">
              <a href={resumeHref} className="cta cta-primary">{ctaLabel} →</a>
              <a href="index.html" className="cta cta-secondary">← Front page</a>
            </div>
            <p className="mh-howto">
              <strong>Younger explorer?</strong> <a href="explorer.html">The Explorer
              Route</a> is a complete trail with its own certificate — no heavy math.
            </p>
          </div>
          <div className="mh-right">
            <a href="dashboard.html" className="mh-ring-link" title="Open your progress dashboard">
              <HeroProgress done={stats.done} total={stats.total} legend={mapStyle === "board"} />
            </a>
          </div>
        </header>

        <div className="sm-toggle-row" id="course">
          <span className="eyebrow">the course</span>
          <div className="sm-toggle" role="tablist" aria-label="Course map style">
            <button className={mapStyle === "simple" ? "active" : ""} onClick={() => pickMap("simple")}>Simple</button>
            <button className={mapStyle === "board" ? "active" : ""} onClick={() => pickMap("board")}>Circuit board</button>
          </div>
        </div>
        {mapStyle === "board" ? <CourseMap progress={progress} /> : <SimpleMap progress={progress} />}

        <a className="pj-onramp" href="project.html">
          <div className="pj-onramp-beacon" aria-hidden="true">
            <svg viewBox="0 0 60 64" width="58" height="62">
              {/* pulsing light rings */}
              <circle className="pj-ring" cx="30" cy="20" r="17" fill="none" stroke="var(--current)" strokeWidth="1.6" />
              <circle className="pj-ring r2" cx="30" cy="20" r="17" fill="none" stroke="var(--current)" strokeWidth="1.4" />
              {/* the device: mast + base */}
              <line x1="30" y1="29" x2="30" y2="48" stroke="var(--ink-soft)" strokeWidth="2.6" />
              <line x1="19" y1="52" x2="41" y2="52" stroke="var(--ink-soft)" strokeWidth="2.6" strokeLinecap="round" />
              <line x1="24" y1="52" x2="30" y2="44" stroke="var(--ink-soft)" strokeWidth="1.8" />
              <line x1="36" y1="52" x2="30" y2="44" stroke="var(--ink-soft)" strokeWidth="1.8" />
              {/* the lamp — blinks */}
              <circle className="pj-lamp" cx="30" cy="20" r="8" fill="var(--current)" />
              <circle cx="30" cy="20" r="8" fill="none" stroke="var(--current-deep)" strokeWidth="1.4" />
            </svg>
          </div>
          <div className="pj-onramp-text">
            <div className="eyebrow" style={{ color: "var(--current)" }}>The flagship build · first of five projects</div>
            <h3>Build <em>The Beacon</em> as you learn</h3>
            <p>Each chapter hands you a new part and a new spec — pick real component values, check the math, and grow one LED into the flashing signal beacon above. By the final build, it's real — blinking at the rate you specced.</p>
          </div>
          <div className="pj-onramp-meta">
            <span className="mono">{pjDone}/{PJ_META.total}</span>
            <span className="pj-onramp-go">{pjDone === 0 ? "Start the build" : pjDone === PJ_META.total ? "Complete" : "Continue"} →</span>
          </div>
        </a>

        <a className="pj-shelf-link" href="projects.html">
          <span className="pj-shelf-dots" aria-hidden="true">●●●●●</span>
          <span>The Beacon is the first of <b>five projects</b> — motor spinner, light sequencer, mood lamp &amp; buzzer too.</span>
          <span className="pj-shelf-go">See the whole shelf →</span>
        </a>

        {/* daily drill + workbench — the habit row (board view only; the simple
            map carries the tools in its Anytime shelf) */}
        {mapStyle === "board" && (
        <div className="aux-row">
          <a className="aux-card" href="daily.html">
            <span className="aux-icon" aria-hidden="true">
              <svg viewBox="0 0 40 40" width="30" height="30">
                <rect x="7" y="9" width="26" height="24" rx="4" fill="none" stroke="var(--current)" strokeWidth="2" />
                <line x1="7" y1="16" x2="33" y2="16" stroke="var(--current)" strokeWidth="2" />
                <line x1="13" y1="6" x2="13" y2="12" stroke="var(--current)" strokeWidth="2" strokeLinecap="round" />
                <line x1="27" y1="6" x2="27" y2="12" stroke="var(--current)" strokeWidth="2" strokeLinecap="round" />
                <text x="20" y="29" textAnchor="middle" fontFamily="IBM Plex Mono, monospace" fontSize="11" fontWeight="700" fill="var(--current)">✓</text>
              </svg>
            </span>
            <span className="aux-text">
              <b>Today's drill</b>
              <i>Three quick questions · keeps it all fresh</i>
            </span>
            <DailyStreakBadge />
          </a>
          <a className="aux-card" href="flow-sandbox.html">
            <span className="aux-icon" aria-hidden="true">
              <svg viewBox="0 0 40 40" width="30" height="30">
                <path d="M6 20 H15" stroke="var(--water)" strokeWidth="2" strokeLinecap="round" fill="none" />
                <path d="M25 20 H34" stroke="var(--water)" strokeWidth="2" strokeLinecap="round" fill="none" />
                <path d="M15 20 l2 -6 l3 12 l3 -12 l2 6" stroke="var(--water)" strokeWidth="2" fill="none" strokeLinejoin="round" strokeLinecap="round" />
                <circle cx="10" cy="20" r="2" fill="var(--current)" />
                <circle cx="30" cy="20" r="2" fill="var(--current)" />
              </svg>
            </span>
            <span className="aux-text">
              <b>The Sandbox</b>
              <i>See how it works · probe live voltages &amp; currents</i>
            </span>
            <span className="aux-go">→</span>
          </a>
          <a className="aux-card" href="circuit-lab.html">
            <span className="aux-icon" aria-hidden="true">
              <svg viewBox="0 0 40 40" width="30" height="30">
                <rect x="5" y="11" width="13" height="18" rx="2" fill="none" stroke="var(--current)" strokeWidth="2" />
                <circle cx="9" cy="16" r="1.3" fill="var(--current)" />
                <circle cx="14" cy="16" r="1.3" fill="var(--current)" />
                <circle cx="9" cy="24" r="1.3" fill="var(--current)" />
                <circle cx="14" cy="24" r="1.3" fill="var(--current)" />
                <path d="M22 20 h3 l1.5 -4 l3 8 l1.5 -4 h3" fill="none" stroke="var(--current)" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            </span>
            <span className="aux-text">
              <b>Circuit Lab</b>
              <i>Board ↔ schematic · one circuit, two views, in sync</i>
            </span>
            <span className="aux-go">→</span>
          </a>
          <a className="aux-card" href="sandbox.html">
            <span className="aux-icon" aria-hidden="true">
              <svg viewBox="0 0 40 40" width="30" height="30">
                <rect x="6" y="10" width="28" height="20" rx="3" fill="none" stroke="var(--water)" strokeWidth="2" />
                {[12, 17, 22, 28].map(x => <circle key={x} cx={x} cy="16" r="1.5" fill="var(--water)" />)}
                {[12, 17, 22, 28].map(x => <circle key={x} cx={x} cy="24" r="1.5" fill="var(--water)" />)}
              </svg>
            </span>
            <span className="aux-text">
              <b>The Workbench</b>
              <i>Free build · no goal, no grade — just wire things</i>
            </span>
            <span className="aux-go">→</span>
          </a>
          <a className="aux-card" href="scope.html">
            <span className="aux-icon" aria-hidden="true">
              <svg viewBox="0 0 40 40" width="30" height="30">
                <rect x="5" y="8" width="30" height="24" rx="3" fill="none" stroke="var(--current)" strokeWidth="2" />
                <path d="M 9 20 q 4 -9 8 0 q 4 9 8 0 q 3 -7 6 -1" fill="none" stroke="var(--current)" strokeWidth="2" strokeLinecap="round" />
              </svg>
            </span>
            <span className="aux-text">
              <b>The Oscilloscope</b>
              <i>Read signals like a pro · spot sick circuits on sight</i>
            </span>
            <span className="aux-go">→</span>
          </a>
        </div>
        )}

        <footer className="home-footer">
          <span>Fath<span style={{ color: "var(--current)" }}>ohm</span> · A field guide</span>
          <span style={{ display: "flex", gap: 22 }}>
            <a href="projects.html">Projects</a>
            <a href="about.html">About</a>
            <a href="dashboard.html">Progress</a>
            <a href="https://ko-fi.com/fathohm" target="_blank" rel="noopener noreferrer">Support</a>
            <a href={resumeHref}>{stats.done === 0 ? "Begin" : "Resume"} →</a>
          </span>
        </footer>
      </main>

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

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