/* ============================================================
   Screen: Director Dashboard
   ============================================================ */
(function () {
  const DB = window.DB;

  /* tiny multi-series line chart */
  function TrendChart({ series, labels, h = 150 }) {
    const w = 560, padL = 28, padB = 22, padT = 12, padR = 8;
    const iw = w - padL - padR, ih = h - padB - padT;
    const allMax = Math.max(...series.flatMap((s) => s.data));
    const max = Math.ceil(allMax / 2) * 2 + 1;
    const x = (i) => padL + (i / (labels.length - 1)) * iw;
    const y = (v) => padT + ih - (v / max) * ih;
    const gy = [0, Math.round(max / 2), max];
    return (
      <svg viewBox={`0 0 ${w} ${h}`} width="100%" style={{ display: "block" }}>
        {gy.map((g, i) => (
          <g key={i}>
            <line x1={padL} y1={y(g)} x2={w - padR} y2={y(g)} stroke="var(--line)" strokeWidth="1" />
            <text x={padL - 6} y={y(g) + 3} textAnchor="end" fontFamily="var(--font-mono)" fontSize="9" fill="var(--faint)">{g}</text>
          </g>
        ))}
        {labels.map((l, i) => (
          <text key={i} x={x(i)} y={h - 6} textAnchor="middle" fontFamily="var(--font-mono)" fontSize="9" fill="var(--faint)">{l}</text>
        ))}
        {series.map((s, si) => {
          const line = s.data.map((d, i) => (i ? "L" : "M") + x(i).toFixed(1) + " " + y(d).toFixed(1)).join(" ");
          return (
            <g key={si}>
              <path d={line + ` L${x(s.data.length - 1)} ${y(0)} L${x(0)} ${y(0)} Z`} fill={s.color} opacity="0.07" />
              <path d={line} fill="none" stroke={s.color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              {s.data.map((d, i) => <circle key={i} cx={x(i)} cy={y(d)} r="2.4" fill={s.color} />)}
            </g>
          );
        })}
      </svg>
    );
  }

  function ComplianceRow({ label, value, total, tone, note }) {
    const pct = Math.round((value / total) * 100);
    const col = tone === "bad" ? "var(--critical)" : tone === "warn" ? "var(--watch)" : "var(--stable)";
    return (
      <div style={{ padding: "11px 0", borderBottom: "1px solid var(--line)" }}>
        <div className="between" style={{ marginBottom: 8 }}>
          <span style={{ fontSize: "var(--fs-sm)", fontWeight: 500, whiteSpace: "nowrap" }}>{label}</span>
          <span className="mono" style={{ fontSize: 12 }}><b style={{ color: col }}>{value}</b><span className="faint">/{total}</span></span>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ flex: 1, height: 5, background: "var(--surface-2)", borderRadius: 999, overflow: "hidden" }}>
            <span style={{ display: "block", width: pct + "%", height: "100%", background: col, borderRadius: 999 }}></span>
          </span>
          <span className="muted" style={{ fontSize: 11, minWidth: 96, textAlign: "right" }}>{note}</span>
        </div>
      </div>
    );
  }

  function Dashboard({ role, openAssistant }) {
    const teacher = role === "teacher";
    const scope = teacher ? DB.STUDENTS.filter((s) => s.cls === "C") : DB.STUDENTS;
    const crit = scope.filter((s) => s.band === "critical");
    const watch = scope.filter((s) => s.band === "watch");
    const avgAtt = Math.round(scope.reduce((a, s) => a + s.attendance, 0) / scope.length);
    const support = scope.filter((s) => s.supportTier >= 2).length;
    const shortlist = [...scope].sort((a, b) => b.risk - a.risk).slice(0, 6);
    const classes = teacher ? DB.classRisk.filter((c) => c.cls === "C") : DB.classRisk;

    return (
      <div className="screen">
        {/* header line */}
        <div className="between" style={{ marginBottom: 20 }}>
          <div>
            <h2 style={{ fontSize: 19 }}>{teacher ? t("My classes — Class C") : t("Whole-school health")}</h2>
            <p className="muted" style={{ fontSize: 13, marginTop: 4 }}>
              {teacher ? t("Your homeroom and subject cohort, Term 3 · Week 8.") : t("Live across 4 classes and 3 programmes · Term 3, Week 8 of 11.")}
            </p>
          </div>
          <div className="row" style={{ gap: 8 }}>
            <button className="btn btn-sm" onClick={() => openAssistant(t("Summarise the school's risk position"))}>
              <Icon name="spark" size={14} />{t("Summarise position")}
            </button>
            <button className="btn btn-sm" onClick={() => window.toast(t("Board brief exported (PDF)"))}><Icon name="download" size={14} />{t("Export brief")}</button>
          </div>
        </div>

        {/* KPIs */}
        <div className={"grid " + (teacher ? "cards-4" : "cards-5")} style={{ marginBottom: 16 }}>
          <KPI label={t("Students at risk")} value={crit.length + watch.length} unit={"/ " + scope.length}
            accent="var(--critical)" delta="2" deltaDir="bad" sub={crit.length + " " + t("critical") + " · " + watch.length + " " + t("watch")} onClick={() => navigate("radar")} />
          <KPI label={t("Avg attendance")} value={avgAtt} unit="%" delta="1.2%" deltaDir="bad"
            sub={t("Whole-school target 92%")} onClick={() => navigate("attendance")} />
          <KPI label={t("Open behaviour cases")} value={teacher ? 1 : DB.stats.openCases} delta="1" deltaDir="bad"
            sub={t("2 awaiting sign-off")} onClick={() => navigate("behaviour")} />
          <KPI label={t("IA / EE completeness")} value={DB.stats.iaComplete} unit="%" delta="3%" deltaDir="good"
            sub={DB.compliance.coursework.submitted + " " + t("of") + " " + DB.compliance.coursework.expected + " " + t("submitted")} onClick={() => navigate("coursework")} />
          {!teacher ? (
            <KPI label={t("Active support plans")} value={support} sub={support + " " + t("on Tier 2+ · ILP/SEN")} onClick={() => navigate("ilp")} />
          ) : null}
        </div>

        {/* main grid */}
        <div className="dash-grid">
          {/* LEFT */}
          <div className="col" style={{ gap: "var(--gap)" }}>
            {/* needs attention */}
            <div className="panel">
              <div className="panel-h">
                <div className="row" style={{ gap: 9 }}>
                  <Icon name="alert" size={16} style={{ color: "var(--critical)" }} />
                  <h3>{t("Needs your attention")}</h3>
                  <span className="badge crit"><span className="dot"></span>{crit.length} {t("critical")}</span>
                </div>
                <button className="btn btn-sm btn-ghost" onClick={() => navigate("radar")}>{t("Open Radar")}<Icon name="arrowR" size={13} /></button>
              </div>
              <div>
                {shortlist.map((s) => (
                  <button key={s.id} className="attn-row" onClick={() => navigate("student/" + s.id)}>
                    <RiskScore score={s.risk} size="md" />
                    <Avatar name={s.name} color={s.avatar} size={30} />
                    <div style={{ minWidth: 0, flex: "0 0 150px" }}>
                      <div style={{ fontWeight: 600, fontSize: 13 }}>{s.name}</div>
                      <div className="muted mono" style={{ fontSize: 10.5 }}>{s.cls} · {s.prog} · {s.id}</div>
                    </div>
                    <div className="attn-reasons">
                      {s.reasons.slice(0, 2).map((r, i) => (
                        <span key={i} className="reason-pill">{t(r)}</span>
                      ))}
                      {s.reasons.length > 2 ? <span className="reason-pill more">+{s.reasons.length - 2}</span> : null}
                    </div>
                    <Icon name="chevronR" size={16} style={{ color: "var(--faint)", marginLeft: "auto" }} />
                  </button>
                ))}
              </div>
            </div>

            {/* term trend */}
            <div className="panel">
              <div className="panel-h">
                <h3>{t("Term risk trend")}</h3>
                <div className="row" style={{ gap: 14 }}>
                  <span className="legend"><i style={{ background: "var(--critical)" }}></i>{t("Critical")}</span>
                  <span className="legend"><i style={{ background: "var(--watch)" }}></i>{t("Watch")}</span>
                </div>
              </div>
              <div className="panel-b">
                <TrendChart labels={DB.trend.map((t) => t.wk)}
                  series={[
                    { color: "var(--critical)", data: DB.trend.map((t) => t.critical) },
                    { color: "var(--watch)", data: DB.trend.map((t) => t.watch) },
                  ]} />
                <p className="muted" style={{ fontSize: 11.5, marginTop: 6 }}>{t("Critical-band students up 3 since Week 1 — driven by behaviour escalations and two IA deadlines passing in Week 6.")}</p>
              </div>
            </div>
          </div>

          {/* RIGHT */}
          <div className="col" style={{ gap: "var(--gap)" }}>
            {/* risk by class */}
            <div className="panel">
              <div className="panel-h"><h3>{t("Risk by class")}</h3><span className="eyebrow">{t("avg score")}</span></div>
              <div className="panel-b" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                {classes.map((c) => (
                  <div key={c.cls}>
                    <div className="between" style={{ marginBottom: 6 }}>
                      <span style={{ fontSize: 13, fontWeight: 600 }}>{t("Class")} {c.cls}<span className="muted mono" style={{ fontWeight: 400, fontSize: 11, marginLeft: 6 }}>{c.n} {t("students")}</span></span>
                      <RiskScore score={c.avg} size="sm" />
                    </div>
                    <StackBar parts={[
                      { label: t("Critical"), value: c.critical, color: "var(--critical)" },
                      { label: t("Watch"), value: c.watch, color: "var(--watch)" },
                      { label: t("Monitor"), value: c.monitor, color: "var(--monitor)" },
                      { label: t("Stable"), value: c.stable, color: "var(--stable)" },
                    ]} />
                  </div>
                ))}
                <div className="row legend-row">
                  {["Critical", "Watch", "Monitor", "Stable"].map((b, i) => (
                    <span key={b} className="legend"><i style={{ background: ["var(--critical)", "var(--watch)", "var(--monitor)", "var(--stable)"][i] }}></i>{t(b)}</span>
                  ))}
                </div>
              </div>
            </div>

            {/* compliance summary */}
            {!teacher ? (
              <div className="panel">
                <div className="panel-h">
                  <div className="row" style={{ gap: 8 }}><Icon name="compliance" size={16} style={{ color: "var(--watch)" }} /><h3>{t("IB compliance")}</h3></div>
                  <span className="badge watch"><span className="dot"></span>{t("Amber")}</span>
                </div>
                <div className="panel-b" style={{ paddingTop: 4 }}>
                  <ComplianceRow label={t("Policies in review date")} value={DB.compliance.policies.current} total={DB.compliance.policies.total} tone="warn" note={t("1 overdue")} />
                  <ComplianceRow label={t("Training coverage")} value={DB.compliance.training.current} total={DB.compliance.training.total} tone="warn" note={t("2 gaps")} />
                  <ComplianceRow label={t("Coursework complete")} value={DB.compliance.coursework.submitted} total={DB.compliance.coursework.expected} tone="ok" note={DB.stats.iaComplete + "%"} />
                  <ComplianceRow label={t("Support coverage")} value={DB.compliance.support.withPlan} total={DB.compliance.support.identified} tone="ok" note={t("1 to assign")} />
                  <button className="btn btn-sm" style={{ width: "100%", justifyContent: "center", marginTop: 12 }} onClick={() => navigate("compliance")}>
                    {t("Open Compliance Cockpit")}<Icon name="arrowR" size={13} />
                  </button>
                </div>
              </div>
            ) : (
              <div className="panel">
                <div className="panel-h"><h3>{t("My IB training")}</h3><span className="badge stable"><span className="dot"></span>{t("Current")}</span></div>
                <div className="panel-b">
                  <p className="muted" style={{ fontSize: 12.5, lineHeight: 1.6 }}>{t("Chemistry HL/SL training is current to Aug 2027. No action required. The full compliance board is available to leadership.")}</p>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  }

  window.SCREENS = window.SCREENS || {};
  window.SCREENS.dashboard = Dashboard;
})();
