/* ============================================================
   HALO SMS — Guardians vertical slice (Batch 1)
   list -> create -> detail -> edit + guardian-link manager (m2m)
   ============================================================ */
(function () {
  const { useState, h } = window.HReact;
  const D = window.HALO;

  const REL = ["Mother", "Father", "Uncle", "Aunt", "Grandparent", "Legal guardian", "Sibling", "Other"];

  function childName(id, students) { const s = (students || []).find((x) => x.id === id) || D.studentById(id); return s ? s.first + " " + s.surname : id; }
  function childOf(id, students) { return (students || []).find((x) => x.id === id) || D.studentById(id); }

  /* ---------------- LIST ---------------- */
  function GuardianList({ navigate, list, students }) {
    const [q, setQ] = useState("");
    const filtered = list.filter((g) => q === "" || (g.name + " " + g.phone + " " + g.email).toLowerCase().includes(q.toLowerCase()));
    return h("div", { className: "page-pad wide" },
      h(PageHead, { eyebrow: "People · " + D.session, title: "Guardians", sub: list.length + " guardians linked to students",
        actions: h(React.Fragment, null,
          h(Button, { kind: "ghost", icon: "upload", onClick: () => navigate("guardians:import") }, "Bulk import"),
          h(Button, { kind: "primary", icon: "plus", onClick: () => navigate("guardians:new") }, "Add guardian")) }),
      h("div", { className: "card" },
        h("div", { style: { padding: "14px 16px", borderBottom: "1px solid var(--line)" } },
          h("div", { className: "searchbox", style: { maxWidth: 340 } }, h(Icon, { name: "search" }), h("input", { placeholder: "Search name, phone or email", value: q, onChange: (e) => setQ(e.target.value) }))),
        filtered.length === 0
          ? h("div", { style: { padding: 8 } }, h(EmptyState, { icon: "users", title: "No guardians match", action: h(Button, { kind: "ghost", onClick: () => setQ("") }, "Clear search") }, "Guardians link to one or more students as the contact and default payer."))
          : h("div", { className: "tablewrap" }, h("table", { className: "data" },
              h("thead", null, h("tr", null, h("th", null, "Guardian"), h("th", null, "Relationship"), h("th", null, "Phone"), h("th", null, "Children"), h("th", null, "Payer"))),
              h("tbody", null, filtered.map((g) => h("tr", { key: g.id, onClick: () => navigate("guardians:detail:" + g.id) },
                h("td", null, h("div", { className: "cellname" }, h(Avatar, { name: g.name, size: 34, variant: "accent" }),
                  h("div", null, h("div", { className: "nm" }, g.name), h("div", { className: "sub" }, g.occupation || g.email)))),
                h("td", null, g.rel),
                h("td", null, h("span", { className: "mono", style: { fontSize: 12.5 } }, g.phone)),
                h("td", null, h("div", { className: "row", style: { gap: 5, flexWrap: "wrap" } }, g.children.map((c) => h("span", { key: c, className: "tag" }, childName(c, students))))),
                h("td", null, isPrimaryPayer(g, students) ? h("span", { className: "chip chip-info" }, h(Icon, { name: "wallet" }), "Primary payer") : h("span", { className: "muted" }, "—")))))))));
  }
  function isPrimaryPayer(g, students) { return g.children.some((c) => { const s = childOf(c, students); return s && s.guardian === g.id && s.primary; }); }

  /* ---------------- DETAIL ---------------- */
  function GuardianDetail({ guardian: g, navigate, students, onManageLinks }) {
    return h("div", { className: "page-pad" },
      h(Button, { kind: "quiet", icon: "arrowleft", onClick: () => navigate("guardians"), style: { marginBottom: 16 } }, "All guardians"),
      h("div", { className: "card", style: { marginBottom: 16 } },
        h("div", { style: { display: "flex", gap: 20, padding: 22, alignItems: "flex-start", flexWrap: "wrap" } },
          h(Avatar, { name: g.name, size: 72, variant: "accent" }),
          h("div", { style: { flex: 1, minWidth: 200 } },
            h("h1", { style: { fontSize: 26 } }, g.name),
            h("div", { className: "muted", style: { fontSize: 13.5, marginTop: 5 } }, g.rel + (g.occupation ? " · " + g.occupation : "")),
            h("div", { className: "row", style: { gap: 8, marginTop: 12, flexWrap: "wrap" } },
              h("span", { className: "chip chip-neutral" }, h(Icon, { name: "users" }), g.children.length + (g.children.length === 1 ? " child" : " children")),
              isPrimaryPayer(g, students) && h("span", { className: "chip chip-info" }, h(Icon, { name: "wallet" }), "Primary payer"))),
          h("div", { className: "row", style: { gap: 8 } },
            h(Button, { kind: "primary", icon: "pencil", onClick: () => navigate("guardians:edit:" + g.id) }, "Edit"))),
        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 } }), "SMS and result notices go to this contact")),
      h("div", { style: { display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 16, alignItems: "start" }, className: "det-cols" },
        h("div", null,
          h("div", { className: "card", style: { marginBottom: 16 } },
            h("div", { className: "card-h" }, h("h3", null, "Linked children"), h(Button, { kind: "ghost", size: "sm", icon: "swap", onClick: () => onManageLinks(g) }, "Manage links")),
            h("div", null, g.children.length === 0
              ? h("div", { className: "card-pad" }, h(EmptyState, { icon: "users", title: "No children linked", action: h(Button, { kind: "primary", size: "sm", icon: "plus", onClick: () => onManageLinks(g) }, "Link a student") }, "Attach a student to this guardian."))
              : g.children.map((cid, i) => { const s = childOf(cid, students); const payer = s && s.guardian === g.id && s.primary;
                  return h("div", { key: cid, style: { display: "flex", alignItems: "center", gap: 12, padding: "13px 20px", borderTop: i ? "1px solid var(--line-soft)" : "none", cursor: "pointer" }, onClick: () => s && navigate("students:detail:" + s.id) },
                    h(Avatar, { name: childName(cid, students), size: 36 }),
                    h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600, fontSize: 14 } }, childName(cid, students)), h("div", { className: "muted", style: { fontSize: 12.5 } }, s ? s.cls : "")),
                    payer ? h("span", { className: "chip chip-info" }, h(Icon, { name: "wallet" }), "Primary payer") : h("span", { className: "tag" }, "Contact"),
                    h(Icon, { name: "chevright", style: { color: "var(--ink-400)" } })); }))),
          h(DetailBlock, { title: "Contact" },
            h(KVRow, { k: "Phone", v: g.phone }), h(KVRow, { k: "Email", v: g.email }), h(KVRow, { k: "Occupation", v: g.occupation }),
            h(KVRow, { k: "Address", v: g.address }))),
        h("div", { className: "card" },
          h("div", { className: "card-h" }, h("h3", null, "Notifications")),
          h("div", { className: "card-pad", style: { display: "flex", flexDirection: "column", gap: 12 } },
            [["SMS", true, "Reserved for important events"], ["Email", true, "Results, receipts, notices"], ["Push", false, "Not configured"]].map(([ch, on, sub]) =>
              h("div", { key: ch, style: { display: "flex", alignItems: "center", gap: 10 } },
                h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600, fontSize: 13.5 } }, ch), h("div", { className: "muted", style: { fontSize: 12 } }, sub)),
                h("span", { className: "chip " + (on ? "chip-ok" : "chip-neutral") }, on ? "On" : "Off")))))));
  }

  /* ---------------- FORM ---------------- */
  const blank = () => ({ name: "", rel: "Mother", phone: "", email: "", occupation: "", address: "", children: [] });
  function GuardianForm({ existing, navigate, onSave }) {
    const isEdit = !!existing;
    const [d, setD] = useState(() => existing ? { ...existing } : blank());
    const [err, setErr] = useState({});
    const set = (k) => (e) => setD({ ...d, [k]: e && e.target ? e.target.value : e });
    function submit() {
      const e = {}; if (!d.name.trim()) e.name = "Required"; if (!d.phone.trim()) e.phone = "A phone number is required for SMS";
      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: 760 } },
      h(PageHead, { back: { label: isEdit ? "Cancel edit" : "Back to guardians", onClick: () => navigate(isEdit ? "guardians:detail:" + existing.id : "guardians") },
        eyebrow: isEdit ? "Edit record" : "New guardian", title: isEdit ? d.name : "Add a guardian",
        actions: h(React.Fragment, null, h(Button, { kind: "ghost", onClick: () => navigate(isEdit ? "guardians:detail:" + existing.id : "guardians") }, "Cancel"), h(Button, { kind: "primary", icon: "check", onClick: submit }, isEdit ? "Save changes" : "Add guardian")) }),
      h("div", { className: "card", style: { padding: "4px 24px" } },
        h(FSection, { step: "01", title: "Guardian details", desc: "The parent or guardian's contact information. SMS notices go to the phone here." },
          h("div", { className: "formgrid" },
            Fld("Full name", { req: true, error: err.name, full: true }, h(Input, { value: d.name, onChange: set("name"), error: err.name, placeholder: "Mrs. Folake Adebayo" })),
            Fld("Relationship", {}, h(Select, { value: d.rel, onChange: set("rel") }, REL.map((o) => h("option", { key: o }, o)))),
            Fld("Occupation", {}, h(Input, { value: d.occupation, onChange: set("occupation") })),
            Fld("Phone", { req: true, error: err.phone }, h(Input, { value: d.phone, onChange: set("phone"), lead: "+234", error: err.phone })),
            Fld("Email", {}, h(Input, { type: "email", value: d.email, onChange: set("email") })),
            Fld("Home address", { full: true }, h(Input, { value: d.address, onChange: set("address") })))),
        h(FSection, { step: "02", title: "Linked children", desc: "Guardians can link to several children. You can also manage links from the guardian's profile." },
          h("div", null, isEdit
            ? h("div", { className: "muted", style: { fontSize: 13.5, lineHeight: 1.5 } }, "Use ", h("b", null, "Manage links"), " on the guardian profile to attach students and set the primary payer.")
            : h("div", { className: "muted", style: { fontSize: 13.5, lineHeight: 1.5 } }, "Save this guardian first, then attach children and set the primary payer from their profile."))),
        h("div", { style: { display: "flex", justifyContent: "flex-end", gap: 10, padding: "20px 0" } },
          h(Button, { kind: "ghost", onClick: () => navigate(isEdit ? "guardians:detail:" + existing.id : "guardians") }, "Cancel"),
          h(Button, { kind: "primary", icon: "check", onClick: submit }, isEdit ? "Save changes" : "Add guardian"))));
  }

  /* ---------------- LINK MANAGER ---------------- */
  function LinkManager({ guardian: g, students, onClose, onSave }) {
    const [linked, setLinked] = useState(g.children.slice());
    const [primary, setPrimary] = useState(() => { const m = {}; g.children.forEach((c) => { const s = students.find((x) => x.id === c); if (s && s.guardian === g.id && s.primary) m[c] = true; }); return m; });
    const [add, setAdd] = useState(false);
    const candidates = students.filter((s) => !linked.includes(s.id));
    return h(Modal, { lg: true, icon: "users", title: "Manage links · " + g.name, onClose,
      footer: h(React.Fragment, null, h(Button, { kind: "ghost", onClick: onClose }, "Cancel"), h(Button, { kind: "primary", icon: "check", onClick: () => onSave(linked, primary) }, "Save links")) },
      h("p", { style: { fontSize: 13.5, color: "var(--ink-600)", marginBottom: 14, lineHeight: 1.5 } }, "A guardian can link to several children, and exactly one guardian per student is the primary payer who receives SMS. Reassigning the payer is audit-stamped."),
      h("div", { style: { display: "flex", flexDirection: "column", gap: 8 } }, linked.map((cid) => { const s = students.find((x) => x.id === cid) || D.studentById(cid);
        return h("div", { key: cid, style: { display: "flex", alignItems: "center", gap: 12, padding: 12, borderRadius: 11, border: "1px solid var(--line)" } },
          h(Avatar, { name: childName(cid, students), size: 34 }),
          h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600, fontSize: 14 } }, childName(cid, students)), h("div", { className: "muted", style: { fontSize: 12.5 } }, s ? s.cls : "")),
          h("label", { className: "checkrow", style: { marginRight: 6 }, onClick: (e) => { e.preventDefault(); setPrimary({ ...primary, [cid]: !primary[cid] }); } },
            h("span", { className: "checkbox" + (primary[cid] ? " on" : "") }, h(Icon, { name: "check" })), h("span", { style: { fontSize: 12.5 } }, "Primary payer")),
          h("button", { className: "iconbtn", style: { width: 32, height: 32 }, onClick: () => { setLinked(linked.filter((x) => x !== cid)); const p = { ...primary }; delete p[cid]; setPrimary(p); } }, h(Icon, { name: "x" }))); })),
      linked.length === 0 && h("div", { className: "muted", style: { fontSize: 13.5, padding: "10px 0" } }, "No children linked yet."),
      add
        ? h("div", { style: { marginTop: 12, border: "1px solid var(--line)", borderRadius: 11, padding: 10, maxHeight: 200, overflowY: "auto" }, className: "scroll" },
            candidates.length === 0 ? h("div", { className: "muted", style: { fontSize: 13, padding: 8 } }, "All students are linked.") :
            candidates.map((s) => h("button", { key: s.id, onClick: () => { setLinked([...linked, s.id]); setAdd(false); }, style: { display: "flex", alignItems: "center", gap: 10, padding: 9, borderRadius: 9, border: "none", background: "none", width: "100%", textAlign: "left" } },
              h(Avatar, { name: s.first + " " + s.surname, size: 30 }), h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600, fontSize: 13.5 } }, s.first + " " + s.surname), h("div", { className: "muted", style: { fontSize: 12 } }, s.cls)), h(Icon, { name: "plus", style: { color: "var(--brand)" } }))))
        : h(Button, { kind: "ghost", icon: "plus", onClick: () => setAdd(true), style: { marginTop: 12 } }, "Link a student"));
  }

  /* ---------------- ROUTER ---------------- */
  function Guardians({ params, navigate, list, upsertGuardian, students, onLinkUpdate }) {
    const [lm, setLm] = useState(null);
    const [p0, p1] = params;
    if (p0 === "import") return h(window.BulkImport, { entity: "guardians", navigate, onDone: () => navigate("guardians") });
    let view;
    if (p0 === "new") view = h(GuardianForm, { navigate, onSave: (d) => { const g = commit(d, false, upsertGuardian); toast("Guardian added"); navigate("guardians:detail:" + g.id); } });
    else if (p0 === "edit") { const g = list.find((x) => x.id === p1); view = h(GuardianForm, { existing: g, navigate, onSave: (d) => { commit(d, true, upsertGuardian); toast("Changes saved"); navigate("guardians:detail:" + g.id); } }); }
    else if (p0 === "detail") { const g = list.find((x) => x.id === p1); view = g ? h(GuardianDetail, { guardian: g, navigate, students, onManageLinks: (gg) => setLm(gg) }) : h("div", { className: "page-pad" }, h(EmptyState, { icon: "alert", title: "Guardian not found", action: h(Button, { kind: "ghost", onClick: () => navigate("guardians") }, "Back") })); }
    else view = h(GuardianList, { navigate, list, students });
    return h(window.DesktopScreen, { title: "Guardians" }, view,
      lm && h(LinkManager, { guardian: lm, students, onClose: () => setLm(null), onSave: (linked, primary) => { onLinkUpdate(lm.id, linked, primary); setLm(null); toast("Links updated"); } }));
  }
  function commit(d, isEdit, upsert) { const id = isEdit ? d.id : "g-" + Math.floor(100 + Math.random() * 899); const g = Object.assign({}, d, { id }); upsert(g); return g; }

  window.Guardians = Guardians;
})();
