/* dashboard.jsx — "Your Progress" across the whole course.
   Reads hte-progress (per-chapter status), hte-activity (quiz/practice/build),
   and hte-project (Beacon stages). Pure read-only view + reset. */

const { useState, useEffect } = React;

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

/* which activities each chapter offers */
function dashActivities(n) {
  if (n.startsWith("L0")) return ["read"];
  if (n === "L2-01") return ["read", "build"];
  if (n.startsWith("L2")) return ["read", "practice", "build"];
  return ["read", "quiz", "practice"]; // L1
}

const ACT_META = {
  read:     { label: "Read", glyph: "▣" },
  quiz:     { label: "Quiz", glyph: "✓" },
  practice: { label: "Practice", glyph: "∑" },
  build:    { label: "Build", glyph: "⚐" },
};

function Ring({ pct, size = 132, stroke = 9 }) {
  const r = (size - stroke) / 2, C = 2 * Math.PI * r;
  return (
    <svg viewBox={`0 0 ${size} ${size}`} width={size} height={size} aria-hidden="true">
      <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--rule)" strokeWidth={stroke} />
      <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="var(--current)" strokeWidth={stroke}
              strokeLinecap="round" strokeDasharray={`${(pct / 100) * C} ${C}`}
              transform={`rotate(-90 ${size / 2} ${size / 2})`} />
      <text x={size / 2} y={size / 2 - 2} textAnchor="middle" fontFamily="Newsreader, serif"
            fontSize={size * 0.3} fill="var(--ink)">{pct}<tspan fontSize={size * 0.14}>%</tspan></text>
      <text x={size / 2} y={size / 2 + size * 0.16} textAnchor="middle"
            fontFamily="IBM Plex Mono, monospace" fontSize={size * 0.08}
            letterSpacing="0.12em" fill="var(--ink-faint)">COMPLETE</text>
    </svg>
  );
}

function ActivityDot({ kind, done }) {
  const m = ACT_META[kind];
  return (
    <span className={`dash-dot ${done ? "done" : ""}`} title={`${m.label}: ${done ? "done" : "not yet"}`}>
      <span className="dd-glyph">{done ? "✓" : m.glyph}</span>
      <span className="dd-label">{m.label}</span>
    </span>
  );
}

function ChapterRow({ ch, status, act }) {
  const acts = dashActivities(ch.n);
  const ready = ch.ready !== false;
  const visited = status === "done" || status === "in-progress";
  const inner = (
    <>
      <span className="dash-n mono">{ch.n}</span>
      <span className="dash-title">
        {ch.t}<i>{ch.sub}</i>
      </span>
      <span className="dash-acts">
        {acts.map(k => (
          <ActivityDot key={k} kind={k}
            done={k === "read" ? visited : !!(act && act[k])} />
        ))}
      </span>
      <span className={`dash-status ${status || "none"}`}>
        {status === "done" ? "Done" : status === "in-progress" ? "Started" : ready ? "Open" : "Soon"}
      </span>
    </>
  );
  return ready
    ? <a className="dash-row" href={ch.href}>{inner}</a>
    : <div className="dash-row soon">{inner}</div>;
}

function LevelBlock({ tag, note, chapters, progress, activity }) {
  const ready = chapters.filter(c => c.ready !== false);
  const done = ready.filter(c => progress[c.n] === "done").length;
  return (
    <section className="dash-level">
      <div className="dash-level-head">
        <div>
          <div className="dash-level-tag">{tag}</div>
          <div className="dash-level-note">{note}</div>
        </div>
        <div className="dash-level-count mono">{done}/{ready.length}</div>
      </div>
      <div className="dash-rows">
        {chapters.map(c => (
          <ChapterRow key={c.n} ch={c} status={progress[c.n]} act={activity[c.n]} />
        ))}
      </div>
    </section>
  );
}

function App() {
  const [t, setTweak] = useTweaks(DASH_TWEAKS);
  useCrossChapterPersistence(t, setTweak, ["audience", "theme", "difficulty"]);
  useEffect(() => { document.body.setAttribute("data-theme", t.theme); }, [t.theme]);

  const progress = useProgressState();
  const activity = useActivityState();

  // overall: count every discrete "task" — read+quiz+practice / read+build etc.
  const allCh = [...ALL_CHAPTERS, ...L15_CHAPTERS, ...M_CHAPTERS, ...L2_CHAPTERS.filter(c => c.ready !== false)];
  let total = 0, done = 0;
  allCh.forEach(c => {
    const acts = dashActivities(c.n);
    acts.forEach(k => {
      total++;
      if (k === "read") { if (progress[c.n] === "done") done++; }
      else if (activity[c.n] && activity[c.n][k]) done++;
    });
  });
  // capstones as read-tasks
  [["capstone", "Lv.1 Exam"], ["capstone-l2", "Master Exam"]].forEach(([k]) => {
    total++; if (progress[k] === "done") done++;
  });
  const pct = total ? Math.round((done / total) * 100) : 0;

  // beacon project stages
  let beaconDone = 0, beaconTotal = 0;
  try {
    const pj = JSON.parse(localStorage.getItem("hte-project") || "{}");
    const d = pj.done || {};
    beaconTotal = 10;
    beaconDone = Object.values(d).filter(Boolean).length;
  } catch (e) {}

  const storyDone = L0_CHAPTERS.filter(c => progress[c.n] === "done").length;
  const l1Done = ALL_CHAPTERS.filter(c => progress[c.n] === "done").length;
  const extraDone = [...L15_CHAPTERS, ...M_CHAPTERS].filter(c => progress[c.n] === "done").length;
  const l2ready = L2_CHAPTERS.filter(c => c.ready !== false);
  const l2Done = l2ready.filter(c => progress[c.n] === "done").length;

  const resetAll = () => {
    if (!confirm("Reset ALL progress — chapters, quizzes, practice, builds, and the Beacon project? Your theme and difficulty stay.")) return;
    ["hte-progress", "hte-activity", "hte-project"].forEach(k => { try { localStorage.removeItem(k); } catch (e) {} });
    window.dispatchEvent(new Event("hte-progress-changed"));
    window.dispatchEvent(new Event("hte-activity-changed"));
  };

  return (
    <>
      <ProgressBar />
      <TopBar chapterLabel="Your progress"
              audience={t.audience} setAudience={(v) => setTweak("audience", v)} />

      <main className="dash">
        <header className="dash-hero">
          <div className="dash-hero-text">
            <div className="eyebrow" style={{ color: "var(--current)" }}>Your progress</div>
            <h1 className="serif">How far you've come.</h1>
            <p className="lede">
              Every chapter you read, quiz you pass, problem you solve, and circuit you
              build is tracked here — on this device. Pick up wherever a row isn't full.
            </p>
            <div className="dash-stat-row">
              <div className="dash-stat"><b>{storyDone}</b><span>/ {L0_CHAPTERS.length} stories</span></div>
              <div className="dash-stat"><b>{l1Done}</b><span>/ {ALL_CHAPTERS.length} theory</span></div>
              <div className="dash-stat"><b>{extraDone}</b><span>/ {L15_CHAPTERS.length + M_CHAPTERS.length} extras</span></div>
              <div className="dash-stat"><b>{l2Done}</b><span>/ {l2ready.length} builds</span></div>
              <div className="dash-stat"><b>{beaconDone}</b><span>/ {beaconTotal} Beacon</span></div>
            </div>
            <div className="dash-actions">
              <DifficultyToggle showBlurb />
            </div>
          </div>
          <div className="dash-hero-ring"><Ring pct={pct} /></div>
        </header>

        <LevelBlock tag="LV.0 · The Story" note="optional history · read anytime"
                    chapters={L0_CHAPTERS} progress={progress} activity={activity} />
        <LevelBlock tag="LV.1 · The Theory" note="read · quiz · practice"
                    chapters={ALL_CHAPTERS} progress={progress} activity={activity} />
        <LevelBlock tag="Electives · Deeper Theory" note="optional · after the Lv.1 exam"
                    chapters={L15_CHAPTERS} progress={progress} activity={activity} />
        <LevelBlock tag="Math for Builders" note="optional support · 5 × 10 min"
                    chapters={M_CHAPTERS} progress={progress} activity={activity} />
        <LevelBlock tag="LV.2 · The Build" note="read · practice · build the circuit"
                    chapters={L2_CHAPTERS} progress={progress} activity={activity} />

        {/* exams + project */}
        <section className="dash-level">
          <div className="dash-level-head">
            <div>
              <div className="dash-level-tag">Capstones &amp; project</div>
              <div className="dash-level-note">the integrative challenges</div>
            </div>
          </div>
          <div className="dash-rows">
            <a className="dash-row" href="capstone.html">
              <span className="dash-n mono">★</span>
              <span className="dash-title">The Capstone Exam<i>Level 1 finale · four design briefs</i></span>
              <span className="dash-acts"></span>
              <span className={`dash-status ${progress["capstone"] || "none"}`}>
                {progress["capstone"] === "done" ? "Passed" : progress["capstone"] ? "Started" : "Open"}
              </span>
            </a>
            <a className="dash-row" href="project.html">
              <span className="dash-n mono">⚙</span>
              <span className="dash-title">The Beacon<i>cumulative project · {beaconDone}/{beaconTotal} stages designed</i></span>
              <span className="dash-acts"></span>
              <span className={`dash-status ${beaconDone === beaconTotal ? "done" : beaconDone ? "in-progress" : "none"}`}>
                {beaconDone === beaconTotal ? "Complete" : beaconDone ? "Building" : "Open"}
              </span>
            </a>
            <a className="dash-row" href="capstone-l2.html">
              <span className="dash-n mono">★</span>
              <span className="dash-title">Master Engineer Exam<i>Level 2 finale · final certificate</i></span>
              <span className="dash-acts"></span>
              <span className={`dash-status ${progress["capstone-l2"] || "none"}`}>
                {progress["capstone-l2"] === "done" ? "Passed" : progress["capstone-l2"] ? "Started" : "Open"}
              </span>
            </a>
          </div>
        </section>

        <footer className="dash-foot">
          <a href="map.html">← Course map</a>
          <button className="dash-reset" onClick={resetAll}>Reset all progress</button>
        </footer>
      </main>

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

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