/* ============================================================
   Screen: Student 360° Profile
   ============================================================ */
(function () {
  const DB = window.DB;

  const FACTORS = [
    { key: "attendance", label: "Attendance", color: "var(--info)" },
    { key: "behaviour", label: "Behaviour", color: "var(--critical)" },
    { key: "academic", label: "Academic", color: "var(--watch)" },
    { key: "coursework", label: "Coursework", color: "oklch(0.55 0.14 300)" },
    { key: "support", label: "Support", color: "var(--stable)" },
  ];
  const TL_ICON = { attendance: "attendance", behaviour: "flag", support: "ilp", coursework: "coursework", academic: "trend", integrity: "compliance" };
  const SEV_COLOR = { crit: "var(--critical)", watch: "var(--watch)", info: "var(--info)", stable: "var(--stable)" };

  function insightFor(s) {
    const sorted = [...FACTORS].filter((f) => s.factors[f.key] > 0).sort((a, b) => s.factors[b.key] - s.factors[a.key]);
    const top = sorted.slice(0, 2).map((f) => t(f.label).toLowerCase());
    const lead = top.length
      ? `${s.name.split(" ")[0]}${t("'s score of")} ${s.risk} (${t(DB.BANDS[s.band].label)}) ${t("is driven primarily by")} ${top.join(" " + t("and") + " ")}.`
      : `${s.name.split(" ")[0]} ${t("is in the")} ${t(DB.BANDS[s.band].label)} ${t("band with no material risk drivers this term.")}`;
    const actions = [];
    if (s.factors.behaviour >= 16) actions.push(t("Convene the current behaviour review before the next deadline."));
    if (s.factors.attendance >= 16) actions.push(t("Confirm parent contact and agree an attendance recovery plan."));
    if (s.factors.academic >= 14) actions.push(t("Move the weakest HL subject to Tier 2 academic support."));
    if (s.factors.coursework >= 10) actions.push(t("Verify the coursework penalty is logged and the student notified."));
    if (s.factors.support >= 6) actions.push(t("Maintain the existing Tier") + " " + s.supportTier + " " + t("check-in cadence."));
    if (!actions.length) actions.push(t("No intervention needed — re-check at the next data point."));
    return { lead, actions };
  }

  function StatPill({ label, value, tone }) {
    return (
      <div style={{ padding: "10px 14px", border: "1px solid var(--line)", borderRadius: "var(--r)", background: "var(--surface)", minWidth: 92 }}>
        <div className="eyebrow" style={{ marginBottom: 5, fontSize: 9.5 }}>{label}</div>
        <div className="mono" style={{ fontSize: 17, fontWeight: 600, color: tone || "var(--ink)" }}>{value}</div>
      </div>
    );
  }

  function StudentProfile({ route, navigate, openAssistant }) {
    const s = DB.student(route.arg);
    const [tlFilter, setTlFilter] = React.useState("all");
    const [noteOpen, setNoteOpen] = React.useState(false);
    if (!s) return <div className="screen"><div className="cmd-empty muted" style={{ padding: 60 }}>{t("Student")} “{route.arg}” {t("not found.")}</div></div>;

    const hr = DB.teacher(s.homeroom);
    const ins = insightFor(s);
    const dp = s.prog !== "Foundation";
    const curTotal = s.subjects.reduce((a, x) => a + x.grade, 0);
    const predTotal = s.subjects.reduce((a, x) => a + x.predicted, 0);
    const tl = s.timeline.filter((e) => tlFilter === "all" || e.type === tlFilter);
    const tlTypes = ["all", ...Array.from(new Set(s.timeline.map((e) => e.type)))];

    return (
      <div className="screen">
        {/* back */}
        <button className="btn btn-sm btn-ghost" style={{ marginBottom: 16, paddingLeft: 6 }} onClick={() => navigate("radar")}>
          <Icon name="chevronL" size={15} />{t("Back to Radar")}
        </button>

        {/* header */}
        <div className="panel" style={{ marginBottom: 16 }}>
          <div className="prof-head">
            <Avatar name={s.name} color={s.avatar} size={64} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="row" style={{ gap: 10, flexWrap: "wrap" }}>
                <h2 style={{ fontSize: 22 }}>{s.name}</h2>
                <BandBadge band={s.band} showRange />
                {s.ilp ? <span className="badge accent"><Icon name="ilp" size={11} />{t("ILP / SEN")}</span> : null}
              </div>
              <div className="muted" style={{ fontSize: 13, marginTop: 6 }}>
                <span className="mono">{s.id}</span> · {t("Class")} {s.cls} · {s.prog} · {t("Homeroom")} <b style={{ color: "var(--ink-2)" }}>{hr?.name}</b>
              </div>
              <div className="row" style={{ gap: 10, marginTop: 14, flexWrap: "wrap" }}>
                <StatPill label={t("Attendance")} value={s.attendance + "%"} tone={s.attendance < 85 ? "var(--critical)" : s.attendance < 92 ? "var(--watch)" : "var(--ink)"} />
                <StatPill label={t("Behaviour")} value={t(s.behaviour)} />
                <StatPill label={t("Support tier")} value={t("Tier") + " " + s.supportTier} />
                {dp ? <StatPill label={t("Predicted total")} value={predTotal + " / 42"} /> : <StatPill label={t("Programme")} value={t("Foundation")} />}
              </div>
            </div>
            <div className="prof-score">
              <RiskScore score={s.risk} size="lg" />
              <span className="eyebrow" style={{ marginTop: 8 }}>{t("Risk score")}</span>
            </div>
          </div>

          {/* explainable factor breakdown */}
          <div style={{ borderTop: "1px solid var(--line)", padding: "14px var(--pad)" }}>
            <div className="between" style={{ marginBottom: 10 }}>
              <span className="eyebrow">{t("How the score breaks down")}</span>
              <span className="muted mono" style={{ fontSize: 11 }}>Σ {s.risk} / 100</span>
            </div>
            <div style={{ display: "flex", height: 12, borderRadius: 999, overflow: "hidden", background: "var(--surface-2)", marginBottom: 12 }}>
              {FACTORS.map((f) => s.factors[f.key] ? <span key={f.key} title={t(f.label) + " +" + s.factors[f.key]} style={{ width: s.factors[f.key] + "%", background: f.color }}></span> : null)}
            </div>
            <div className="row wrap" style={{ gap: 16 }}>
              {FACTORS.map((f) => (
                <span key={f.key} className="row" style={{ gap: 7 }}>
                  <span style={{ width: 9, height: 9, borderRadius: 2, background: f.color }}></span>
                  <span style={{ fontSize: 12, fontWeight: 500 }}>{t(f.label)}</span>
                  <span className="mono" style={{ fontSize: 12, color: s.factors[f.key] ? "var(--ink)" : "var(--faint)", fontWeight: 600 }}>+{s.factors[f.key]}</span>
                </span>
              ))}
            </div>
          </div>
        </div>

        {/* main grid */}
        <div className="dash-grid">
          {/* LEFT */}
          <div className="col" style={{ gap: "var(--gap)" }}>
            {/* subjects */}
            <div className="panel">
              <div className="panel-h">
                <h3>{t("Achievement — Groups 1–6")}</h3>
                {dp ? <span className="muted mono" style={{ fontSize: 11 }}>{t("current")} {curTotal} · {t("predicted")} {predTotal} / 42</span> : <span className="badge">{t("Pre-DP")}</span>}
              </div>
              <table className="tbl">
                <thead>
                  <tr>
                    <th style={{ width: 34 }}>{t("Grp")}</th><th>{t("Subject")}</th><th style={{ width: 56 }}>{t("Level")}</th>
                    <th style={{ width: 70 }} className="num">{t("Current")}</th><th style={{ width: 88 }} className="num">{t("Predicted")}</th><th style={{ width: 56 }} className="num">{t("Trend")}</th>
                  </tr>
                </thead>
                <tbody>
                  {s.subjects.map((sub, i) => (
                    <tr key={i}>
                      <td className="mono faint">{sub.g}</td>
                      <td style={{ fontWeight: 500 }}>{sub.name}</td>
                      <td><span className={sub.level === "HL" ? "tag-hl" : "tag-sl"}>{sub.level}</span></td>
                      <td className="num"><Grade value={sub.grade} /></td>
                      <td className="num"><span className="mono" style={{ fontWeight: 600 }}>{sub.predicted}</span><span className="faint mono" style={{ fontSize: 10 }}> /7</span></td>
                      <td className="num"><TrendArrow v={sub.trend} /></td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {dp ? (
                <div className="core-row">
                  {[["TOK", s.core.tok], ["EE", s.core.ee], ["CAS", s.core.cas]].map(([k, v]) => {
                    const tone = /overdue|behind|not started/i.test(v) ? "crit" : /track/i.test(v) ? "stable" : "";
                    return (
                      <div key={k} className="core-card">
                        <div className="eyebrow">{k}</div>
                        <div className="row" style={{ gap: 6, marginTop: 6 }}>
                          <span className={"dot-sev " + tone}></span>
                          <span style={{ fontSize: 12.5, fontWeight: 500 }}>{t(v)}</span>
                        </div>
                      </div>
                    );
                  })}
                </div>
              ) : null}
            </div>

            {/* timeline */}
            <div className="panel">
              <div className="panel-h">
                <h3>{t("Unified timeline")}</h3>
                <div className="row wrap" style={{ gap: 5 }}>
                  {tlTypes.map((tp) => (
                    <button key={tp} className={"tl-filter" + (tlFilter === tp ? " on" : "")} onClick={() => setTlFilter(tp)}>
                      {tp === "all" ? t("All") : t(tp[0].toUpperCase() + tp.slice(1))}
                    </button>
                  ))}
                </div>
              </div>
              <div className="panel-b">
                <div className="timeline">
                  {tl.map((e, i) => (
                    <div key={i} className="tl-item">
                      <div className="tl-mark" style={{ color: SEV_COLOR[e.sev] || "var(--muted)" }}>
                        <Icon name={TL_ICON[e.type] || "note"} size={14} />
                      </div>
                      <div className="tl-body">
                        <div className="between" style={{ alignItems: "flex-start" }}>
                          <span style={{ fontWeight: 600, fontSize: 13 }}>{t(e.title)}</span>
                          <span className="mono faint" style={{ fontSize: 10.5, whiteSpace: "nowrap" }}>{e.date}</span>
                        </div>
                        <p className="muted" style={{ fontSize: 12, marginTop: 3, lineHeight: 1.5 }}>{t(e.detail)}</p>
                        <span className="tl-type mono">{t(e.type)}</span>
                      </div>
                    </div>
                  ))}
                  {!tl.length ? <p className="muted" style={{ fontSize: 12, padding: "8px 0" }}>{t("No")} {t(tlFilter)} {t("events recorded.")}</p> : null}
                </div>
              </div>
            </div>
          </div>

          {/* RIGHT */}
          <div className="col" style={{ gap: "var(--gap)" }}>
            {/* AI insight */}
            <div className="panel" style={{ borderColor: "var(--accent-line)" }}>
              <div className="panel-h" style={{ background: "var(--accent-soft)", borderColor: "var(--accent-line)" }}>
                <div className="row" style={{ gap: 8 }}>
                  <span className="asst-mark" style={{ width: 26, height: 26 }}><Icon name="spark" size={14} /></span>
                  <h3 style={{ color: "var(--accent-ink)" }}>{t("AI risk insight")}</h3>
                </div>
                <span className="badge accent">{t("Draft")}</span>
              </div>
              <div className="panel-b">
                <p style={{ fontSize: 13, lineHeight: 1.6 }}>{ins.lead}</p>
                <div className="eyebrow" style={{ margin: "16px 0 9px" }}>{t("Suggested next actions")}</div>
                <ul className="ai-actions">
                  {ins.actions.map((a, i) => (
                    <li key={i}><Icon name="arrowR" size={13} style={{ color: "var(--accent)", marginTop: 2 }} /><span>{a}</span></li>
                  ))}
                </ul>
                <div className="asst-src" style={{ marginTop: 14 }}>
                  <div className="eyebrow" style={{ marginBottom: 6 }}>{t("Sources")}</div>
                  <div className="asst-src-item"><Icon name="doc" size={13} /><span><b>{t("At-Risk Radar")}</b> · {t("scoring model")}</span><span className="mono faint" style={{ marginLeft: "auto", fontSize: 10 }}>{t("live")}</span></div>
                  <div className="asst-src-item"><Icon name="doc" size={13} /><span><b>{t("Record")} {s.id}</b> · {t("Term 3 timeline")}</span><span className="mono faint" style={{ marginLeft: "auto", fontSize: 10 }}>{t("live")}</span></div>
                </div>
                <div className="row" style={{ gap: 8, marginTop: 14 }}>
                  <button className="btn btn-sm btn-primary" style={{ flex: 1, justifyContent: "center" }} onClick={() => openAssistant(t("Suggest next actions for") + " " + s.name)}>
                    <Icon name="spark" size={13} />{t("Ask a follow-up")}
                  </button>
                  <button className="btn btn-sm" onClick={() => window.toast(t("Action plan approved for") + " " + s.name.split(" ")[0])}>{t("Approve plan")}</button>
                </div>
                <p className="muted" style={{ fontSize: 10.5, marginTop: 10, textAlign: "center" }}>{t("AI drafts only — a human reviews and approves.")}</p>
              </div>
            </div>

            {/* quick actions */}
            <div className="panel">
              <div className="panel-h"><h3>{t("Actions")}</h3></div>
              <div className="panel-b" style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {[["note", t("Log a pastoral note"), () => setNoteOpen(true)], ["flag", t("Open a behaviour case"), () => navigate("behaviour")], ["coursework", t("Check coursework"), () => navigate("coursework")], ["ilp", s.ilp ? t("View ILP / SEN plan") : t("Refer for support"), () => navigate("ilp")]].map(([ic, label, fn], i) => (
                  <button key={i} className="qa-btn" onClick={fn || (() => {})}>
                    <Icon name={ic} size={15} /><span>{label}</span><Icon name="chevronR" size={14} style={{ marginLeft: "auto", color: "var(--faint)" }} />
                  </button>
                ))}
              </div>
            </div>
          </div>
        </div>

        {noteOpen ? (
          <FormModal title={t("Log a pastoral note —") + " " + s.name} subtitle={t("Notes are added to the student's timeline and visible to their pastoral team.")}
            fields={[
              { k: "type", label: t("Note type"), type: "select", options: [t("Wellbeing check-in"), t("Academic concern"), t("Positive recognition"), t("Parent contact"), t("Other")] },
              { k: "note", label: t("Note"), type: "textarea", ph: t("What happened, and any follow-up needed…"), required: true },
            ]}
            submitLabel={t("Save note")} submitIcon="check"
            onClose={() => setNoteOpen(false)}
            onSubmit={() => { setNoteOpen(false); window.toast(t("Pastoral note added to timeline")); }} />
        ) : null}
      </div>
    );
  }

  window.SCREENS = window.SCREENS || {};
  window.SCREENS.student = StudentProfile;
})();
