/* ============================================================
   Screen: At-Risk Radar (headline)
   ============================================================ */
(function () {
  const DB = window.DB;

  const REASON_CATS = {
    attendance: { label: "Attendance", color: "var(--info)" },
    behaviour:  { label: "Behaviour", color: "var(--critical)" },
    academic:   { label: "Academic", color: "var(--watch)" },
    coursework: { label: "Coursework", color: "oklch(0.55 0.14 300)" },
    support:    { label: "Support", color: "var(--stable)" },
  };

  function reasonTags(s) {
    const f = s.factors, out = [];
    if (f.attendance > 6) out.push("attendance");
    if (f.behaviour > 0) out.push("behaviour");
    if (f.academic > 9) out.push("academic");
    if (f.coursework > 0) out.push("coursework");
    if (f.support > 0) out.push("support");
    return out;
  }
  // deterministic small trend delta per student
  function delta(s) {
    const n = parseInt(s.id.replace(/\D/g, ""), 10);
    const d = ((n * 7) % 11) - 4; // -4..+6
    return s.band === "stable" ? Math.min(0, d) : d;
  }

  function Radar({ role, navigate }) {
    const teacher = role === "teacher";
    const base = teacher ? DB.STUDENTS.filter((s) => s.cls === "C") : DB.STUDENTS;

    const [cls, setCls] = React.useState("all");
    const [prog, setProg] = React.useState("all");
    const [bands, setBands] = React.useState([]); // multi
    const [reasons, setReasons] = React.useState([]); // multi
    const [q, setQ] = React.useState("");
    const [sort, setSort] = React.useState("risk-desc");

    const toggle = (arr, set, v) => set(arr.includes(v) ? arr.filter((x) => x !== v) : [...arr, v]);

    let rows = base.filter((s) => {
      if (cls !== "all" && s.cls !== cls) return false;
      if (prog !== "all" && s.prog !== prog) return false;
      if (bands.length && !bands.includes(s.band)) return false;
      if (reasons.length && !reasonTags(s).some((r) => reasons.includes(r))) return false;
      if (q && !(s.name.toLowerCase().includes(q.toLowerCase()) || s.id.toLowerCase().includes(q.toLowerCase()))) return false;
      return true;
    });
    rows.sort((a, b) => {
      if (sort === "risk-desc") return b.risk - a.risk;
      if (sort === "risk-asc") return a.risk - b.risk;
      if (sort === "att-asc") return a.attendance - b.attendance;
      if (sort === "name") return a.name.localeCompare(b.name);
      return 0;
    });

    const dist = ["critical", "watch", "monitor", "stable"].map((b) => ({
      band: b, n: base.filter((s) => s.band === b).length,
    }));
    const totalBase = base.length;
    const active = cls !== "all" || prog !== "all" || bands.length || reasons.length || q;

    return (
      <div className="screen">
        {/* intro */}
        <div className="between" style={{ marginBottom: 18 }}>
          <div>
            <h2 style={{ fontSize: 19 }}>{t("At-Risk Radar")}</h2>
            <p className="muted" style={{ fontSize: 13, marginTop: 4 }}>
              {t("One fused risk score per student — attendance, behaviour, achievement, coursework and support history.")} {teacher ? t("Showing your Class C cohort.") : t("Every student, every class.")}
            </p>
          </div>
          <div className="row" style={{ gap: 8 }}>
            <button className="btn btn-sm" onClick={() => window.toast(t("At-Risk Radar list exported (CSV)"))}><Icon name="download" size={14} />{t("Export list")}</button>
          </div>
        </div>

        {/* distribution bar */}
        <div className="panel" style={{ marginBottom: 16 }}>
          <div className="radar-dist">
            {dist.map((d) => {
              const on = bands.includes(d.band);
              const b = DB.BANDS[d.band];
              const col = { critical: "var(--critical)", watch: "var(--watch)", monitor: "var(--monitor)", stable: "var(--stable)" }[d.band];
              return (
                <button key={d.band} className={"dist-cell" + (on ? " on" : "")} onClick={() => toggle(bands, setBands, d.band)}>
                  <div className="row" style={{ gap: 8, marginBottom: 10 }}>
                    <span style={{ width: 10, height: 10, borderRadius: 3, background: col }}></span>
                    <span style={{ fontWeight: 600, fontSize: 13 }}>{t(b.label)}</span>
                    <span className="mono faint" style={{ fontSize: 11 }}>{b.range}</span>
                  </div>
                  <div className="row" style={{ alignItems: "baseline", gap: 6 }}>
                    <span className="mono" style={{ fontSize: 28, fontWeight: 600, color: col }}>{d.n}</span>
                    <span className="muted" style={{ fontSize: 11 }}>{Math.round((d.n / totalBase) * 100)}% {t("of cohort")}</span>
                  </div>
                  <div style={{ marginTop: 10, height: 4, background: "var(--surface-2)", borderRadius: 999, overflow: "hidden" }}>
                    <span style={{ display: "block", height: "100%", width: (d.n / totalBase) * 100 + "%", background: col }}></span>
                  </div>
                </button>
              );
            })}
          </div>
        </div>

        {/* toolbar */}
        <div className="toolbar">
          <div className="tb-input">
            <Icon name="search" size={15} />
            <input value={q} onChange={(e) => setQ(e.target.value)} placeholder={t("Find a student by name or ID…")} />
          </div>
          <div className="seg">
            {["all", "A", "B", "C", "D"].filter((c) => !teacher || c === "all" || c === "C").map((c) => (
              <button key={c} className={cls === c ? "on" : ""} onClick={() => setCls(c)}>{c === "all" ? t("All classes") : t("Class") + " " + c}</button>
            ))}
          </div>
          <select className="input" style={{ width: "auto", height: 32 }} value={prog} onChange={(e) => setProg(e.target.value)}>
            <option value="all">{t("All programmes")}</option>
            <option value="Foundation">{t("Foundation")}</option><option>DP1</option><option>DP2</option>
          </select>
          <div style={{ marginLeft: "auto" }} className="row">
            <span className="muted mono" style={{ fontSize: 11 }}>{rows.length} {t("students")}</span>
            <select className="input" style={{ width: "auto", height: 32 }} value={sort} onChange={(e) => setSort(e.target.value)}>
              <option value="risk-desc">{t("Risk: high → low")}</option>
              <option value="risk-asc">{t("Risk: low → high")}</option>
              <option value="att-asc">{t("Attendance: low → high")}</option>
              <option value="name">{t("Name A–Z")}</option>
            </select>
          </div>
        </div>

        {/* reason chips */}
        <div className="row wrap" style={{ gap: 8, marginBottom: 14 }}>
          <span className="eyebrow" style={{ marginRight: 2 }}>{t("Flagged for")}</span>
          {Object.entries(REASON_CATS).map(([k, v]) => {
            const on = reasons.includes(k);
            return (
              <button key={k} className={"chip-filter" + (on ? " on" : "")} onClick={() => toggle(reasons, setReasons, k)}>
                <span style={{ width: 7, height: 7, borderRadius: "50%", background: v.color }}></span>{t(v.label)}
              </button>
            );
          })}
          {active ? (
            <button className="chip-filter" style={{ borderStyle: "dashed" }}
              onClick={() => { setCls("all"); setProg("all"); setBands([]); setReasons([]); setQ(""); }}>
              <Icon name="close" size={12} />{t("Clear all")}
            </button>
          ) : null}
        </div>

        {/* table */}
        <div className="panel" style={{ overflow: "hidden" }}>
          <div style={{ overflowX: "auto" }}>
            <table className="tbl radar-tbl">
              <thead>
                <tr>
                  <th style={{ width: 40 }}>#</th>
                  <th style={{ width: 150 }}>{t("Risk")}</th>
                  <th style={{ width: 180 }}>{t("Student")}</th>
                  <th style={{ width: 96 }}>{t("Class")}</th>
                  <th style={{ width: 92 }} className="num">{t("Attend.")}</th>
                  <th style={{ width: 120 }}>{t("Behaviour")}</th>
                  <th>{t("Why flagged")}</th>
                  <th style={{ width: 64 }} className="num">{t("Trend")}</th>
                  <th style={{ width: 36 }}></th>
                </tr>
              </thead>
              <tbody>
                {rows.map((s, i) => {
                  const d = delta(s);
                  const bcls = { "Red Report": "crit", "Behaviour Contract": "crit", "Yellow Report": "watch", "Clear": "stable" }[s.behaviour] || "";
                  return (
                    <tr key={s.id} className="clickable" onClick={() => navigate("student/" + s.id)}>
                      <td className="mono faint">{i + 1}</td>
                      <td>
                        <div className="row" style={{ gap: 9 }}>
                          <RiskScore score={s.risk} size="sm" />
                          <span style={{ flex: 1, maxWidth: 64 }}><RiskBar score={s.risk} /></span>
                        </div>
                      </td>
                      <td>
                        <div className="row" style={{ gap: 9 }}>
                          <Avatar name={s.name} color={s.avatar} size={26} />
                          <div style={{ minWidth: 0 }}>
                            <div style={{ fontWeight: 600, whiteSpace: "nowrap" }}>{s.name}</div>
                            <div className="muted mono" style={{ fontSize: 10, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", maxWidth: 150 }}>{s.id} · HR {DB.teacher(s.homeroom)?.name}</div>
                          </div>
                        </div>
                      </td>
                      <td style={{ whiteSpace: "nowrap" }}><span className="mono" style={{ fontSize: 12 }}>{s.cls}</span> <span className="muted" style={{ fontSize: 11 }}>· {s.prog}</span></td>
                      <td className="num" style={{ color: s.attendance < 85 ? "var(--critical)" : s.attendance < 92 ? "var(--watch)" : "var(--ink-2)", fontWeight: 600 }}>{s.attendance}%</td>
                      <td>{s.behaviour === "Clear" ? <span className="muted" style={{ fontSize: 12 }}>{t("Clear")}</span> : <span className={"badge " + bcls}><span className="dot"></span>{t(s.behaviour)}</span>}</td>
                      <td>
                        <div className="row" style={{ gap: 5 }}>
                          {reasonTags(s).slice(0, 4).map((r) => (
                            <span key={r} className="flag-tag" title={t(REASON_CATS[r].label)}>
                              <span style={{ width: 6, height: 6, borderRadius: "50%", background: REASON_CATS[r].color }}></span>
                              {t(REASON_CATS[r].label)}
                            </span>
                          ))}
                          {!reasonTags(s).length ? <span className="faint" style={{ fontSize: 11 }}>{t("No active flags")}</span> : null}
                        </div>
                      </td>
                      <td className="num"><TrendArrow v={d} /></td>
                      <td><Icon name="chevronR" size={15} style={{ color: "var(--faint)" }} /></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
          {!rows.length ? <div className="cmd-empty muted" style={{ padding: 40 }}>{t("No students match these filters.")}</div> : null}
        </div>
      </div>
    );
  }

  window.SCREENS = window.SCREENS || {};
  window.SCREENS.radar = Radar;
})();
