/* =========================================================================
   TAXR — Dashboard (phases → modules → progress)
   ========================================================================= */
function moduleState(m, account, progress) {
  const built = window.TAXR.modules[m.id];
  const total = m.lessons || (m.topics ? m.topics.length : 0);
  let lessonsDone = 0;
  const ids = built ? built.lessons.map((l) => l.id) : Array.from({ length: total }, (_, i) => m.id + "-l" + i);
  ids.forEach((id) => { if (progress.lessons[id]) lessonsDone++; });
  const testScore = (progress.tests || {})[m.id];
  const testPassed = testScore >= 70;
  const owned = account.paid || (account.purchasedModules || []).includes(m.id);
  const freeTeaser = m.id === "m1";
  const unlocked = owned || freeTeaser;
  // prereq: the module id that must be *passed* before this one can be purchased
  const prereqPassed = !m.prereq || ((progress.tests || {})[m.prereq] >= 70);
  // purchasable: not yet owned, and prereq test has been passed (or no prereq)
  const purchasable = !owned && prereqPassed;
  return { total, lessonsDone, testScore, testPassed, unlocked, owned, started: lessonsDone > 0, built: !!built, prereqPassed, purchasable };
}

function ModuleCard({ m, account, progress, nav }) {
  const s = moduleState(m, account, progress);
  const pct = s.total ? Math.round((s.lessonsDone / s.total) * 100) : 0;
  const locked = !s.unlocked;

  // prereq module title for tooltip
  const prereqMeta = m.prereq ? window.TAXR.moduleMeta[m.prereq] : null;
  const waitingOnPrereq = !s.unlocked && !s.prereqPassed;

  let statusEl, action;
  if (m.capstone) {
    statusEl = <Badge kind="amber">Capstone</Badge>;
  } else if (s.testPassed) {
    statusEl = <Badge kind="solid-green">Passed · {s.testScore}%</Badge>;
  } else if (waitingOnPrereq) {
    statusEl = <Badge kind="lock" dot={false}><Icon name="lock" size={12} style={{ marginRight: 2 }} />Pass M{prereqMeta?.n} first</Badge>;
  } else if (locked) {
    statusEl = <Badge kind="amber" dot={false}>Unlock</Badge>;
  } else if (s.started) {
    statusEl = <Badge kind="blue">In progress</Badge>;
  } else if (m.id === "m1") {
    statusEl = <Badge kind="green">Free start</Badge>;
  }

  function go() {
    if (waitingOnPrereq) return; // not clickable — prereq not met
    if (locked) { nav("paywall", { moduleId: m.id }); return; }
    const built = window.TAXR.modules[m.id];
    if (built) {
      const first = built.lessons.find((l) => !progress.lessons[l.id]) || built.lessons[0];
      nav("lesson", { lessonId: first.id, moduleId: m.id });
    } else {
      nav("module", { moduleId: m.id });
    }
  }

  return (
    <button onClick={go} className={`card${waitingOnPrereq ? "" : " card-hover"}`} style={{ padding: 22, textAlign: "left", display: "flex", flexDirection: "column", gap: 14, opacity: waitingOnPrereq ? 0.45 : locked ? 0.82 : 1, cursor: waitingOnPrereq ? "default" : "pointer" }}>
      <div className="row spread" style={{ alignItems: "flex-start" }}>
        <span className="row gap-12" style={{ alignItems: "center" }}>
          <span style={{ width: 38, height: 38, borderRadius: 11, display: "grid", placeItems: "center", flex: "none",
            background: s.testPassed ? "var(--green-soft)" : locked ? "rgba(255,255,255,0.04)" : "var(--blue-soft)",
            color: s.testPassed ? "var(--green)" : locked ? "var(--dim)" : "var(--blue-bright)" }}>
            {s.testPassed ? <Icon name="check" size={19} /> : locked ? <Icon name="lock" size={17} /> : <span className="mono fs-14" style={{ fontWeight: 600 }}>{String(m.n).padStart(2, "0")}</span>}
          </span>
          {m.tag && <span className="mono fs-13 t-dim">{m.tag}</span>}
        </span>
        {statusEl}
      </div>

      <div className="col" style={{ gap: 6 }}>
        <h3 className="serif" style={{ fontSize: 19, lineHeight: 1.2 }}>{m.title}</h3>
        <p className="fs-14 t-muted" style={{ lineHeight: 1.5, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{m.blurb}</p>
      </div>

      <div className="row spread" style={{ marginTop: "auto", alignItems: "center" }}>
        <span className="mono fs-13 t-dim">{m.capstone ? "Practice exams" : (locked ? m.lessons + " lessons" : s.lessonsDone + " / " + s.total + " lessons")}</span>
        {waitingOnPrereq
          ? <span className="fs-13 t-dim">Complete {prereqMeta?.title} first</span>
          : locked
            ? <span className="row gap-8 fs-14 t-amber" style={{ fontWeight: 600 }}>Unlock <Icon name="arrow" size={15} /></span>
            : <span className="row gap-8 fs-14 t-blue" style={{ fontWeight: 600 }}>{s.started ? "Continue" : "Start"} <Icon name="arrow" size={15} /></span>}
      </div>
      {!locked && !m.capstone && <Progress value={pct} green={s.testPassed} thin />}
    </button>
  );
}

function Dashboard({ nav, account, progress, dueCount = 0 }) {
  const D = window.TAXR;
  // overall progress
  let done = 0, total = 0;
  D.phases.forEach((p) => p.modules.forEach((m) => {
    const s = moduleState(m, account, progress);
    total += s.total; done += s.lessonsDone;
  }));
  const overall = total ? Math.round((done / total) * 100) : 0;

  // continue target — first unlocked, built module with an unfinished lesson
  function nextTarget() {
    for (const ph of D.phases) for (const m of ph.modules) {
      const built = D.modules[m.id];
      if (!built) continue;
      const s = moduleState(m, account, progress);
      if (!s.unlocked) continue;
      const lesson = built.lessons.find((l) => !progress.lessons[l.id]);
      if (lesson) return { mod: m, lesson };
    }
    return { mod: D.phases[0].modules[0], lesson: D.modules.m1.lessons[0] };
  }
  const target = nextTarget();
  const contMod = target.mod;
  const nextLesson = target.lesson;
  const justStarting = done === 0;

  return (
    <div className="wrap" style={{ padding: "36px 32px 80px" }}>
      {/* header */}
      <div className="row spread" style={{ alignItems: "flex-end", marginBottom: 28 }}>
        <div>
          <Eyebrow style={{ marginBottom: 12 }}>Your track</Eyebrow>
          <h1 className="display" style={{ fontSize: 40 }}>{justStarting ? <>Welcome, <span className="it">{account.name.split(" ")[0]}.</span></> : <>Keep going, <span className="it">{account.name.split(" ")[0]}.</span></>}</h1>
        </div>
        {!account.paid && (
          <Button variant="ghost" onClick={() => nav("checkout", { plan: "full" })}>
            <Icon name="spark" size={16} style={{ color: "var(--amber)" }} /> Unlock full course · $39
          </Button>
        )}
      </div>

      {/* continue card */}
      <div className="card grid-lines" style={{ padding: 30, display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 28, alignItems: "center", marginBottom: 16 }}>
        <div className="col center" style={{ position: "relative" }}>
          <div style={{ position: "relative", width: 84, height: 84 }}>
            <Ring value={overall} size={84} stroke={7} />
            <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center" }}>
              <span className="serif" style={{ fontSize: 24 }}>{overall}%</span>
            </div>
          </div>
          <span className="mono fs-13 t-dim" style={{ marginTop: 8 }}>OVERALL</span>
        </div>
        <div className="col" style={{ gap: 6 }}>
          <span className="mono fs-13 t-blue" style={{ letterSpacing: ".14em" }}>{justStarting ? "START HERE" : "PICK UP WHERE YOU LEFT OFF"}</span>
          <h2 className="serif" style={{ fontSize: 26 }}>{contMod.title}</h2>
          <p className="fs-15 t-muted">Lesson {nextLesson.n} · {nextLesson.title}</p>
        </div>
        <Button size="lg" arrow onClick={() => nav("lesson", { lessonId: nextLesson.id, moduleId: contMod.id })}>{justStarting ? "Begin lesson 1.1" : "Continue"}</Button>
      </div>

      {/* daily review strip */}
      <button onClick={() => nav("review")} className="card card-hover row spread"
        style={{ width: "100%", padding: "16px 22px", alignItems: "center", textAlign: "left",
          borderColor: dueCount > 0 ? "rgba(231,179,92,0.4)" : "var(--line)" }}>
        <div className="row gap-16" style={{ alignItems: "center" }}>
          <span style={{ width: 42, height: 42, borderRadius: 12, display: "grid", placeItems: "center", flex: "none",
            background: dueCount > 0 ? "var(--amber-soft)" : "var(--surface-3)", color: dueCount > 0 ? "var(--amber)" : "var(--dim)" }}>
            <Icon name="spark" size={20} />
          </span>
          <div className="col" style={{ gap: 2 }}>
            <span className="serif" style={{ fontSize: 18 }}>Daily review</span>
            <span className="fs-14 t-muted">{dueCount > 0
              ? dueCount + " item" + (dueCount === 1 ? "" : "s") + " Pip wants to bring back before you forget"
              : "Spaced repetition — missed questions return here, right on schedule"}</span>
          </div>
        </div>
        <span className="row gap-10" style={{ alignItems: "center", flex: "none" }}>
          {dueCount > 0 && <Badge kind="amber">{dueCount} due</Badge>}
          <span className="row gap-8 fs-14" style={{ fontWeight: 600, color: dueCount > 0 ? "var(--amber)" : "var(--blue-bright)" }}>{dueCount > 0 ? "Review now" : "Open deck"} <Icon name="arrow" size={15} /></span>
        </span>
      </button>

      {/* phases */}
      {D.phases.map((ph) => {
        const phModsDone = ph.modules.filter((m) => moduleState(m, account, progress).testPassed).length;
        return (
          <div key={ph.id} style={{ marginTop: 44 }}>
            <div className="row spread" style={{ marginBottom: 20, alignItems: "flex-end" }}>
              <div>
                <div className="row gap-12" style={{ marginBottom: 8 }}>
                  <span className="mono fs-13 t-blue" style={{ letterSpacing: ".14em" }}>PHASE {ph.n}</span>
                  <span className="mono fs-13 t-dim">{ph.topic}</span>
                </div>
                <h2 className="display" style={{ fontSize: 30 }}>{ph.name}</h2>
              </div>
              <div className="col" style={{ alignItems: "flex-end", gap: 8, minWidth: 180 }}>
                <span className="mono fs-13 t-dim">{phModsDone} / {ph.modules.length} modules passed</span>
                <Progress value={(phModsDone / ph.modules.length) * 100} green={phModsDone === ph.modules.length} thin />
              </div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 16 }}>
              {ph.modules.map((m) => <ModuleCard key={m.id} m={m} account={account} progress={progress} nav={nav} />)}
            </div>
            {/* milestone */}
            <div className="row gap-12" style={{ marginTop: 18, padding: "14px 20px", borderRadius: 14,
              border: "1px dashed " + (phModsDone === ph.modules.length ? "rgba(70,214,164,0.4)" : "var(--line-2)"),
              color: phModsDone === ph.modules.length ? "var(--green)" : "var(--dim)" }}>
              <Icon name={phModsDone === ph.modules.length ? "trophy" : "flag"} size={18} />
              <span className="fs-15" style={{ color: "var(--muted)" }}>{ph.milestone}</span>
            </div>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { Dashboard, moduleState });
