/* ============================================================
   Screen: Compliance Cockpit — IB verification readiness
   ============================================================ */
(function () {
  const DB = window.DB;
  const TODAY = "2026-06-04";
  const days = (a, b) => Math.round((new Date(b) - new Date(a)) / 86400000);
  function polStatus(date) {
    const d = days(TODAY, date);
    if (d < 0) return { k: "overdue", label: t("Overdue"), cls: "crit" };
    if (d <= 45) return { k: "due", label: t("Due") + " " + date.slice(5), cls: "watch" };
    return { k: "current", label: t("Current"), cls: "stable" };
  }

  const TRAINING = [
    { subj: "Chemistry HL / SL", teacher: "T-04", status: "current", exp: "2027-08" },
    { subj: "Mathematics AA HL / SL", teacher: "T-06", status: "expiring", exp: "2026-08" },
    { subj: "History HL + TOK", teacher: "T-02", status: "current", exp: "2027-01" },
    { subj: "Economics HL", teacher: "T-09", status: "gap", exp: "—" },
    { subj: "Physics HL / SL", teacher: "T-08", status: "current", exp: "2026-12" },
    { subj: "Biology HL / SL", teacher: "T-10", status: "current", exp: "2027-03" },
    { subj: "English B HL / SL", teacher: "T-05", status: "current", exp: "2026-11" },
    { subj: "Russian A / Uzbek A", teacher: "T-12", status: "expiring", exp: "2026-07" },
    { subj: "Visual Arts / Film", teacher: "T-11", status: "current", exp: "2027-02" },
    { subj: "Mathematics AA HL (Section 2)", teacher: null, status: "gap", exp: "—" },
    { subj: "Business Management SL", teacher: "T-09", status: "current", exp: "2027-04" },
    { subj: "Psychology HL", teacher: "T-02", status: "current", exp: "2026-10" },
  ];
  const TR_STATUS = { current: { label: "Current", cls: "stable" }, expiring: { label: "Expiring", cls: "watch" }, gap: { label: "Gap", cls: "crit" } };

  function Pillar({ label, value, total, unit, status, note, onClick }) {
    const col = status === "crit" ? "var(--critical)" : status === "warn" ? "var(--watch)" : "var(--stable)";
    return (
      <button className="pillar" onClick={onClick}>
        <div className="between">
          <span className="eyebrow">{label}</span>
          <span className="dot-sev" style={{ background: col }}></span>
        </div>
        <div className="row" style={{ alignItems: "baseline", gap: 4, marginTop: 10 }}>
          <span className="mono" style={{ fontSize: 24, fontWeight: 600, color: col }}>{value}</span>
          {total ? <span className="mono faint" style={{ fontSize: 13 }}>/ {total}</span> : null}
          {unit ? <span className="mono faint" style={{ fontSize: 13 }}>{unit}</span> : null}
        </div>
        <div className="muted" style={{ fontSize: 11, marginTop: 6 }}>{note}</div>
      </button>
    );
  }

  function Compliance({ navigate }) {
    const c = DB.compliance;
    const policies = DB.DOCUMENTS.filter((d) => d.cat === "Policy");
    const trCurrent = TRAINING.filter((t) => t.status === "current").length;
    const trGap = TRAINING.filter((t) => t.status === "gap").length;
    const cwPct = c.stats ? c.stats.iaComplete : Math.round((c.coursework.submitted / c.coursework.expected) * 100);
    const iaPct = Math.round((c.coursework.submitted / c.coursework.expected) * 100);

    const readiness = Math.round((
      (c.policies.current / c.policies.total) * 100 +
      (trCurrent / TRAINING.length) * 100 +
      iaPct +
      (c.support.withPlan / c.support.identified) * 100
    ) / 4);

    const blockers = [
      { sev: "crit", text: t("Safeguarding & Child Protection Policy review is overdue (since 20 May)."), to: "docs" },
      { sev: "crit", text: t("Economics HL has no IB-trained teacher on record."), to: null },
      { sev: "crit", text: t("Mathematics AA HL (Section 2) — training gap, unassigned."), to: null },
      { sev: "watch", text: t("2 teachers' IB training expires this term — schedule renewal."), to: null },
      { sev: "watch", text: c.coursework.expected - c.coursework.submitted + " " + t("coursework pieces still outstanding (") + iaPct + t("% complete)."), to: "coursework" },
      { sev: "watch", text: t("1 identified student is without an active support plan."), to: "ilp" },
    ];

    return (
      <div className="screen">
        <div className="between" style={{ marginBottom: 18 }}>
          <div>
            <h2 style={{ fontSize: 19 }}>{t("Compliance Cockpit")}</h2>
            <p className="muted" style={{ fontSize: 13, marginTop: 4 }}>{t("IB verification readiness across policies, staff training, coursework and support coverage.")}</p>
          </div>
          <button className="btn btn-sm" onClick={() => window.toast(t("Generating IB readiness report…"))}><Icon name="download" size={14} />{t("Readiness report")}</button>
        </div>

        {/* readiness banner */}
        <div className="panel readiness-banner">
          <div className="rb-ring">
            <Donut size={132} thickness={14} center={readiness + "%"} segments={[
              { value: readiness, color: readiness >= 85 ? "var(--stable)" : readiness >= 70 ? "var(--watch)" : "var(--critical)" },
              { value: 100 - readiness, color: "var(--surface-2)" },
            ]} />
            <div style={{ textAlign: "center", marginTop: 10 }}>
              <span className="badge watch"><span className="dot"></span>{t("Amber · approaching ready")}</span>
            </div>
          </div>
          <div className="rb-pillars">
            <Pillar label={t("Policies in review")} value={c.policies.current} total={c.policies.total} status={c.policies.overdue ? "crit" : "warn"} note={c.policies.overdue + " " + t("overdue") + " · " + c.policies.due + " " + t("due soon")} onClick={() => navigate("docs")} />
            <Pillar label={t("IB training coverage")} value={trCurrent} total={TRAINING.length} status={trGap ? "crit" : "warn"} note={trGap + " " + t("gaps · 2 expiring")} onClick={() => {}} />
            <Pillar label={t("Coursework complete")} value={iaPct} unit="%" status={iaPct >= 90 ? "ok" : "warn"} note={c.coursework.submitted + " " + t("of") + " " + c.coursework.expected + " " + t("submitted")} onClick={() => navigate("coursework")} />
            <Pillar label={t("Support coverage")} value={c.support.withPlan} total={c.support.identified} status={c.support.withPlan < c.support.identified ? "warn" : "ok"} note={t("1 plan to assign")} onClick={() => navigate("ilp")} />
          </div>
        </div>

        {/* blockers */}
        <div className="panel" style={{ margin: "16px 0" }}>
          <div className="panel-h"><div className="row" style={{ gap: 8 }}><Icon name="alert" size={15} style={{ color: "var(--watch)" }} /><h3>{t("Outstanding for verification")}</h3></div><span className="mono muted" style={{ fontSize: 12 }}>{blockers.length} {t("items")}</span></div>
          <div className="panel-b" style={{ display: "flex", flexDirection: "column", gap: 0 }}>
            {blockers.map((b, i) => (
              <div key={i} className="blocker-row">
                <span className={"dot-sev " + (b.sev === "crit" ? "crit" : "")} style={b.sev === "watch" ? { background: "var(--watch)" } : {}}></span>
                <span style={{ flex: 1, fontSize: 12.5 }}>{b.text}</span>
                {b.to ? <button className="btn btn-sm btn-ghost" onClick={() => navigate(b.to)}>{t("Resolve")}<Icon name="arrowR" size={12} /></button> : <span className="badge">{t("Action needed")}</span>}
              </div>
            ))}
          </div>
        </div>

        {/* detail grid */}
        <div className="split-2">
          {/* policies */}
          <div className="panel">
            <div className="panel-h"><h3>{t("Policy review status")}</h3><button className="btn btn-sm btn-ghost" onClick={() => navigate("docs")}>{t("Library")}<Icon name="arrowR" size={12} /></button></div>
            <div style={{ overflowX: "auto" }}>
            <table className="tbl cmp-tbl">
              <thead><tr><th>{t("Policy")}</th><th style={{ width: 60 }}>{t("Ver.")}</th><th style={{ width: 100 }}>{t("Review by")}</th><th style={{ width: 96 }}>{t("Status")}</th></tr></thead>
              <tbody>
                {policies.map((p) => {
                  const st = polStatus(p.nextReview);
                  return (
                    <tr key={p.id}>
                      <td style={{ fontWeight: 500, fontSize: 12.5 }}>{t(p.title)}</td>
                      <td className="mono faint">{p.v}</td>
                      <td className="mono" style={{ fontSize: 11.5 }}>{p.nextReview}</td>
                      <td><span className={"badge " + st.cls}><span className="dot"></span>{st.k === "current" ? t("Current") : st.label}</span></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
            </div>
          </div>

          {/* training */}
          <div className="panel">
            <div className="panel-h"><h3>{t("IB training coverage")}</h3><span className="badge crit"><span className="dot"></span>{trGap} {t("gaps")}</span></div>
            <div style={{ overflowX: "auto" }}>
            <table className="tbl cmp-tbl">
              <thead><tr><th>{t("Subject")}</th><th>{t("Trained teacher")}</th><th style={{ width: 80 }}>{t("Expires")}</th><th style={{ width: 88 }}>{t("Status")}</th></tr></thead>
              <tbody>
                {TRAINING.map((tr, i) => {
                  const tch = tr.teacher ? DB.teacher(tr.teacher) : null;
                  const S = TR_STATUS[tr.status];
                  return (
                    <tr key={i} style={tr.status === "gap" ? { background: "var(--critical-soft)" } : {}}>
                      <td style={{ fontWeight: 500, fontSize: 12.5 }}>{tr.subj}</td>
                      <td>{tch ? <div className="row" style={{ gap: 7 }}><Avatar name={tch.name} color={tch.avatar} size={20} /><span style={{ fontSize: 12 }}>{tch.name}</span></div> : <span className="badge crit" style={{ fontWeight: 600 }}>{t("Unassigned")}</span>}</td>
                      <td className="mono faint" style={{ fontSize: 11 }}>{tr.exp}</td>
                      <td><span className={"badge " + S.cls}><span className="dot"></span>{t(S.label)}</span></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
            </div>
          </div>

          {/* coursework */}
          <div className="panel">
            <div className="panel-h"><h3>{t("Coursework completeness")}</h3><button className="btn btn-sm btn-ghost" onClick={() => navigate("coursework")}>{t("Monitor")}<Icon name="arrowR" size={12} /></button></div>
            <div className="panel-b">
              <div className="row" style={{ gap: 20, alignItems: "center" }}>
                <Donut size={108} thickness={13} center={iaPct + "%"} segments={[
                  { value: c.coursework.submitted, color: "var(--stable)" },
                  { value: c.coursework.expected - c.coursework.submitted, color: "var(--surface-2)" },
                ]} />
                <div style={{ flex: 1 }}>
                  <div className="cw-stat"><span style={{ width: 9, height: 9, borderRadius: 2, background: "var(--stable)" }}></span><span style={{ fontSize: 12.5 }}>{t("Submitted")}</span><span className="mono" style={{ marginLeft: "auto", fontWeight: 600 }}>{c.coursework.submitted}</span></div>
                  <div className="cw-stat"><span style={{ width: 9, height: 9, borderRadius: 2, background: "var(--line-2)" }}></span><span style={{ fontSize: 12.5 }}>{t("Outstanding")}</span><span className="mono" style={{ marginLeft: "auto", fontWeight: 600 }}>{c.coursework.expected - c.coursework.submitted}</span></div>
                  <div className="hr" style={{ margin: "10px 0" }}></div>
                  <div className="cw-stat"><span style={{ fontSize: 12.5, color: "var(--muted)" }}>{t("Expected (IA + EE)")}</span><span className="mono" style={{ marginLeft: "auto", fontWeight: 600 }}>{c.coursework.expected}</span></div>
                  <p className="muted" style={{ fontSize: 11, marginTop: 10, lineHeight: 1.5 }}>{t("Verification requires ≥ 95% on-time completeness. Currently")} <b style={{ color: "var(--watch)" }}>{iaPct}%</b> {t("— below threshold.")}</p>
                </div>
              </div>
            </div>
          </div>

          {/* support coverage */}
          <div className="panel">
            <div className="panel-h"><h3>{t("Support-plan coverage")}</h3><button className="btn btn-sm btn-ghost" onClick={() => navigate("ilp")}>{t("Plans")}<Icon name="arrowR" size={12} /></button></div>
            <div className="panel-b">
              <div className="row" style={{ gap: 12, marginBottom: 14 }}>
                <div className="cov-tile"><span className="mono" style={{ fontSize: 22, fontWeight: 600 }}>{c.support.identified}</span><span className="eyebrow">{t("Identified")}</span></div>
                <div className="cov-tile"><span className="mono" style={{ fontSize: 22, fontWeight: 600, color: "var(--stable)" }}>{c.support.withPlan}</span><span className="eyebrow">{t("With plan")}</span></div>
                <div className="cov-tile"><span className="mono" style={{ fontSize: 22, fontWeight: 600, color: "var(--watch)" }}>{c.support.identified - c.support.withPlan}</span><span className="eyebrow">{t("To assign")}</span></div>
              </div>
              <div className="col" style={{ gap: 8 }}>
                {DB.STUDENTS.filter((s) => s.supportTier >= 2).map((s) => (
                  <div key={s.id} className="cov-row">
                    <Avatar name={s.name} color={s.avatar} size={22} />
                    <span style={{ fontSize: 12.5, fontWeight: 500 }}>{s.name}</span>
                    <span className="muted mono" style={{ fontSize: 10.5 }}>{t("Tier")} {s.supportTier}</span>
                    <span className={"badge " + (DB.ilp(s.id) ? "stable" : "watch")} style={{ marginLeft: "auto" }}><span className="dot"></span>{DB.ilp(s.id) ? t("Plan active") : t("No plan")}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  window.SCREENS = window.SCREENS || {};
  window.SCREENS.compliance = Compliance;
})();
