/* ============================================================
   HALO SMS — Staff vertical slice (Batch 1)
   list -> onboard -> detail -> edit -> lifecycle -> roles
   ============================================================ */
(function () {
  const { useState, h } = window.HReact;
  const D = window.HALO;

  const lc = (s) => (s || "").toLowerCase();
  const lcChip = (state) => {
    const m = { active: "ok", onboarding: "info", suspended: "warn", banned: "bad", resigned: "neutral", transferred: "neutral", terminated: "bad" };
    return h("span", { className: "chip chip-" + (m[lc(state)] || "neutral") }, h("span", { className: "d" }), state);
  };
  const roleNames = (ids) => ids.map((r) => (D.roleDef(r) || { name: r }).name);

  /* ---------------- LIST ---------------- */
  function StaffList({ navigate, list }) {
    const [q, setQ] = useState(""); const [role, setRole] = useState("all"); const [lf, setLf] = useState("all");
    const filtered = list.filter((s) =>
      (role === "all" || s.roles.includes(role)) && (lf === "all" || lc(s.lifecycle) === lf) &&
      (q === "" || (s.first + " " + s.surname + " " + s.title).toLowerCase().includes(q.toLowerCase())));
    return h("div", { className: "page-pad wide" },
      h(PageHead, { eyebrow: "People · " + D.session, title: "Staff", sub: list.length + " members · " + list.filter((s) => lc(s.lifecycle) === "active").length + " active",
        actions: h(React.Fragment, null,
          h(Button, { kind: "ghost", icon: "upload", onClick: () => navigate("staff:import") }, "Bulk import"),
          h(Button, { kind: "primary", icon: "plus", onClick: () => navigate("staff:new") }, "Onboard staff")) }),
      h("div", { className: "card" },
        h("div", { style: { display: "flex", alignItems: "center", gap: 12, padding: "14px 16px", borderBottom: "1px solid var(--line)", flexWrap: "wrap" } },
          h("div", { className: "searchbox", style: { flex: 1, minWidth: 200, maxWidth: 320 } }, h(Icon, { name: "search" }), h("input", { placeholder: "Search name or title", value: q, onChange: (e) => setQ(e.target.value) })),
          h("select", { className: "select", style: { width: "auto", height: 38 }, value: role, onChange: (e) => setRole(e.target.value) },
            h("option", { value: "all" }, "All roles"), D.ROLE_DEFS.filter((r) => !["parent","student"].includes(r.id)).map((r) => h("option", { key: r.id, value: r.id }, r.name))),
          h("select", { className: "select", style: { width: "auto", height: 38 }, value: lf, onChange: (e) => setLf(e.target.value) },
            h("option", { value: "all" }, "All statuses"), ["active","onboarding","suspended","resigned"].map((s) => h("option", { key: s, value: s }, s[0].toUpperCase() + s.slice(1))))),
        filtered.length === 0
          ? h("div", { style: { padding: 8 } }, h(EmptyState, { icon: "staff", title: "No staff match", action: h(Button, { kind: "ghost", onClick: () => { setQ(""); setRole("all"); setLf("all"); } }, "Clear filters") }, "Try a different name, role or status."))
          : h("div", { className: "tablewrap" }, h("table", { className: "data" },
              h("thead", null, h("tr", null, h("th", null, "Name"), h("th", null, "Designation"), h("th", null, "Roles"), h("th", null, "Teaches"), h("th", null, "Status"))),
              h("tbody", null, filtered.map((s) => h("tr", { key: s.id, onClick: () => navigate("staff:detail:" + s.id) },
                h("td", null, h("div", { className: "cellname" }, h(Avatar, { name: s.first + " " + s.surname, size: 34 }),
                  h("div", null, h("div", { className: "nm" }, s.surname + ", " + s.first), h("div", { className: "sub" }, s.email)))),
                h("td", null, s.title),
                h("td", null, h("div", { className: "row", style: { gap: 5, flexWrap: "wrap" } }, roleNames(s.roles).slice(0, 2).map((r) => h("span", { key: r, className: "tag" }, r)), s.roles.length > 2 && h("span", { className: "tag" }, "+" + (s.roles.length - 2)))),
                h("td", null, s.classTeacherOf ? h("span", { className: "chip chip-info" }, h(Icon, { name: "graduation" }), s.classTeacherOf) : s.subjects.length ? h("span", { className: "muted", style: { fontSize: 13 } }, s.subjects.join(", ")) : h("span", { className: "muted" }, "—")),
                h("td", null, lcChip(s.lifecycle)))))))));
  }

  /* ---------------- DETAIL ---------------- */
  function StaffDetail({ staff: s, navigate, onLifecycle, onAccount }) {
    const [menu, setMenu] = useState(false);
    const full = s.first + " " + s.surname;
    return h("div", { className: "page-pad" },
      h(Button, { kind: "quiet", icon: "arrowleft", onClick: () => navigate("staff"), style: { marginBottom: 16 } }, "All staff"),
      h("div", { className: "card", style: { marginBottom: 16, overflow: "visible" } },
        h("div", { style: { display: "flex", gap: 20, padding: 22, alignItems: "flex-start", flexWrap: "wrap" } },
          h(Avatar, { name: full, size: 72, variant: "brand" }),
          h("div", { style: { flex: 1, minWidth: 200 } },
            h("h1", { style: { fontSize: 26 } }, full),
            h("div", { className: "muted", style: { fontSize: 13.5, marginTop: 5 } }, s.title + " · " + s.employment + " · joined " + fmtDate(s.joined)),
            h("div", { className: "row", style: { gap: 8, marginTop: 12, flexWrap: "wrap" } }, lcChip(s.lifecycle),
              roleNames(s.roles).map((r) => h("span", { key: r, className: "chip chip-neutral" }, r)),
              s.login ? h("span", { className: "chip chip-ok" }, h(Icon, { name: "key" }), "Login active") : h("span", { className: "chip chip-neutral" }, "No login"))),
          h("div", { className: "row", style: { gap: 8, position: "relative" } },
            h(Button, { kind: "primary", icon: "pencil", onClick: () => navigate("staff:edit:" + s.id) }, "Edit"),
            h(Button, { kind: "ghost", icon: "more", onClick: () => setMenu(!menu) }),
            menu && h(Menu, { style: { right: 0, top: 46 }, onClose: () => setMenu(false) },
              h(MenuItem, { icon: "shield", label: "Manage account", onClick: () => { setMenu(false); onAccount(s); } }),
              h(MenuItem, { icon: "swap", label: "Roles & assignments", onClick: () => { setMenu(false); navigate("staff:edit:" + s.id); } }),
              h("div", { className: "mlabel" }, "Lifecycle"),
              h(MenuItem, { icon: "lock", label: "Suspend", onClick: () => { setMenu(false); onLifecycle("Suspend", s); } }),
              h(MenuItem, { icon: "logout", label: "Mark resigned", onClick: () => { setMenu(false); onLifecycle("Resign", s); } }),
              h("div", { className: "mdiv" }),
              h(MenuItem, { icon: "alert", label: "Terminate", onClick: () => { setMenu(false); onLifecycle("Terminate", s); } })))),
        s.note && h("div", { style: { margin: "0 22px 18px", padding: "12px 14px", borderRadius: 10, background: "var(--info-bg)", border: "1px solid var(--info-line)", color: "var(--info-fg)", fontSize: 13, display: "flex", gap: 9 } },
          h(Icon, { name: "info", style: { flex: "none", marginTop: 1 } }), s.note),
        h("div", { className: "divider" }),
        h("div", { style: { padding: "10px 22px", fontSize: 12, color: "var(--ink-500)", display: "flex", gap: 7, alignItems: "center" } },
          h(Icon, { name: "shield", style: { fontSize: 13 } }), "Last updated by ", h("b", { style: { fontWeight: 600, color: "var(--ink-700)" } }, "Mr. Tunde Bakare"), " · 5 days ago")),
      h(DetailBlock, { title: "Bio & contact" },
        h(KVRow, { k: "Gender", v: s.gender }), h(KVRow, { k: "Date of birth", v: fmtDate(s.dob) }), h(KVRow, { k: "Phone", v: s.phone }),
        h(KVRow, { k: "Email", v: s.email }), h(KVRow, { k: "State / LGA", v: s.state + " · " + s.lga }), h(KVRow, { k: "Address", v: s.address })),
      h(DetailBlock, { title: "Employment" },
        h(KVRow, { k: "Designation", v: s.title }), h(KVRow, { k: "Employment type", v: s.employment }), h(KVRow, { k: "Date joined", v: fmtDate(s.joined) }),
        h(KVRow, { k: "Lifecycle", v: s.lifecycle }), h(KVRow, { k: "Nationality", v: s.nationality }), h(KVRow, { k: "Staff ID", v: h("span", { className: "mono", style: { fontSize: 13 } }, s.id.toUpperCase()) })),
      h(DetailBlock, { title: "Roles & teaching assignments", cols: 1 },
        h("div", { style: { display: "flex", flexDirection: "column", gap: 14 } },
          h("div", null, h("div", { className: "k", style: { fontFamily: "var(--fs-mono)", fontSize: 11.5, color: "var(--ink-500)", textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 7 } }, "Assigned roles"),
            h("div", { className: "row", style: { gap: 7, flexWrap: "wrap" } }, roleNames(s.roles).map((r) => h("span", { key: r, className: "chip chip-info" }, h(Icon, { name: "shield" }), r)))),
          h("div", null, h("div", { className: "k", style: { fontFamily: "var(--fs-mono)", fontSize: 11.5, color: "var(--ink-500)", textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 7 } }, "Subjects taught"),
            s.subjects.length ? h("div", { className: "row", style: { gap: 7, flexWrap: "wrap" } }, s.subjects.map((sub) => h("span", { key: sub, className: "tag" }, sub))) : h("span", { className: "muted", style: { fontSize: 13.5 } }, "Not a teaching role")),
          s.classTeacherOf && h("div", null, h("div", { className: "k", style: { fontFamily: "var(--fs-mono)", fontSize: 11.5, color: "var(--ink-500)", textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 7 } }, "Class teacher of"),
            h("span", { className: "chip chip-ok" }, h(Icon, { name: "graduation" }), s.classTeacherOf)))));
  }

  /* ---------------- FORM ---------------- */
  const blank = () => ({ surname: "", first: "", gender: "Female", dob: "", phone: "", email: "", address: "", nationality: "Nigerian", state: "Lagos", lga: "", employment: "Full-time", title: "", joined: new Date().toISOString().slice(0,10), roles: ["subject-teacher"], subjects: [], classTeacherOf: "", login: true, lifecycle: "Onboarding" });

  function StaffForm({ existing, navigate, onSave }) {
    const isEdit = !!existing;
    const [d, setD] = useState(() => existing ? { ...existing, classTeacherOf: existing.classTeacherOf || "" } : blank());
    const [err, setErr] = useState({});
    const set = (k) => (e) => setD({ ...d, [k]: e && e.target ? e.target.value : e });
    const toggle = (k, val) => setD({ ...d, [k]: d[k].includes(val) ? d[k].filter((x) => x !== val) : [...d[k], val] });
    const teaches = d.roles.includes("subject-teacher") || d.roles.includes("class-teacher");

    function submit() {
      const e = {};
      ["surname","first"].forEach((k) => { if (!d[k].trim()) e[k] = "Required"; });
      if (!d.email.trim()) e.email = "Email is required to create a login";
      if (!d.roles.length) e.roles = "Assign at least one role";
      setErr(e);
      if (Object.keys(e).length) { toast("Please fix the highlighted fields", "bad"); return; }
      onSave(d, isEdit);
    }
    return h("div", { className: "page-pad", style: { maxWidth: 920 } },
      h(PageHead, { back: { label: isEdit ? "Cancel edit" : "Back to staff", onClick: () => navigate(isEdit ? "staff:detail:" + existing.id : "staff") },
        eyebrow: isEdit ? "Edit record" : "New staff", title: isEdit ? d.first + " " + d.surname : "Onboard a staff member",
        actions: h(React.Fragment, null, h(Button, { kind: "ghost", onClick: () => navigate(isEdit ? "staff:detail:" + existing.id : "staff") }, "Cancel"), h(Button, { kind: "primary", icon: "check", onClick: submit }, isEdit ? "Save changes" : "Onboard")) }),
      h("div", { className: "card", style: { padding: "4px 24px" } },
        h(FSection, { step: "01", title: "Bio & contact", desc: "Personal and contact details. Email is used to create the login." },
          h("div", { className: "formgrid" },
            Fld("Surname", { req: true, error: err.surname }, h(Input, { value: d.surname, onChange: set("surname"), error: err.surname })),
            Fld("First name", { req: true, error: err.first }, h(Input, { value: d.first, onChange: set("first"), error: err.first })),
            Fld("Gender", {}, h(Segmented, { value: d.gender, onChange: set("gender"), options: [{ value: "Female", label: "Female" }, { value: "Male", label: "Male" }] })),
            Fld("Date of birth", {}, h(Input, { type: "date", value: d.dob, onChange: set("dob") })),
            Fld("Phone", {}, h(Input, { value: d.phone, onChange: set("phone"), lead: "+234" })),
            Fld("Email", { req: true, error: err.email }, h(Input, { type: "email", value: d.email, onChange: set("email"), error: err.email })))),
        h(FSection, { step: "02", title: "Origin & address", desc: "Nigerian-specific fields the school reports on." },
          h("div", { className: "formgrid" },
            Fld("State of origin", {}, h(Select, { value: d.state, onChange: set("state") }, D.STATES.map((o) => h("option", { key: o }, o)))),
            Fld("L.G.A.", {}, h(Input, { value: d.lga, onChange: set("lga") })),
            Fld("Home address", { full: true }, h(Input, { value: d.address, onChange: set("address") })))),
        h(FSection, { step: "03", title: "Employment", desc: "Role at the school. Lean by design — bank/HR details are out of scope in v1." },
          h("div", { className: "formgrid" },
            Fld("Designation / title", {}, h(Input, { value: d.title, onChange: set("title"), placeholder: "e.g. Mathematics Teacher" })),
            Fld("Employment type", {}, h(Segmented, { value: d.employment, onChange: set("employment"), options: D.EMPLOYMENT.map((e) => ({ value: e, label: e })) })),
            Fld("Date joined", {}, h(Input, { type: "date", value: d.joined, onChange: set("joined") })),
            Fld("Create login account", { hint: "First sign-in forces a password change" }, h("div", { style: { display: "flex", alignItems: "center", gap: 10, height: 42 } }, h(Toggle, { on: d.login, onChange: set("login") }), h("span", { style: { fontSize: 13.5 } }, d.login ? "Login will be created" : "No login")))) ),
        h(FSection, { step: "04", title: "Roles & access", desc: "RBAC — pick one or more roles. A person can hold several (a teacher who is also an admin).", error: err.roles },
          h("div", null,
            h("div", { className: "row", style: { gap: 8, flexWrap: "wrap" } }, D.ROLE_DEFS.filter((r) => !["parent","student","super-admin"].includes(r.id)).map((r) =>
              h("button", { key: r.id, type: "button", onClick: () => toggle("roles", r.id),
                style: { display: "flex", alignItems: "center", gap: 8, padding: "9px 13px", borderRadius: 10, border: "1px solid " + (d.roles.includes(r.id) ? "var(--brand)" : "var(--line)"), background: d.roles.includes(r.id) ? "var(--brand-soft)" : "var(--surface)", color: d.roles.includes(r.id) ? "var(--brand-strong)" : "var(--ink-700)", fontWeight: 600, fontSize: 13.5 } },
                h("span", { className: "checkbox" + (d.roles.includes(r.id) ? " on" : ""), style: { width: 17, height: 17 } }, h(Icon, { name: "check" })), r.name))),
            err.roles && h("div", { className: "errmsg", style: { marginTop: 8 } }, h(Icon, { name: "alert" }), err.roles))),
        teaches && h(FSection, { step: "05", title: "Teaching assignments", desc: "Subjects taught and the arm this person is class teacher of (if any)." },
          h("div", null,
            h(Field, { label: "Subjects taught", hint: "Tap to add" }, h("div", { className: "row", style: { gap: 7, flexWrap: "wrap", marginTop: 2 } },
              D.SUBJECTS.map((sub) => h("button", { key: sub, type: "button", onClick: () => toggle("subjects", sub),
                style: { padding: "6px 11px", borderRadius: 8, fontSize: 12.5, border: "1px solid " + (d.subjects.includes(sub) ? "var(--brand)" : "var(--line)"), background: d.subjects.includes(sub) ? "var(--brand-soft)" : "var(--surface-2)", color: d.subjects.includes(sub) ? "var(--brand-strong)" : "var(--ink-600)", fontWeight: 500 } }, sub)))),
            d.roles.includes("class-teacher") && h("div", { style: { marginTop: 16 } }, h(Field, { label: "Class teacher of" }, h(Select, { value: d.classTeacherOf, onChange: set("classTeacherOf") }, h("option", { value: "" }, "Not a class teacher"), D.CLASSES.map((c) => h("option", { key: c }, c))))))),
        h("div", { style: { display: "flex", justifyContent: "flex-end", gap: 10, padding: "20px 0" }, className: "noprint" },
          h(Button, { kind: "ghost", onClick: () => navigate(isEdit ? "staff:detail:" + existing.id : "staff") }, "Cancel"),
          h(Button, { kind: "primary", icon: "check", onClick: submit }, isEdit ? "Save changes" : "Onboard staff"))));
  }

  /* ---------------- ROUTER ---------------- */
  function Staff({ params, navigate, list, upsertStaff }) {
    const [lcm, setLcm] = useState(null); const [acct, setAcct] = useState(null);
    const [p0, p1] = params;
    if (p0 === "import") return h(window.BulkImport, { entity: "staff", navigate, onDone: () => navigate("staff") });

    let view;
    if (p0 === "new") view = h(StaffForm, { navigate, onSave: (d) => { const s = commit(d, false, upsertStaff); toast("Staff onboarded"); navigate("staff:detail:" + s.id); } });
    else if (p0 === "edit") { const s = list.find((x) => x.id === p1); view = h(StaffForm, { existing: s, navigate, onSave: (d) => { commit(d, true, upsertStaff); toast("Changes saved"); navigate("staff:detail:" + s.id); } }); }
    else if (p0 === "detail") { const s = list.find((x) => x.id === p1); view = s ? h(StaffDetail, { staff: s, navigate, onLifecycle: (a, st) => setLcm({ action: a, staff: st }), onAccount: (st) => setAcct(st) }) : h("div", { className: "page-pad" }, h(EmptyState, { icon: "alert", title: "Staff not found", action: h(Button, { kind: "ghost", onClick: () => navigate("staff") }, "Back") })); }
    else view = h(StaffList, { navigate, list });

    return h(window.DesktopScreen, { title: "Staff" }, view,
      lcm && h(window.ConfirmModal, { icon: lcm.action === "Terminate" ? "alert" : "swap", tone: "warn", danger: lcm.action === "Terminate", title: lcm.action + " " + lcm.staff.first + " " + lcm.staff.surname,
        body: "This sets the staff lifecycle to " + lcMap(lcm.action) + ". Note: resigning or terminating does not remove any linked parent access — roles are independent on one identity.", needReason: true,
        confirmLabel: "Confirm " + lcm.action.toLowerCase(), onClose: () => setLcm(null),
        onConfirm: () => { upsertStaff({ ...lcm.staff, lifecycle: lcMap(lcm.action), login: lcm.action === "Suspend" ? false : lcm.staff.login }); toast(lcm.staff.first + " " + lcm.staff.surname + " updated"); setLcm(null); } }),
      acct && h(window.AccountAdminModal, { subject: { name: acct.first + " " + acct.surname, email: acct.email, disabled: acct.lifecycle === "Suspended" }, onClose: () => setAcct(null), onAction: (a) => toast(({ reset: "Password reset · invite sent", invite: "Invite re-sent", disable: "Login disabled", enable: "Login re-enabled", lock: "Account locked for 24 hours", unlink: "Google sign-in unlinked" })[a] || "Done") }));
  }
  function lcMap(a) { return ({ Suspend: "Suspended", Resign: "Resigned", Terminate: "Terminated", Transfer: "Transferred" })[a] || "Active"; }
  function commit(d, isEdit, upsert) {
    const id = isEdit ? d.id : "sf-" + Math.floor(20 + Math.random() * 79);
    const s = Object.assign({}, d, { id, lifecycle: isEdit ? d.lifecycle : (d.login ? "Onboarding" : "Active"), classTeacherOf: d.classTeacherOf || null });
    upsert(s); return s;
  }

  window.Staff = Staff;
})();
