/* ============================================================
   Screen: Behaviour Pipeline
   ============================================================ */
(function () {
  const DB = window.DB;
  const STAGES = [
    { key: "Yellow", label: "Yellow Report", color: "var(--monitor)" },
    { key: "Red", label: "Red Report", color: "var(--critical)" },
    { key: "Contract", label: "Behaviour Contract", color: "oklch(0.55 0.14 300)" },
    { key: "Suspension", label: "Suspension", color: "var(--ink)" },
  ];
  const STAGE_ORDER = ["Yellow", "Red", "Contract", "Suspension"];

  function metSummary(rc) {
    let met = 0, total = 0;
    rc.forEach((d) => d.lessons.forEach((l) => { if (l.met !== null) { total++; if (l.met) met++; } }));
    return { met, total };
  }

  function CaseCard({ c, onOpen }) {
    const s = DB.student(c.studentId);
    return (
      <button className="case-card" onClick={() => onOpen(c.id)}>
        <div className="row" style={{ gap: 9, marginBottom: 10 }}>
          <Avatar name={s.name} color={s.avatar} size={28} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontWeight: 600, fontSize: 13, whiteSpace: "nowrap" }}>{s.name}</div>
            <div className="muted mono" style={{ fontSize: 10 }}>{s.cls} · {c.id}</div>
          </div>
          <RiskScore score={s.risk} size="sm" />
        </div>
        <p className="muted" style={{ fontSize: 11.5, lineHeight: 1.45, marginBottom: 10 }}>{t(c.reason)}</p>
        <div className="case-meta">
          <span className="cm"><Icon name="clock" size={12} />{c.daysInStage}{t("d in stage")}</span>
          <span className={"cm" + (c.reviewOverdue ? " bad" : "")}>
            <Icon name="attendance" size={12} />{c.reviewOverdue ? t("Review overdue") : t("Due") + " " + c.reviewDue.slice(5)}
          </span>
        </div>
        <div className="case-foot">
          <span className={"chip-status " + (c.parentNotified === "sent" ? "ok" : "warn")} title={t("Parent notification")}>
            <Icon name={c.parentNotified === "sent" ? "check" : "clock"} size={11} />{t("Parent")}
          </span>
          {c.signOff !== "n/a" ? (
            <span className={"chip-status " + (c.signOff === "approved" ? "ok" : "warn")} title={t("Academic Director sign-off")}>
              <Icon name={c.signOff === "approved" ? "check" : "clock"} size={11} />{t("AD sign-off")}
            </span>
          ) : null}
        </div>
      </button>
    );
  }

  function Stepper({ stage }) {
    const idx = STAGE_ORDER.indexOf(stage);
    return (
      <div className="stepper">
        {STAGES.map((st, i) => (
          <React.Fragment key={st.key}>
            <div className={"step" + (i < idx ? " past" : i === idx ? " cur" : "")} style={i === idx ? { "--sc": st.color } : {}}>
              <span className="step-dot"></span>
              <span className="step-label">{t(st.label)}</span>
            </div>
            {i < STAGES.length - 1 ? <span className={"step-line" + (i < idx ? " past" : "")}></span> : null}
          </React.Fragment>
        ))}
      </div>
    );
  }

  function CaseDrawer({ caseId, role, onClose, navigate }) {
    const c = caseId ? DB.case(caseId) : null;
    const s = c ? DB.student(c.studentId) : null;
    const ms = c ? metSummary(c.reportCard) : null;
    const periods = c && c.reportCard.length ? c.reportCard[0].lessons.map((l) => l.p) : [];
    const comments = c ? c.reportCard.flatMap((d) => d.lessons.filter((l) => l.comment).map((l) => ({ day: d.day, p: l.p, subj: l.subj, comment: l.comment, met: l.met }))) : [];

    return (
      <div className={"drawer" + (c ? " open" : "")}>
        <div className="drawer-scrim" onClick={onClose}></div>
        <div className="drawer-panel">
          {c ? (
            <React.Fragment>
              <div className="drawer-h">
                <div>
                  <span className="eyebrow">{c.id} · {t("Behaviour case")}</span>
                  <button className="link-name" onClick={() => { onClose(); navigate("student/" + s.id); }}>
                    <Avatar name={s.name} color={s.avatar} size={24} /><h3>{s.name}</h3><Icon name="external" size={13} />
                  </button>
                </div>
                <button className="icon-btn" onClick={onClose}><Icon name="close" size={18} /></button>
              </div>

              <div className="drawer-body scroll-y">
                <Stepper stage={c.stage} />

                <div className="case-grid">
                  {[[t("Opened"), c.opened, false], [t("Time in stage"), c.daysInStage + " " + t("days"), false], [t("Review due"), c.reviewDue + (c.reviewOverdue ? " · " + t("overdue") : ""), c.reviewOverdue],
                    [t("Parent notified"), c.parentNotified === "sent" ? t("Sent") + " " + (c.parentDate || "") : t("Pending"), c.parentNotified !== "sent"],
                    [t("AD sign-off"), c.signOff === "n/a" ? t("Not required") : c.signOff === "approved" ? t("Approved") : t("Pending"), c.signOff === "pending"],
                    [t("Owner"), DB.teacher(c.owner)?.name, false]].map(([k, v, flag], i) => (
                    <div key={i} className="case-cell">
                      <div className="eyebrow" style={{ fontSize: 9 }}>{k}</div>
                      <div style={{ fontSize: 13, fontWeight: 500, marginTop: 4, color: flag ? "var(--critical)" : "var(--ink)" }}>{v}</div>
                    </div>
                  ))}
                </div>

                <div className="case-target">
                  <Icon name="pin" size={14} style={{ color: "var(--accent)" }} />
                  <div><span className="eyebrow">{t("Daily target")}</span><div style={{ fontSize: 13, marginTop: 2 }}>{t(c.target)}</div></div>
                </div>

                {role === "director" && c.signOff === "pending" ? (
                  <div className="signoff-bar">
                    <span style={{ fontSize: 12.5 }}><b>{t("Academic Director sign-off required")}</b> {t("to continue this report.")}</span>
                    <div className="row" style={{ gap: 6, marginLeft: "auto" }}>
                      <button className="btn btn-sm" onClick={() => { window.toast(t("Changes requested — returned to homeroom teacher")); onClose(); }}>{t("Request changes")}</button>
                      <button className="btn btn-sm btn-primary" onClick={() => { window.toast(t("Red Report signed off")); onClose(); }}><Icon name="check" size={13} />{t("Approve")}</button>
                    </div>
                  </div>
                ) : null}

                {/* report card */}
                <div className="between" style={{ margin: "22px 0 12px" }}>
                  <h4 style={{ fontSize: 14 }}>{t("Daily report card")}</h4>
                  {ms.total ? <span className="badge"><b className="mono" style={{ marginRight: 3 }}>{ms.met}/{ms.total}</b> {t("targets met")}</span> : <span className="muted" style={{ fontSize: 12 }}>{t("No active report")}</span>}
                </div>

                {c.reportCard.length ? (
                  <div className="rc-wrap">
                    <table className="rc-tbl">
                      <thead>
                        <tr><th>{t("Day")}</th>{periods.map((p) => <th key={p} className="rc-p">{p}</th>)}</tr>
                      </thead>
                      <tbody>
                        {c.reportCard.map((d, i) => (
                          <tr key={i}>
                            <td className="rc-day">{d.day}</td>
                            {d.lessons.map((l, j) => (
                              <td key={j} className="rc-cell" title={l.subj + (l.comment ? " — " + t(l.comment) : "")}>
                                <span className={"rc-mark " + (l.met === true ? "yes" : l.met === false ? "no" : "na")}>
                                  {l.met === true ? "✓" : l.met === false ? "✕" : "·"}
                                </span>
                              </td>
                            ))}
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                ) : (
                  <p className="muted" style={{ fontSize: 12.5 }}>{t("No report card — student is off-site during the suspension. A reintegration plan applies on return.")}</p>
                )}

                {comments.length ? (
                  <div style={{ marginTop: 16 }}>
                    <div className="eyebrow" style={{ marginBottom: 8 }}>{t("Teacher comments")}</div>
                    <div className="col" style={{ gap: 8 }}>
                      {comments.map((cm, i) => (
                        <div key={i} className="rc-comment">
                          <span className={"rc-mark sm " + (cm.met ? "yes" : cm.met === false ? "no" : "na")}>{cm.met ? "✓" : cm.met === false ? "✕" : "·"}</span>
                          <span className="mono faint" style={{ fontSize: 10.5, minWidth: 96 }}>{cm.day} · {cm.subj}</span>
                          <span style={{ fontSize: 12.5 }}>{t(cm.comment)}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                ) : null}

                {/* history */}
                <div className="eyebrow" style={{ margin: "22px 0 12px" }}>{t("Case history")}</div>
                <div className="timeline">
                  {c.history.map((h, i) => (
                    <div key={i} className="tl-item">
                      <div className="tl-mark"><Icon name="dots" size={13} /></div>
                      <div className="tl-body">
                        <div className="between"><span style={{ fontSize: 12.5, fontWeight: 500 }}>{h.by}</span><span className="mono faint" style={{ fontSize: 10.5 }}>{h.date}</span></div>
                        <p className="muted" style={{ fontSize: 12, marginTop: 2, lineHeight: 1.5 }}>{t(h.text)}</p>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </React.Fragment>
          ) : null}
        </div>
      </div>
    );
  }

  function Behaviour({ role, navigate }) {
    const teacher = role === "teacher";
    const cases = teacher ? DB.CASES.filter((c) => DB.student(c.studentId).cls === "C") : DB.CASES;
    const [open, setOpen] = React.useState(null);
    const [newCase, setNewCase] = React.useState(false);

    const dueThisWeek = cases.filter((c) => c.reviewOverdue || c.reviewDue <= "2026-06-09").length;
    const awaitingSignoff = cases.filter((c) => c.signOff === "pending").length;
    const parentPending = cases.filter((c) => c.parentNotified !== "sent").length;

    return (
      <div className="screen">
        <div className="between" style={{ marginBottom: 18 }}>
          <div>
            <h2 style={{ fontSize: 19 }}>{t("Behaviour Pipeline")}</h2>
            <p className="muted" style={{ fontSize: 13, marginTop: 4 }}>{t("Discipline cases moving through Yellow → Red → Contract → Suspension.")} {teacher ? t("Your Class C cases.") : ""}</p>
          </div>
          <button className="btn btn-sm btn-primary" onClick={() => setNewCase(true)}><Icon name="plus" size={14} />{t("New case")}</button>
        </div>

        {/* stats */}
        <div className="grid cards-4" style={{ marginBottom: 18 }}>
          <KPI label={t("Open cases")} value={cases.length} sub={t("across all stages")} />
          <KPI label={t("Reviews due")} value={dueThisWeek} accent="var(--watch)" sub={t("this week")} />
          <KPI label={t("Awaiting AD sign-off")} value={awaitingSignoff} accent={awaitingSignoff ? "var(--critical)" : "var(--ink)"} sub={t("needs approval")} />
          <KPI label={t("Parent notification")} value={parentPending} sub={parentPending ? t("pending") : t("all sent")} />
        </div>

        {/* kanban */}
        <div className="kanban">
          {STAGES.map((st) => {
            const col = cases.filter((c) => c.stage === st.key);
            return (
              <div key={st.key} className="kb-col">
                <div className="kb-h">
                  <span className="row" style={{ gap: 8 }}>
                    <span style={{ width: 9, height: 9, borderRadius: 2, background: st.color }}></span>
                    <span style={{ fontWeight: 600, fontSize: 13 }}>{t(st.label)}</span>
                  </span>
                  <span className="mono muted" style={{ fontSize: 12 }}>{col.length}</span>
                </div>
                <div className="kb-body">
                  {col.map((c) => <CaseCard key={c.id} c={c} onOpen={setOpen} />)}
                  {!col.length ? <div className="kb-empty">{t("No cases")}</div> : null}
                </div>
              </div>
            );
          })}
        </div>

        <CaseDrawer caseId={open} role={role} onClose={() => setOpen(null)} navigate={navigate} />

        {newCase ? (
          <FormModal title={t("Open a behaviour case")} subtitle={t("Start a new case at the appropriate escalation stage. Parent notification and review dates are set automatically.")}
            fields={[
              { k: "student", label: t("Student"), type: "select", options: cases.length ? DB.STUDENTS.map((s) => s.name + " · " + s.cls) : ["—"] },
              { k: "stage", label: t("Opening stage"), type: "select", options: [t("Yellow Report"), t("Red Report"), t("Behaviour Contract"), t("Suspension")] },
              { k: "reason", label: t("Reason"), type: "textarea", ph: t("Describe the incident or pattern of behaviour…"), required: true },
            ]}
            submitLabel={t("Open case")} submitIcon="plus"
            onClose={() => setNewCase(false)}
            onSubmit={() => { setNewCase(false); window.toast(t("Behaviour case opened · parents notified")); }} />
        ) : null}
      </div>
    );
  }

  window.SCREENS = window.SCREENS || {};
  window.SCREENS.behaviour = Behaviour;
})();
