/* ============================================================
   HALO SMS — Results: arm overview (31) + result student
   detail (32) + publish flow (36)
   ============================================================ */
(function () {
  const { useState, h } = window.HReact;
  const D = window.HALO;
  const ARMS = ["JSS 1A", "JSS 2B", "SS2 Science", "SS3 Arts", "Primary 4"];

  const stateChip = (st) => {
    const m = { published: ["chip-ok", "Published"], entered: ["chip-info", "Entered"], incomplete: ["chip-warn", "Incomplete"], empty: ["chip-neutral", "Not started"], draft: ["chip-warn", "Draft"], none: ["chip-neutral", "No result"] };
    const [c, t] = m[st] || ["chip-neutral", st];
    return h("span", { className: "chip " + c }, h("span", { className: "d" }), t);
  };

  function Overview({ navigate, students, role, onPublish, version }) {
    const [arm, setArm] = useState("JSS 1A");
    const subs = D.armSubjectStatus(arm, students);
    const roster = D.rosterForArm(arm, students);
    const armSt = D.armState(arm);
    const canPublish = ["admin", "principal", "class-teacher"].includes(role);
    const complete = subs.filter((s) => s.state === "entered" || s.state === "published").length;
    const incomplete = subs.filter((s) => s.state === "incomplete").length;

    return h("div", { className: "page-pad wide" },
      h(window.PageHead, { eyebrow: "Results · " + D.STRUCTURE.activeTerm, title: "Results overview", sub: "Review entry progress, then publish per arm" }),
      h("div", { className: "card", style: { padding: 16, marginBottom: 16, display: "flex", gap: 14, alignItems: "center", flexWrap: "wrap" } },
        h("div", { className: "field", style: { gap: 4 } }, h("label", { style: { fontSize: 12 } }, "Class / arm"),
          h("select", { className: "select", style: { width: 200, height: 40 }, value: arm, onChange: (e) => setArm(e.target.value) }, ARMS.map((a) => h("option", { key: a }, a)))),
        h("div", { style: { flex: 1 } }),
        h("div", { className: "row", style: { gap: 8 } }, stateChip(armSt),
          canPublish && armSt !== "none" && h(Button, { kind: armSt === "published" ? "ghost" : "primary", icon: armSt === "published" ? "check" : "shieldcheck", disabled: armSt === "published", onClick: () => onPublish(arm) },
            armSt === "published" ? "Published" : "Review & publish"))),

      h("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, alignItems: "start" }, className: "det-cols" },
        h("div", { className: "card" },
          h("div", { className: "card-h" }, h("div", null, h("h3", null, "Subjects"), h("div", { className: "sub" }, complete + " complete · " + incomplete + " incomplete")),
            h(Button, { kind: "quiet", size: "sm", iconRight: "chevright", onClick: () => navigate("scores") }, "Score entry")),
          armSt === "none"
            ? h("div", { className: "card-pad" }, h(EmptyState, { icon: "filetext", title: "No scores yet", action: h(Button, { kind: "primary", size: "sm", onClick: () => navigate("scores") }, "Start score entry") }, "Score entry hasn't begun for this arm this term."))
            : h("div", null, subs.map((s, i) => h("div", { key: s.name, style: { display: "flex", alignItems: "center", gap: 12, padding: "12px 18px", borderTop: i ? "1px solid var(--line-soft)" : "none" } },
                h("div", { style: { flex: 1, fontWeight: 500, fontSize: 14 } }, s.name),
                h("div", { className: "muted tnum", style: { fontSize: 13, width: 64, textAlign: "right" } }, s.entered + "/" + s.total),
                h("div", { style: { width: 70, height: 6, borderRadius: 99, background: "var(--surface-3)", overflow: "hidden" } }, h("div", { style: { height: "100%", width: Math.round(s.entered / s.total * 100) + "%", background: s.state === "incomplete" ? "var(--warn)" : "var(--ok)" } })),
                stateChip(s.state))))),
        h("div", { className: "card" },
          h("div", { className: "card-h" }, h("h3", null, "Students"), h("span", { className: "muted", style: { fontSize: 12.5 } }, roster.length + " in arm")),
          h("div", { style: { maxHeight: 420, overflowY: "auto" }, className: "scroll" }, roster.map((s, i) =>
            h("div", { key: s.id, onClick: () => navigate("results:student:" + s.id), style: { display: "flex", alignItems: "center", gap: 11, padding: "11px 18px", borderTop: i ? "1px solid var(--line-soft)" : "none", cursor: "pointer" } },
              h(Avatar, { name: s.first + " " + s.surname, size: 32 }),
              h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600, fontSize: 13.5 } }, s.surname + ", " + s.first),
                h("div", { className: "muted", style: { fontSize: 12 } }, s.avg != null ? "Avg " + s.avg.toFixed(1) + " · pos " + (s.position || "—") : "Awaiting scores")),
              s.results === "published" ? stateChip("published") : armSt === "incomplete" && i % 5 === 2 ? stateChip("incomplete") : stateChip("draft"),
              h(Icon, { name: "chevright", style: { color: "var(--ink-400)" } })))))));
  }

  function ResultStudentDetail({ student, navigate, role }) {
    const r = window.resultFor(student);
    const valid = r.subjects.filter((x) => !x.absent && x.total != null);
    const avg = valid.length ? (valid.reduce((a, x) => a + x.total, 0) / valid.length).toFixed(1) : "—";
    return h("div", { className: "page-pad" },
      h(Button, { kind: "quiet", icon: "arrowleft", onClick: () => navigate("results"), style: { marginBottom: 14 } }, "Back to results"),
      h("div", { className: "card", style: { marginBottom: 16, padding: 22, display: "flex", gap: 18, alignItems: "center", flexWrap: "wrap" } },
        h(Avatar, { name: student.first + " " + student.surname, size: 60 }),
        h("div", { style: { flex: 1, minWidth: 180 } }, h("h1", { style: { fontSize: 23 } }, student.first + " " + student.surname),
          h("div", { className: "muted", style: { fontSize: 13, marginTop: 4 } }, student.cls + " · " + D.STRUCTURE.activeTerm)),
        h("div", { className: "row", style: { gap: 22 } },
          h("div", { className: "kv" }, h("span", { className: "k" }, "Term avg"), h("span", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 22 }, className: "tnum" }, avg)),
          h("div", { className: "kv" }, h("span", { className: "k" }, "Position"), h("span", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 22 }, className: "tnum" }, student.position ? student.position + "/" + student.ofN : "—"))),
        h("div", { className: "row", style: { gap: 8 } },
          h(Button, { kind: "ghost", icon: "clipboard", onClick: () => navigate("scores") }, "Edit scores"),
          h(Button, { kind: "primary", icon: "filetext", onClick: () => navigate("students:report:" + student.id) }, "Report sheet"))),
      h("div", { className: "card" },
        h("div", { className: "card-h" }, h("h3", null, "Subject breakdown"), h("span", { className: "muted", style: { fontSize: 12.5 } }, "Staff-editable")),
        h("div", { className: "tablewrap" }, h("table", { className: "data" },
          h("thead", null, h("tr", null, h("th", null, "Subject"), h("th", { className: "num" }, "CA1"), h("th", { className: "num" }, "CA2"), h("th", { className: "num" }, "Exam"), h("th", { className: "num" }, "Total"), h("th", { className: "num" }, "Grade"), h("th", { className: "num" }, "Pos"))),
          h("tbody", null, r.subjects.map((s, i) => h("tr", { key: i, style: { cursor: "default" } },
            h("td", { style: { fontWeight: 600 } }, s.name),
            s.absent
              ? h("td", { className: "num muted", colSpan: 4, style: { textAlign: "center", fontStyle: "italic" } }, "Absent")
              : h(React.Fragment, null, h("td", { className: "num" }, s.ca1), h("td", { className: "num" }, s.ca2), h("td", { className: "num" }, s.exam), h("td", { className: "num", style: { fontWeight: 700 } }, s.total)),
            h("td", { className: "num", style: { fontWeight: 700 } }, s.grade),
            h("td", { className: "num muted" }, s.pos === "—" ? "—" : s.pos))))))));
  }

  function PublishModal({ arm, students, onClose, onConfirm }) {
    const subs = D.armSubjectStatus(arm, students);
    const roster = D.rosterForArm(arm, students);
    const incomplete = subs.filter((s) => s.state === "incomplete").length;
    const missing = subs.reduce((a, s) => a + (s.total - s.entered), 0);
    return h(Modal, { icon: "shieldcheck", iconTone: "warn", title: "Publish " + arm + " results", onClose,
      footer: h(React.Fragment, null, h(Button, { kind: "ghost", onClick: onClose }, "Cancel"), h(Button, { kind: "primary", icon: "check", onClick: onConfirm }, "Publish results")) },
      h("div", { style: { display: "flex", gap: 10, marginBottom: 14 } },
        h(SummaryTile, { n: roster.length, label: "Students", tone: "info" }),
        h(SummaryTile, { n: subs.length - incomplete, label: "Subjects ready", tone: "ok" }),
        h(SummaryTile, { n: incomplete, label: "Incomplete", tone: incomplete ? "warn" : "ok" })),
      incomplete > 0 && h("div", { className: "consequence", style: { marginBottom: 12 } }, h(Icon, { name: "alert", style: { fontSize: 17 } }),
        h("div", null, h("b", null, incomplete + " subject(s) still incomplete"), " — " + missing + " scores missing. You can still publish; missing entries show as blank on the report sheet.")),
      h("div", { className: "consequence", style: { background: "var(--info-bg)", borderColor: "var(--info-line)", color: "var(--info-fg)" } },
        h(Icon, { name: "info", style: { fontSize: 17 } }),
        h("div", null, h("b", null, "Parents and students will see these results immediately."), " This is audit-logged. Fee-gated children will only see results once their fees are settled.")));
  }
  function SummaryTile({ n, label, tone }) {
    return h("div", { style: { flex: 1, padding: "12px 14px", borderRadius: 11, background: `var(--${tone}-bg)`, border: `1px solid var(--${tone}-line)` } },
      h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 22, color: `var(--${tone}-fg)` } }, n),
      h("div", { style: { fontSize: 12, color: `var(--${tone}-fg)`, fontWeight: 600 } }, label));
  }

  function Results({ params, navigate, students, upsertStudent, role }) {
    const [, force] = useState(0);
    const [pub, setPub] = useState(null);
    if (params[0] === "import") return h(window.BulkImport, { entity: "results", navigate, onDone: () => navigate("results") });
    if (params[0] === "student") { const s = students.find((x) => x.id === params[1]); return s ? h(ResultStudentDetail, { student: s, navigate, role }) : h("div", { className: "page-pad" }, h(EmptyState, { icon: "alert", title: "Student not found", action: h(Button, { kind: "ghost", onClick: () => navigate("results") }, "Back") })); }
    return h(React.Fragment, null,
      h(Overview, { navigate, students, role, version: 0, onPublish: (arm) => setPub(arm) }),
      pub && h(PublishModal, { arm: pub, students, onClose: () => setPub(null), onConfirm: () => {
        D.ARM_STATE[pub] = { ...(D.ARM_STATE[pub] || {}), state: "published" };
        D.rosterForArm(pub, students).forEach((s) => upsertStudent({ ...s, results: "published" }));
        toast("Results published — " + pub); setPub(null); force((n) => n + 1);
      } }));
  }

  window.Results = Results;
})();
