/* =========================================================================
   TAXR — Lesson reader
   ========================================================================= */
function Block({ b }) {
  if (b.t === "p") return <p className="fs-17 lh-rel" style={{ color: "var(--ink)", marginBottom: 20 }}>{b.x}</p>;
  if (b.t === "h") return <h3 className="serif" style={{ fontSize: 24, margin: "34px 0 14px" }}>{b.x}</h3>;
  if (b.t === "list") return (
    <ul className="col" style={{ gap: 10, margin: "0 0 22px", paddingLeft: 2, listStyle: "none" }}>
      {b.items.map((it, i) => (
        <li key={i} className="row gap-12" style={{ alignItems: "flex-start" }}>
          <span style={{ width: 6, height: 6, borderRadius: 3, background: "var(--blue)", marginTop: 10, flex: "none" }} />
          <span className="fs-16 lh-rel" style={{ color: "var(--ink)" }}>{it}</span>
        </li>
      ))}
    </ul>
  );
  if (b.t === "table") return (
    <div className="card" style={{ overflow: "hidden", margin: "10px 0 26px" }}>
      <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 15 }}>
        <thead>
          <tr>{b.head.map((h, i) => (
            <th key={i} style={{ textAlign: "left", padding: "13px 16px", fontFamily: "var(--mono)", fontSize: 12, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--dim)", borderBottom: "1px solid var(--line)", background: "rgba(255,255,255,0.02)" }}>{h}</th>
          ))}</tr>
        </thead>
        <tbody>
          {b.rows.map((r, ri) => (
            <tr key={ri}>{r.map((c, ci) => (
              <td key={ci} style={{ padding: "12px 16px", borderBottom: ri < b.rows.length - 1 ? "1px solid var(--line)" : "none", color: ci === 0 ? "var(--text)" : "var(--muted)", fontWeight: ci === 0 ? 600 : 400, fontVariantNumeric: "tabular-nums" }}>{c}</td>
            ))}</tr>
          ))}
        </tbody>
      </table>
    </div>
  );
  if (b.t === "callout") {
    const tone = { blue: ["var(--blue-bright)", "var(--blue-soft)", "rgba(91,133,245,0.3)"], amber: ["var(--amber)", "var(--amber-soft)", "rgba(231,179,92,0.3)"] }[b.tone || "blue"];
    return (
      <div style={{ display: "flex", gap: 14, padding: "18px 20px", borderRadius: 14, background: tone[1], border: "1px solid " + tone[2], margin: "10px 0 26px" }}>
        <Icon name="spark" size={18} style={{ color: tone[0], marginTop: 3, flex: "none" }} />
        <div className="col" style={{ gap: 5 }}>
          {b.title && <span style={{ fontWeight: 700, color: tone[0] }}>{b.title}</span>}
          <span className="fs-15 lh-rel" style={{ color: "var(--ink)" }}>{b.x}</span>
        </div>
      </div>
    );
  }
  if (b.t === "key") return (
    <div style={{ borderLeft: "3px solid var(--green)", paddingLeft: 20, margin: "26px 0" }}>
      {b.title && <div className="mono fs-13 t-green upper" style={{ marginBottom: 6 }}>{b.title}</div>}
      <p className="serif-it" style={{ fontSize: 21, lineHeight: 1.4, color: "var(--text)" }}>{b.x}</p>
    </div>
  );
  return null;
}

function LessonSidebar({ lessons, currentId, moduleId, moduleNum, account, progress, nav, testScore }) {
  return (
    <aside className="col lesson-side" style={{ gap: 4, position: "sticky", top: 88, alignSelf: "flex-start", width: 270, flex: "none" }}>
      <div className="row spread" style={{ marginBottom: 14 }}>
        <span className="mono fs-13 t-dim upper">Module {moduleNum}</span>
        <button className="row gap-8 fs-13 t-blue" onClick={() => nav("dashboard")}><Icon name="back" size={14} /> All modules</button>
      </div>
      {lessons.map((l) => {
        const done = progress.lessons[l.id];
        const owned = account.paid;
        const locked = !l.free && !owned;
        const active = l.id === currentId;
        return (
          <button key={l.id} onClick={() => nav("lesson", { lessonId: l.id, moduleId })}
            className="row gap-12" style={{ padding: "11px 12px", borderRadius: 10, textAlign: "left", alignItems: "center",
              background: active ? "var(--surface-2)" : "transparent", border: "1px solid " + (active ? "var(--line-2)" : "transparent") }}>
            <span style={{ width: 24, height: 24, borderRadius: 7, display: "grid", placeItems: "center", flex: "none",
              background: done ? "var(--green-soft)" : "rgba(255,255,255,0.04)", color: done ? "var(--green)" : locked ? "var(--dim)" : "var(--muted)" }}>
              {done ? <Icon name="check" size={14} /> : locked ? <Icon name="lock" size={12} /> : <span className="mono" style={{ fontSize: 11 }}>{l.n.split(".")[1]}</span>}
            </span>
            <div className="col" style={{ minWidth: 0 }}>
              <span className="fs-14" style={{ fontWeight: active ? 600 : 400, color: active ? "var(--text)" : "var(--muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{l.title}</span>
            </div>
          </button>
        );
      })}
      <div className="hr" style={{ margin: "10px 0" }} />
      <button onClick={() => nav("flashcards", { moduleId })} className="row gap-12" style={{ padding: "11px 12px", borderRadius: 10, color: "var(--muted)" }}>
        <span style={{ width: 24, display: "grid", placeItems: "center" }}><Icon name="cards" size={16} /></span><span className="fs-14">Flashcards</span>
      </button>
      <button onClick={() => nav("quiz", { moduleId })} className="row gap-12" style={{ padding: "11px 12px", borderRadius: 10, color: testScore >= 70 ? "var(--green)" : "var(--muted)" }}>
        <span style={{ width: 24, display: "grid", placeItems: "center" }}><Icon name={testScore >= 70 ? "trophy" : "flag"} size={16} /></span>
        <span className="fs-14">Module test{testScore >= 70 ? " · " + testScore + "%" : ""}</span>
      </button>
    </aside>
  );
}

function Lesson({ nav, params, account, progress, onComplete }) {
  const D = window.TAXR;
  const moduleId = params.moduleId || D.lessonModule[params.lessonId] || "m1";
  const mod = D.modules[moduleId];
  const moduleNum = (D.moduleMeta[moduleId] || {}).n || 1;
  const lessons = mod.lessons;
  const idx = Math.max(0, lessons.findIndex((l) => l.id === params.lessonId));
  const lesson = lessons[idx];
  const owned = account.paid;
  const locked = !lesson.free && !owned;
  const done = !!progress.lessons[lesson.id];
  const testScore = (progress.tests || {})[moduleId] || 0;
  const scrollRef = useRef(null);

  useEffect(() => { if (scrollRef.current) scrollRef.current.scrollTop = 0; window.scrollTo(0, 0); }, [params.lessonId]);

  const isLast = idx === lessons.length - 1;
  function next() {
    if (!done) onComplete(lesson.id);
    if (isLast) { nav("quiz", { moduleId }); return; }
    nav("lesson", { lessonId: lessons[idx + 1].id, moduleId });
  }

  return (
    <div className="wrap lesson-shell" style={{ padding: "30px 32px 90px", display: "flex", gap: 44, alignItems: "flex-start" }}>
      <LessonSidebar lessons={lessons} currentId={lesson.id} moduleId={moduleId} moduleNum={moduleNum} account={account} progress={progress} nav={nav} testScore={testScore} />

      <main style={{ flex: 1, maxWidth: 720, minWidth: 0 }} ref={scrollRef}>
        {/* lesson header */}
        <div className="row gap-12" style={{ marginBottom: 14 }}>
          <Badge kind={lesson.free ? "green" : "blue"}>{lesson.free ? "Free lesson" : "Lesson " + lesson.n}</Badge>
          <span className="row gap-8 mono fs-13 t-dim"><Icon name="clock" size={14} /> {lesson.min} min read</span>
        </div>
        <h1 className="display" style={{ fontSize: 40, marginBottom: 16 }}>{lesson.title}</h1>
        <div style={{ padding: "14px 18px", borderRadius: 12, background: "var(--surface)", border: "1px solid var(--line)", marginBottom: 36 }}>
          <span className="mono fs-13 t-blue upper">Learning objective</span>
          <p className="fs-15 t-muted" style={{ marginTop: 6 }}>{lesson.objective}</p>
        </div>

        {/* content (blurred if locked) */}
        <div style={{ position: "relative" }}>
          <div style={{ filter: locked ? "blur(7px)" : "none", pointerEvents: locked ? "none" : "auto", userSelect: locked ? "none" : "auto" }}>
            {lesson.blocks.map((b, i) => <Block key={i} b={b} />)}
            {!locked && moduleId === "m1" && idx === 1 && <Pip tone="tip" title="Pip's tip" style={{ marginTop: 12 }}>The extension trap catches almost everyone. Say it out loud once: "extension to <em>file</em>, not to <em>pay</em>." That one line has saved clients thousands in penalties.</Pip>}
          </div>

          {locked && (
            <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", paddingTop: 30 }}>
              {window.UnlockCard({ nav, moduleId, account })}
            </div>
          )}
        </div>

        {/* footer nav */}
        {!locked && (
          <div className="row spread" style={{ marginTop: 44, paddingTop: 26, borderTop: "1px solid var(--line)" }}>
            <Button variant="ghost" back disabled={idx === 0} onClick={() => nav("lesson", { lessonId: lessons[idx - 1].id, moduleId })}>Previous</Button>
            <div className="row gap-12">
              {done && <span className="row gap-8 fs-14 t-green"><Icon name="check" size={16} /> Completed</span>}
              <Button arrow onClick={next}>{isLast ? "Take the module test" : (done ? "Next lesson" : "Mark complete & continue")}</Button>
            </div>
          </div>
        )}
      </main>
    </div>
  );
}

Object.assign(window, { Lesson });
