/* ============================================================
   HALO SMS — Settings hub + 59 finance, 60 branding,
   63 modules, 64 integrations, 65 admission format
   ============================================================ */
(function () {
  const { useState, h } = window.HReact;
  const D = window.HALO;

  /* ---------------- HUB ---------------- */
  function SettingsHub({ navigate }) {
    const cards = [
      ["structure", "building", "Academic structure", "Levels, arms, terms, subjects, departments"],
      ["assessment", "clipboard", "Assessment rules", "CA weights, grade bands, ranking, promotion"],
      ["feesettings", "card", "Finance settings", "Approvals, overpayment, fee-gate threshold"],
      ["branding", "star", "Branding", "Logo, colours and school identity"],
      ["notices", "bell", "Notifications", "Event → channel matrix, quiet hours"],
      ["roles", "shield", "Roles & access", "Predefined and custom roles"],
      ["modules", "plug", "Feature modules", "Turn modules on or off"],
      ["integrations", "plug", "Integrations", "Payments, email, SMS, AI, backups"],
      ["admformat", "filetext", "Admission numbers", "Format for generated admission no."],
      ["audit", "shieldcheck", "Audit log", "Every sensitive action, filterable"],
      ["backups", "database", "Backups", "Automatic and manual backups"],
    ];
    const body = h("div", { className: "page-pad wide" },
      h(window.PageHead, { eyebrow: "Administration", title: "Settings", sub: "Configure how " + D.BRANDS[document.documentElement.getAttribute("data-brand")].name + " runs" }),
      h("div", { className: "grid-3" }, cards.map(([id, icon, title, desc]) =>
        h("button", { key: id, onClick: () => navigate(id), style: { textAlign: "left", border: "none", background: "none", padding: 0 } },
          h("div", { className: "card", style: { padding: 18, height: "100%", display: "flex", gap: 14, alignItems: "flex-start" } },
            h("div", { style: { width: 40, height: 40, borderRadius: 11, flex: "none", background: "var(--brand-soft)", color: "var(--brand-strong)", display: "grid", placeItems: "center" } }, h(Icon, { name: icon })),
            h("div", null, h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 700, fontSize: 15.5 } }, title), h("div", { className: "muted", style: { fontSize: 12.5, marginTop: 4, lineHeight: 1.45 } }, desc)))))));
    return h(window.DesktopScreen, { title: "Settings" }, body);
  }

  /* ---------------- 59 FINANCE SETTINGS ---------------- */
  function FinanceSettings({ navigate }) {
    const [approval, setApproval] = useState(true);
    const [overpay, setOverpay] = useState("credit");
    const [gate, setGate] = useState(100);
    const body = h("div", { className: "page-pad", style: { maxWidth: 760 } },
      h(window.PageHead, { back: { label: "Settings", onClick: () => navigate("settings") }, eyebrow: "Settings", title: "Finance settings",
        actions: h(Button, { kind: "primary", icon: "check", onClick: () => toast("Finance settings saved") }, "Save") }),
      h("div", { className: "card", style: { marginBottom: 16, padding: 18 } },
        h(SettingRow, { title: "Require payment approval", desc: "Manually-recorded payments need a second sign-off before posting." }, h(Toggle, { on: approval, onChange: setApproval })),
        h("div", { className: "divider", style: { margin: "16px 0" } }),
        h("div", null, h("div", { style: { fontWeight: 600, fontSize: 14.5 } }, "Overpayment policy"), h("div", { className: "muted", style: { fontSize: 12.5, margin: "3px 0 12px" } }, "What happens when a parent pays more than the balance"),
          h(Segmented, { value: overpay, onChange: setOverpay, options: [{ value: "credit", label: "Carry as credit" }, { value: "refund", label: "Flag for refund" }, { value: "block", label: "Block overpayment" }] }))),
      h("div", { className: "card", style: { padding: 18 } },
        h("div", { style: { fontWeight: 600, fontSize: 14.5 } }, "Result fee-gate"),
        h("div", { className: "muted", style: { fontSize: 12.5, margin: "3px 0 14px", lineHeight: 1.5 } }, "Parents must have paid at least this share of fees before they can view their child's published results. Set to 0% to disable gating."),
        h("div", { className: "row", style: { gap: 14 } },
          h("input", { type: "range", min: 0, max: 100, step: 5, value: gate, onChange: (e) => setGate(Number(e.target.value)), style: { flex: 1 } }),
          h("span", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 24, width: 64 }, className: "tnum" }, gate + "%")),
        gate === 0 && h("div", { className: "consequence", style: { marginTop: 14, background: "var(--info-bg)", borderColor: "var(--info-line)", color: "var(--info-fg)" } }, h(Icon, { name: "info", style: { fontSize: 16 } }), "Gating disabled — all published results are visible regardless of fees.")));
    return h(window.DesktopScreen, { title: "Finance settings" }, body);
  }
  function SettingRow({ title, desc, children }) {
    return h("div", { style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16 } },
      h("div", null, h("div", { style: { fontWeight: 600, fontSize: 14.5 } }, title), desc && h("div", { className: "muted", style: { fontSize: 12.5, marginTop: 3, lineHeight: 1.5 } }, desc)), children);
  }

  /* ---------------- 60 BRANDING ---------------- */
  function Branding({ navigate }) {
    const cur = document.documentElement.getAttribute("data-brand");
    const meta = D.BRANDS[cur];
    const palettes = [
      ["bright-future", "Teal & gold", "oklch(0.55 0.085 195)", "oklch(0.78 0.115 84)"],
      ["crestwood", "Navy & gold", "oklch(0.40 0.085 264)", "oklch(0.74 0.10 86)"],
      ["little-stars", "Violet & coral", "oklch(0.55 0.16 300)", "oklch(0.72 0.15 30)"],
    ];
    const [name, setName] = useState(meta.name);
    const [motto, setMotto] = useState(meta.motto);
    function applyBrand(id) { document.documentElement.setAttribute("data-brand", id); localStorage.setItem("halo-brand", id); toast("Brand preview applied"); }
    const body = h("div", { className: "page-pad", style: { maxWidth: 880 } },
      h(window.PageHead, { back: { label: "Settings", onClick: () => navigate("settings") }, eyebrow: "Settings", title: "Branding",
        actions: h(Button, { kind: "primary", icon: "check", onClick: () => toast("Branding saved") }, "Save") }),
      h("div", { style: { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, alignItems: "start" }, className: "det-cols" },
        h("div", { className: "card", style: { padding: 20 } },
          h("div", { style: { display: "flex", flexDirection: "column", gap: 16 } },
            h(Field, { label: "School name" }, h(Input, { value: name, onChange: (e) => setName(e.target.value) })),
            h(Field, { label: "Motto / tagline" }, h(Input, { value: motto, onChange: (e) => setMotto(e.target.value) })),
            h(Field, { label: "Logo", hint: "PNG or SVG, square. Falls back to initials." },
              h("div", { className: "row", style: { gap: 12 } }, h("div", { className: "logo", style: { width: 52, height: 52, fontSize: 22 } }, meta.short), h(Button, { kind: "ghost", icon: "upload", onClick: () => toast("Logo uploaded") }, "Upload logo"))),
            h(Field, { label: "Brand palette", hint: "Primary + accent. Status colours never change." },
              h("div", { style: { display: "flex", flexDirection: "column", gap: 8 } }, palettes.map(([id, label, c1, c2]) =>
                h("button", { key: id, onClick: () => applyBrand(id), style: { display: "flex", alignItems: "center", gap: 12, padding: 10, borderRadius: 11, border: "1px solid " + (cur === id ? "var(--brand)" : "var(--line)"), background: cur === id ? "var(--brand-soft)" : "var(--surface)" } },
                  h("span", { style: { display: "flex", gap: 4 } }, h("i", { style: { width: 22, height: 22, borderRadius: 6, background: c1, display: "block" } }), h("i", { style: { width: 22, height: 22, borderRadius: 6, background: c2, display: "block" } })),
                  h("span", { style: { flex: 1, textAlign: "left", fontWeight: 600, fontSize: 13.5 } }, label),
                  cur === id && h("span", { className: "chip chip-ok" }, h(Icon, { name: "check" }), "Active")))))) ),
        h("div", null,
          h("div", { className: "eyebrow", style: { marginBottom: 10 } }, "Live preview"),
          h("div", { className: "card", style: { overflow: "hidden" } },
            h("div", { style: { padding: 18, background: "var(--brand)", color: "var(--on-brand)" } },
              h("div", { className: "row", style: { gap: 11 } }, h("div", { style: { width: 38, height: 38, borderRadius: 10, background: "rgba(255,255,255,.20)", display: "grid", placeItems: "center", fontFamily: "var(--fs-display)", fontWeight: 800 } }, meta.short), h("div", null, h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 700 } }, name), h("div", { style: { fontSize: 12, opacity: .85 } }, motto)))),
            h("div", { className: "card-pad" },
              h(Button, { kind: "primary" }, "Primary button"), " ",
              h("div", { className: "row", style: { gap: 8, marginTop: 14 } }, h("span", { className: "chip chip-ok" }, h("span", { className: "d" }), "Paid"), h("span", { className: "chip chip-warn" }, h("span", { className: "d" }), "Partial"), h("span", { className: "chip chip-bad" }, h("span", { className: "d" }), "Owing")),
              h("div", { className: "muted", style: { fontSize: 12, marginTop: 14 } }, "Status colours stay fixed across every brand."))))));
    return h(window.DesktopScreen, { title: "Branding" }, body);
  }

  /* ---------------- 63 FEATURE MODULES ---------------- */
  function Modules({ navigate }) {
    const [mods, setMods] = useState(() => D.MODULES.map((m) => ({ ...m })));
    const toggle = (id) => setMods((p) => p.map((m) => m.id === id && !m.core && !m.blocked ? { ...m, on: !m.on } : m));
    const body = h("div", { className: "page-pad", style: { maxWidth: 760 } },
      h(window.PageHead, { back: { label: "Settings", onClick: () => navigate("settings") }, eyebrow: "Settings", title: "Feature modules", sub: "Switch optional modules on or off for this school" }),
      h("div", { className: "card" }, mods.map((m, i) => h("div", { key: m.id, style: { display: "flex", alignItems: "center", gap: 14, padding: "15px 18px", borderTop: i ? "1px solid var(--line-soft)" : "none" } },
        h("div", { style: { flex: 1 } },
          h("div", { className: "row", style: { gap: 8 } }, h("span", { style: { fontWeight: 600, fontSize: 14.5 } }, m.name), m.core && h("span", { className: "tag" }, "Core")),
          h("div", { className: "muted", style: { fontSize: 12.5, marginTop: 3 } }, m.blocked || m.desc)),
        m.core ? h("span", { className: "chip chip-ok" }, "Always on")
          : m.blocked ? h("span", { className: "chip chip-neutral" }, "Unavailable")
          : h(Toggle, { on: m.on, onChange: () => toggle(m.id) })))));
    return h(window.DesktopScreen, { title: "Feature modules" }, body);
  }

  /* ---------------- 64 INTEGRATIONS ---------------- */
  function Integrations({ navigate }) {
    const [list, setList] = useState(() => D.INTEGRATIONS.map((x) => ({ ...x })));
    const [cfg, setCfg] = useState(null);
    const cats = [...new Set(list.map((i) => i.category))];
    const body = h("div", { className: "page-pad wide" },
      h(window.PageHead, { back: { label: "Settings", onClick: () => navigate("settings") }, eyebrow: "Settings", title: "Integrations", sub: list.filter((i) => i.connected).length + " of " + list.length + " connected" }),
      cats.map((cat) => h("div", { key: cat, style: { marginBottom: 22 } },
        h("div", { className: "eyebrow", style: { marginBottom: 10 } }, cat),
        h("div", { className: "grid-3" }, list.filter((i) => i.category === cat).map((it) =>
          h("div", { key: it.id, className: "card", style: { padding: 18, display: "flex", flexDirection: "column", gap: 12 } },
            h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "flex-start" } },
              h("div", { style: { width: 40, height: 40, borderRadius: 11, background: "var(--surface-2)", border: "1px solid var(--line)", display: "grid", placeItems: "center", color: "var(--ink-600)" } }, h(Icon, { name: it.category === "Payments" ? "card" : it.category === "Email" ? "mail" : it.category === "SMS" ? "phone" : it.category === "AI" ? "star" : it.category === "Backups" ? "database" : "bell" })),
              it.connected ? h("span", { className: "chip chip-ok" }, h("span", { className: "d" }), it.status) : h("span", { className: "chip chip-neutral" }, "Off")),
            h("div", null, h("div", { style: { fontWeight: 700, fontFamily: "var(--fs-display)", fontSize: 15 } }, it.name), h("div", { className: "muted", style: { fontSize: 12.5, marginTop: 4, lineHeight: 1.45 } }, it.desc)),
            it.connected && it.account && h("div", { className: "mono", style: { fontSize: 11.5, color: "var(--ink-500)" } }, it.account),
            h("div", { style: { flex: 1 } }),
            h(Button, { kind: it.connected ? "ghost" : "primary", size: "sm", block: true, onClick: () => setCfg(it) }, it.connected ? "Manage" : "Connect"))))) ),
      cfg && h(IntegrationModal, { it: cfg, onClose: () => setCfg(null), onSave: (connected) => { setList((p) => p.map((x) => x.id === cfg.id ? { ...x, connected, status: connected ? "Live" : "Not connected" } : x)); setCfg(null); toast(connected ? cfg.name + " connected" : cfg.name + " disconnected"); } }));
    return h(window.DesktopScreen, { title: "Integrations" }, body);
  }
  function IntegrationModal({ it, onClose, onSave }) {
    return h(Modal, { icon: "plug", title: it.name, onClose,
      footer: h(React.Fragment, null, it.connected && h(Button, { kind: "danger-soft", onClick: () => onSave(false) }, "Disconnect"), h("div", { style: { flex: 1 } }), h(Button, { kind: "ghost", onClick: onClose }, "Cancel"), h(Button, { kind: "primary", onClick: () => onSave(true) }, it.connected ? "Save" : "Connect")) },
      h("p", { style: { fontSize: 13.5, color: "var(--ink-600)", marginBottom: 16, lineHeight: 1.5 } }, it.desc),
      h("div", { style: { display: "flex", flexDirection: "column", gap: 12 } }, it.fields.map((f) =>
        h(Field, { key: f, label: f }, h(Input, { type: f.toLowerCase().includes("secret") || f.toLowerCase().includes("key") || f.toLowerCase().includes("token") ? "password" : "text", placeholder: it.connected ? "••••••••••••" : "Enter " + f.toLowerCase() })))));
  }

  /* ---------------- 65 ADMISSION FORMAT ---------------- */
  function AdmissionFormat({ navigate }) {
    const [prefix, setPrefix] = useState("BFA");
    const [useYear, setUseYear] = useState(true);
    const [pad, setPad] = useState(4);
    const sample = prefix + "/" + (useYear ? "2025/" : "") + "0".repeat(pad - 2) + "42";
    const body = h("div", { className: "page-pad", style: { maxWidth: 680 } },
      h(window.PageHead, { back: { label: "Settings", onClick: () => navigate("settings") }, eyebrow: "Settings", title: "Admission numbers",
        actions: h(Button, { kind: "primary", icon: "check", onClick: () => toast("Admission format saved") }, "Save") }),
      h("div", { className: "card", style: { padding: 20 } },
        h("div", { style: { display: "flex", flexDirection: "column", gap: 16 } },
          h(Field, { label: "Prefix", hint: "School code at the start of every admission number" }, h(Input, { value: prefix, onChange: (e) => setPrefix(e.target.value.toUpperCase().slice(0, 5)) })),
          h("div", { className: "row", style: { justifyContent: "space-between" } }, h("div", null, h("div", { style: { fontWeight: 600, fontSize: 14.5 } }, "Include admission year"), h("div", { className: "muted", style: { fontSize: 12.5, marginTop: 3 } }, "e.g. BFA/2025/0042")), h(Toggle, { on: useYear, onChange: setUseYear })),
          h(Field, { label: "Sequence digits", hint: "Zero-padded running number" }, h(Segmented, { value: pad, onChange: setPad, options: [{ value: 3, label: "3" }, { value: 4, label: "4" }, { value: 5, label: "5" }] })),
          h("div", { style: { padding: 16, borderRadius: 12, background: "var(--surface-2)", border: "1px solid var(--line)" } },
            h("div", { className: "eyebrow", style: { marginBottom: 8 } }, "Next admission number"),
            h("div", { className: "mono", style: { fontSize: 22, fontWeight: 600, letterSpacing: "-0.01em" } }, sample)))));
    return h(window.DesktopScreen, { title: "Admission numbers" }, body);
  }

  Object.assign(window, { SettingsHub, FinanceSettings, Branding, Modules, Integrations, AdmissionFormat });
})();
