/* ============================================================
   Screen: IA / EE Submission Monitor
   ============================================================ */
(function () {
  const DB = window.DB;
  const TODAY = "2026-06-04";
  const dayms = 86400000;
  const days = (a, b) => Math.round((new Date(b) - new Date(a)) / dayms);

  function evaluate(sub) {
    const eff = sub.extension ? sub.extension.to : sub.deadline;
    if (sub.submitted) {
      const late = Math.max(0, days(eff, sub.submitted));
      if (late === 0) return { status: "ontime", late: 0, penalty: 0 };
      if (late <= 3) return { status: "late", late, penalty: late * 5 };
      return { status: "voided", late, penalty: 100 };
    }
    const overdue = days(eff, TODAY);
    if (sub.extension) return { status: "extension", late: 0, penalty: 0 };
    if (overdue > 0) return { status: "missing", late: overdue, penalty: null };
    return { status: "pending", late: 0, penalty: 0, dueIn: -overdue };
  }
  const STATUS = {
    ontime:    { label: "On time", cls: "stable" },
    late:      { label: "Late", cls: "watch" },
    voided:    { label: "Voided", cls: "crit" },
    missing:   { label: "Missing", cls: "crit" },
    pending:   { label: "Upcoming", cls: "" },
    extension: { label: "Extension", cls: "accent" },
  };

  function Coursework({ role, navigate }) {
    const teacher = role === "teacher";
    const all = DB.SUBMISSIONS.map((s) => ({ ...s, ev: evaluate(s) }))
      .filter((s) => !teacher || s.subject.includes("Chemistry"));
    const [type, setType] = React.useState("all");
    const [status, setStatus] = React.useState("all");
    const [q, setQ] = React.useState("");

    let rows = all.filter((s) => {
      if (type !== "all" && s.type !== type) return false;
      if (status !== "all" && s.ev.status !== status) return false;
      if (q) { const st = DB.student(s.studentId); if (!(st.name.toLowerCase().includes(q.toLowerCase()) || s.subject.toLowerCase().includes(q.toLowerCase()))) return false; }
      return true;
    });
    const order = { missing: 0, voided: 1, late: 2, extension: 3, pending: 4, ontime: 5 };
    rows.sort((a, b) => order[a.ev.status] - order[b.ev.status] || new Date(a.deadline) - new Date(b.deadline));

    const onTime = all.filter((s) => s.ev.status === "ontime").length;
    const submitted = all.filter((s) => s.submitted).length;
    const lateN = all.filter((s) => s.ev.status === "late" || s.ev.status === "voided").length;
    const missing = all.filter((s) => s.ev.status === "missing").length;
    const exts = all.filter((s) => s.ev.status === "extension").length;
    const actionList = all.filter((s) => ["missing", "voided", "late"].includes(s.ev.status))
      .sort((a, b) => order[a.ev.status] - order[b.ev.status]);

    const penaltyText = (ev) => {
      if (ev.status === "late") return "−" + ev.penalty + "%";
      if (ev.status === "voided") return "0 · " + t("voided");
      return "—";
    };

    return (
      <div className="screen">
        <div className="between" style={{ marginBottom: 16 }}>
          <div>
            <h2 style={{ fontSize: 19 }}>{t("IA / EE Submission Monitor")}</h2>
            <p className="muted" style={{ fontSize: 13, marginTop: 4 }}>{t("Internal Assessment & Extended Essay coursework — deadlines, submissions and auto-calculated penalties.")}</p>
          </div>
          <button className="btn btn-sm" onClick={() => window.toast(t("Coursework report exported (CSV)"))}><Icon name="download" size={14} />{t("Export")}</button>
        </div>

        {/* KPIs */}
        <div className="grid cards-4" style={{ marginBottom: 16 }}>
          <KPI label={t("On-time rate")} value={Math.round((onTime / all.length) * 100)} unit="%" accent="var(--stable)" sub={onTime + " " + t("of") + " " + all.length + " " + t("pieces")} />
          <KPI label={t("Late / penalised")} value={lateN} accent={lateN ? "var(--watch)" : "var(--ink)"} sub={t("penalty applied")} onClick={() => setStatus("late")} />
          <KPI label={t("Missing")} value={missing} accent={missing ? "var(--critical)" : "var(--ink)"} sub={t("past deadline")} onClick={() => setStatus("missing")} />
          <KPI label={t("Extensions")} value={exts} sub={t("approved")} onClick={() => setStatus("extension")} />
        </div>

        {/* action list */}
        {actionList.length ? (
          <div className="panel" style={{ marginBottom: 16, borderColor: "var(--critical-line)" }}>
            <div className="panel-h" style={{ background: "var(--critical-soft)", borderColor: "var(--critical-line)" }}>
              <div className="row" style={{ gap: 8 }}><Icon name="alert" size={15} style={{ color: "var(--critical)" }} /><h3>{t("Late & missing — needs action")}</h3></div>
              <span className="badge crit"><span className="dot"></span>{actionList.length}</span>
            </div>
            <div>
              {actionList.map((s) => {
                const st = DB.student(s.studentId);
                return (
                  <div key={s.id} className="action-row">
                    <span className="mx-status" style={{ flex: "0 0 108px", display: "flex" }}><span className={"badge " + STATUS[s.ev.status].cls} style={{ whiteSpace: "nowrap" }}>{t(STATUS[s.ev.status].label)}</span></span>
                    <button className="mx-name" style={{ flex: "0 0 160px" }} onClick={() => navigate("student/" + st.id)}>
                      <Avatar name={st.name} color={st.avatar} size={24} />
                      <span><span style={{ display: "block", fontWeight: 600, fontSize: 12.5 }}>{st.name}</span><span className="muted mono" style={{ fontSize: 9.5 }}>{st.cls}</span></span>
                    </button>
                    <span className="mx-subject" style={{ flex: 1, fontSize: 12.5 }}><b>{s.type}</b> · {s.subject} <span className={s.level === "HL" ? "tag-hl" : "tag-sl"}>{s.level}</span></span>
                    <span className="muted mono mx-late" style={{ fontSize: 11.5 }}>{s.ev.status === "missing" ? s.ev.late + "d " + t("overdue") : s.ev.status === "voided" ? s.ev.late + "d " + t("late") + " · 0" : "−" + s.ev.penalty + "%"}</span>
                    <button className="btn btn-sm mx-open" onClick={() => navigate("student/" + st.id)}>{t("Open")}</button>
                  </div>
                );
              })}
            </div>
          </div>
        ) : null}

        {/* toolbar */}
        <div className="toolbar">
          <div className="seg">
            {["all", "IA", "EE"].map((tp) => <button key={tp} className={type === tp ? "on" : ""} onClick={() => setType(tp)}>{tp === "all" ? t("All types") : tp}</button>)}
          </div>
          <div className="row wrap" style={{ gap: 6 }}>
            {["all", "missing", "late", "voided", "extension", "ontime", "pending"].map((s) => (
              <button key={s} className={"chip-filter" + (status === s ? " on" : "")} onClick={() => setStatus(s)}>{s === "all" ? t("All status") : t(STATUS[s].label)}</button>
            ))}
          </div>
          <div className="tb-input" style={{ marginLeft: "auto" }}>
            <Icon name="search" size={15} />
            <input value={q} onChange={(e) => setQ(e.target.value)} placeholder={t("Student or subject…")} />
          </div>
        </div>

        {/* rule note */}
        <div className="rule-note">
          <Icon name="compliance" size={14} />
          <span>{t("Late penalty applies automatically:")} <b>{t("5% per day, capped at 3 days (−15%)")}</b>. {t("Beyond 3 days the piece scores")} <b>{t("zero")}</b>, {t("unless an extension was approved in advance.")}</span>
        </div>

        {/* table */}
        <div className="panel" style={{ overflow: "hidden" }}>
          <div style={{ overflowX: "auto" }}>
            <table className="tbl cw-tbl">
              <thead>
                <tr>
                  <th style={{ width: 150 }}>{t("Student")}</th>
                  <th style={{ width: 50 }}>{t("Type")}</th>
                  <th>{t("Subject")}</th>
                  <th style={{ width: 100 }}>{t("Deadline")}</th>
                  <th style={{ width: 100 }}>{t("Submitted")}</th>
                  <th style={{ width: 76 }} className="num">{t("Days late")}</th>
                  <th style={{ width: 92 }} className="num">{t("Penalty")}</th>
                  <th style={{ width: 150 }}>{t("Status")}</th>
                </tr>
              </thead>
              <tbody>
                {rows.map((s) => {
                  const st = DB.student(s.studentId);
                  const ev = s.ev;
                  return (
                    <tr key={s.id} className="clickable" onClick={() => navigate("student/" + st.id)}>
                      <td>
                        <div className="row" style={{ gap: 8 }}>
                          <Avatar name={st.name} color={st.avatar} size={22} />
                          <span style={{ fontWeight: 500, fontSize: 12.5, whiteSpace: "nowrap" }}>{st.name}</span>
                        </div>
                      </td>
                      <td><span className={"cw-type " + s.type}>{s.type}</span></td>
                      <td style={{ whiteSpace: "nowrap" }}>{s.subject} <span className={s.level === "HL" ? "tag-hl" : "tag-sl"}>{s.level}</span></td>
                      <td className="mono" style={{ fontSize: 11.5, color: ev.status === "extension" ? "var(--faint)" : "var(--ink-2)", textDecoration: ev.status === "extension" ? "line-through" : "none" }}>{s.deadline}</td>
                      <td className="mono" style={{ fontSize: 11.5 }}>{s.submitted || <span className="faint">—</span>}</td>
                      <td className="num" style={{ color: ev.late > 3 ? "var(--critical)" : ev.late ? "oklch(0.5 0.15 55)" : "var(--faint)", fontWeight: ev.late ? 600 : 400 }}>{ev.status === "missing" ? ev.late + "d" : ev.late || "—"}</td>
                      <td className="num" style={{ color: ev.status === "late" ? "oklch(0.5 0.15 55)" : ev.status === "voided" ? "var(--critical)" : "var(--faint)", fontWeight: ev.penalty ? 600 : 400 }}>{penaltyText(ev)}</td>
                      <td>
                        <div className="row" style={{ gap: 7 }}>
                          <span className={"badge " + STATUS[ev.status].cls}><span className="dot"></span>{t(STATUS[ev.status].label)}</span>
                          {ev.status === "extension" ? <span className="mono faint" style={{ fontSize: 10 }}>→ {s.extension.to}</span> : null}
                          {ev.status === "pending" ? <span className="mono faint" style={{ fontSize: 10 }}>{ev.dueIn}d</span> : null}
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          {!rows.length ? <div className="cmd-empty muted" style={{ padding: 40 }}>{t("No coursework matches these filters.")}</div> : null}
        </div>
      </div>
    );
  }

  window.SCREENS = window.SCREENS || {};
  window.SCREENS.coursework = Coursework;
})();
