/* ============================================================
   HALO SMS — Affective/psychomotor (34) + Remarks (35)
   ============================================================ */
(function () {
  const { useState, h } = window.HReact;
  const D = window.HALO;
  const ARMS = ["JSS 1A", "JSS 2B", "Primary 4", "SS2 Science", "SS3 Arts"];

  function ArmStudentPicker({ arm, setArm, roster, sel, setSel }) {
    return h("div", { className: "card", style: { alignSelf: "start" } },
      h("div", { style: { padding: 14, borderBottom: "1px solid var(--line)" } },
        h("select", { className: "select", value: arm, onChange: (e) => { setArm(e.target.value); } }, ARMS.map((a) => h("option", { key: a }, a)))),
      h("div", { style: { maxHeight: 460, overflowY: "auto" }, className: "scroll" }, roster.length === 0
        ? h("div", { className: "muted", style: { padding: 18, fontSize: 13 } }, "No students in this arm.")
        : roster.map((s, i) => h("button", { key: s.id, onClick: () => setSel(s.id),
            style: { display: "flex", alignItems: "center", gap: 10, padding: "11px 14px", width: "100%", textAlign: "left", border: "none", borderTop: i ? "1px solid var(--line-soft)" : "none", background: sel === s.id ? "var(--brand-soft)" : "transparent" } },
            h(Avatar, { name: s.first + " " + s.surname, size: 30 }),
            h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600, fontSize: 13.5, color: sel === s.id ? "var(--brand-strong)" : "inherit" } }, s.surname + ", " + s.first), h("div", { className: "muted", style: { fontSize: 11.5 } }, s.adm))))));
  }

  function RatingPick({ value, onPick }) {
    return h("div", { className: "row", style: { gap: 5 } }, [1, 2, 3, 4, 5].map((n) =>
      h("button", { key: n, onClick: () => onPick(n), title: ["", "Poor", "Weak", "Fair", "Good", "Excellent"][n],
        style: { width: 32, height: 32, borderRadius: 8, fontWeight: 700, fontSize: 13, border: "1px solid " + (value === n ? "var(--brand)" : "var(--line)"), background: value === n ? "var(--brand)" : "var(--surface)", color: value === n ? "var(--on-brand)" : "var(--ink-500)" } }, n)));
  }

  function Affective({ params, navigate, students }) {
    const [arm, setArm] = useState("JSS 1A");
    const roster = D.rosterForArm(arm, students);
    const [sel, setSel] = useState(roster[0] && roster[0].id);
    const [ratings, setRatings] = useState({});
    const student = roster.find((s) => s.id === sel) || roster[0];
    const cur = (student && ratings[student.id]) || {};
    const set = (item, n) => setRatings((p) => ({ ...p, [student.id]: { ...(p[student.id] || {}), [item]: n } }));

    return h(window.DesktopScreen, { title: "Affective & psychomotor" },
      h("div", { className: "page-pad wide" },
        h(window.PageHead, { eyebrow: "Class teacher · " + arm, title: "Affective & psychomotor", sub: "Rate each trait 1–5. Saved with the term result.",
          actions: h(Button, { kind: "primary", icon: "check", onClick: () => toast("Ratings saved for " + (student ? student.first : "")) }, "Save ratings") }),
        h("div", { style: { display: "grid", gridTemplateColumns: "260px 1fr", gap: 16, alignItems: "start" }, className: "det-cols" },
          h(ArmStudentPicker, { arm, setArm: (a) => { setArm(a); const r = D.rosterForArm(a, students); setSel(r[0] && r[0].id); }, roster, sel, setSel }),
          !student ? h("div", { className: "card", style: { padding: 40 } }, h(EmptyState, { icon: "star", title: "No students" }, "Admit students to this arm first."))
          : h("div", { style: { display: "flex", flexDirection: "column", gap: 16 } },
              h("div", { className: "card", style: { padding: 18, display: "flex", alignItems: "center", gap: 14 } },
                h(Avatar, { name: student.first + " " + student.surname, size: 44, variant: "brand" }),
                h("div", null, h("div", { style: { fontWeight: 700, fontSize: 16 } }, student.first + " " + student.surname), h("div", { className: "muted", style: { fontSize: 12.5 } }, student.cls + " · " + student.adm))),
              ratingCard("Affective traits", D.ASSESSMENT.affectiveItems, cur, set),
              ratingCard("Psychomotor skills", D.ASSESSMENT.psychomotorItems, cur, set)))));
  }
  function ratingCard(title, items, cur, set) {
    return h("div", { className: "card" },
      h("div", { className: "card-h" }, h("h3", null, title), h("span", { className: "muted", style: { fontSize: 12 } }, "1 Poor · 5 Excellent")),
      h("div", null, items.map((it, i) => h("div", { key: it, style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: "12px 18px", borderTop: i ? "1px solid var(--line-soft)" : "none" } },
        h("span", { style: { fontSize: 14, fontWeight: 500 } }, it), h(RatingPick, { value: cur[it], onPick: (n) => set(it, n) })))));
  }

  // ---------- Remarks ----------
  const AI_REMARKS = [
    "%N% is a diligent and well-mannered student who has shown steady improvement this term. With continued focus, even stronger results are within reach.",
    "%N% participates actively in class and relates well with peers. A little more consistency in homework will lift overall performance.",
    "%N% has demonstrated good character and commitment. Encouraged to keep up the effort and aim higher next term.",
  ];

  function Remarks({ params, navigate, students, role }) {
    const [arm, setArm] = useState("JSS 1A");
    const roster = D.rosterForArm(arm, students);
    const [sel, setSel] = useState(roster[0] && roster[0].id);
    const [remarks, setRemarks] = useState({});
    const [aiBusy, setAiBusy] = useState(false);
    const student = roster.find((s) => s.id === sel) || roster[0];
    const cur = (student && remarks[student.id]) || {};
    const setR = (key, val) => setRemarks((p) => ({ ...p, [student.id]: { ...(p[student.id] || {}), [key]: val } }));
    const isPrincipal = role === "principal" || role === "admin";

    function aiDraft() {
      setAiBusy(true);
      setTimeout(() => {
        const t = AI_REMARKS[Math.floor(Math.random() * AI_REMARKS.length)].replace(/%N%/g, student.first);
        setR("teacher", t); setR("ai", true); setAiBusy(false); toast("AI draft inserted — review before saving");
      }, 900);
    }

    return h(window.DesktopScreen, { title: "Remarks" },
      h("div", { className: "page-pad wide" },
        h(window.PageHead, { eyebrow: "Remarks · " + arm, title: "Term remarks", sub: "Class-teacher and principal remarks for the report sheet",
          actions: h(Button, { kind: "primary", icon: "check", onClick: () => toast("Remark saved for " + (student ? student.first : "")) }, "Save remark") }),
        h("div", { style: { display: "grid", gridTemplateColumns: "260px 1fr", gap: 16, alignItems: "start" }, className: "det-cols" },
          h(ArmStudentPicker, { arm, setArm: (a) => { setArm(a); const r = D.rosterForArm(a, students); setSel(r[0] && r[0].id); }, roster, sel, setSel }),
          !student ? h("div", { className: "card", style: { padding: 40 } }, h(EmptyState, { icon: "pencil", title: "No students" }, "Admit students to this arm first."))
          : h("div", { style: { display: "flex", flexDirection: "column", gap: 16 } },
              h("div", { className: "card", style: { padding: 18, display: "flex", alignItems: "center", gap: 14 } },
                h(Avatar, { name: student.first + " " + student.surname, size: 44, variant: "brand" }),
                h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 700, fontSize: 16 } }, student.first + " " + student.surname), h("div", { className: "muted", style: { fontSize: 12.5 } }, student.cls + " · avg " + (student.avg != null ? student.avg.toFixed(1) : "—")))),
              h("div", { className: "card", style: { padding: 18 } },
                h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 } },
                  h("div", null, h("div", { style: { fontWeight: 600, fontSize: 14.5 } }, "Class teacher's remark"), cur.ai && h("span", { className: "chip chip-info", style: { marginTop: 4 } }, h(Icon, { name: "star" }), "AI suggested — review")),
                  h(Button, { kind: "ghost", size: "sm", icon: "star", disabled: aiBusy, onClick: aiDraft }, aiBusy ? "Drafting…" : "AI draft")),
                h(Textarea, { value: cur.teacher || "", onChange: (e) => { setR("teacher", e.target.value); setR("ai", false); }, placeholder: "Write a remark, or use AI draft to start…", style: { minHeight: 110 } }),
                cur.ai && h("div", { className: "muted", style: { fontSize: 12, marginTop: 8, display: "flex", gap: 7, alignItems: "center" } }, h(Icon, { name: "info", style: { fontSize: 13 } }), "AI-generated — edit to confirm; editing clears the AI flag.")),
              h("div", { className: "card", style: { padding: 18, opacity: isPrincipal ? 1 : 0.65 } },
                h("div", { style: { fontWeight: 600, fontSize: 14.5, marginBottom: 10 } }, "Principal's remark", !isPrincipal && h("span", { className: "tag", style: { marginLeft: 8 } }, "Principal only")),
                h(Textarea, { value: cur.principal || "", disabled: !isPrincipal, onChange: (e) => setR("principal", e.target.value), placeholder: isPrincipal ? "Principal's remark…" : "Added by the principal", style: { minHeight: 80 } }))))));
  }

  window.Affective = Affective;
  window.Remarks = Remarks;
})();
