/* ============================================================
   HALO SMS — 66 Audit log + 67 Backups + 68 Setup wizard
   ============================================================ */
(function () {
  const { useState, h } = window.HReact;
  const D = window.HALO;

  /* ---------------- 66 AUDIT LOG ---------------- */
  function AuditLog({ navigate }) {
    const [cat, setCat] = useState("All");
    const [q, setQ] = useState("");
    const catTone = { Results: "ok", Finance: "warn", People: "info", Security: "bad", System: "neutral", Comms: "info" };
    const rows = D.AUDIT.filter((a) => (cat === "All" || a.cat === cat) && (q === "" || (a.actor + " " + a.action + " " + a.target).toLowerCase().includes(q.toLowerCase())));
    const body = h("div", { className: "page-pad wide" },
      h(window.PageHead, { eyebrow: "System", title: "Audit log", sub: "Every sensitive action, immutable",
        actions: h(Button, { kind: "ghost", icon: "upload", onClick: () => toast("Audit log exported to CSV") }, "Export") }),
      h("div", { className: "card" },
        h("div", { style: { display: "flex", gap: 12, padding: "14px 16px", borderBottom: "1px solid var(--line)", flexWrap: "wrap", alignItems: "center" } },
          h("div", { className: "searchbox", style: { flex: 1, minWidth: 200, maxWidth: 300 } }, h(Icon, { name: "search" }), h("input", { placeholder: "Search actor, action, target", value: q, onChange: (e) => setQ(e.target.value) })),
          h("div", { className: "row", style: { gap: 6, flexWrap: "wrap" } }, D.AUDIT_CATS.map((c) => h("button", { key: c, onClick: () => setCat(c), className: "btn btn-sm " + (cat === c ? "btn-primary" : "btn-ghost") }, c)))),
        rows.length === 0
          ? h(EmptyState, { icon: "shieldcheck", title: "No matching entries", action: h(Button, { kind: "ghost", onClick: () => { setQ(""); setCat("All"); } }, "Clear filters") }, "Try a different search or category.")
          : h("div", { className: "tablewrap" }, h("table", { className: "data" },
              h("thead", null, h("tr", null, h("th", null, "Actor"), h("th", null, "Action"), h("th", null, "Target"), h("th", null, "Category"), h("th", null, "Time"), h("th", null, "IP"))),
              h("tbody", null, rows.map((a) => h("tr", { key: a.id, style: { cursor: "default" } },
                h("td", null, h("div", null, h("div", { style: { fontWeight: 600, fontSize: 13.5 } }, a.actor), h("div", { className: "muted", style: { fontSize: 11.5 } }, a.role))),
                h("td", { style: { fontWeight: 500 } }, a.action),
                h("td", { className: "muted", style: { fontSize: 13 } }, a.target),
                h("td", null, h("span", { className: "chip chip-" + (catTone[a.cat] || "neutral") }, a.cat)),
                h("td", { className: "mono", style: { fontSize: 12, color: "var(--ink-500)" } }, a.time),
                h("td", { className: "mono", style: { fontSize: 12, color: "var(--ink-400)" } }, a.ip))))))));
    return h(window.DesktopScreen, { title: "Audit log" }, body);
  }

  /* ---------------- 67 BACKUPS ---------------- */
  function Backups({ navigate }) {
    const [auto, setAuto] = useState(true);
    const [busy, setBusy] = useState(false);
    const [list, setList] = useState(() => D.BACKUPS.map((b) => ({ ...b })));
    function runNow() { setBusy(true); setTimeout(() => { setList((p) => [{ id: "b" + Date.now(), when: new Date().toISOString().slice(0, 16).replace("T", " "), size: "248 MB", type: "Manual", dest: "Download", status: "ok" }, ...p]); setBusy(false); toast("Backup completed"); }, 1400); }
    const body = h("div", { className: "page-pad", style: { maxWidth: 820 } },
      h(window.PageHead, { eyebrow: "System", title: "Backups", sub: "Your data, safe off-site",
        actions: h(Button, { kind: "primary", icon: "database", disabled: busy, onClick: runNow }, busy ? "Backing up…" : "Back up now") }),
      h("div", { className: "grid-2", style: { marginBottom: 16 } },
        h("div", { className: "card", style: { padding: 18 } },
          h("div", { className: "row", style: { justifyContent: "space-between" } }, h("div", null, h("div", { style: { fontWeight: 600, fontSize: 14.5 } }, "Automatic nightly backup"), h("div", { className: "muted", style: { fontSize: 12.5, marginTop: 3 } }, "Runs at 2:00am to Google Drive")), h(Toggle, { on: auto, onChange: setAuto })),
          auto && h("div", { className: "row", style: { gap: 8, marginTop: 14 } }, h("span", { className: "chip chip-ok" }, h("span", { className: "d" }), "Healthy"), h("span", { className: "muted", style: { fontSize: 12.5 } }, "Last: today 02:00"))),
        h("div", { className: "card", style: { padding: 18 } },
          h("div", { style: { fontWeight: 600, fontSize: 14.5, marginBottom: 4 } }, "Destination"),
          h("div", { className: "row", style: { gap: 11, marginTop: 8 } }, h("div", { style: { width: 36, height: 36, borderRadius: 9, background: "var(--surface-2)", border: "1px solid var(--line)", display: "grid", placeItems: "center" } }, h(Icon, { name: "database" })), h("div", null, h("div", { style: { fontWeight: 600, fontSize: 13.5 } }, "Google Drive"), h("div", { className: "muted", style: { fontSize: 12 } }, "backups@bf-school"))),
          h(Button, { kind: "quiet", size: "sm", style: { marginTop: 12 }, onClick: () => navigate("integrations") }, "Change destination"))),
      busy && h("div", { className: "card", style: { padding: 16, marginBottom: 16 } }, h("div", { className: "skel", style: { height: 8, borderRadius: 99, marginBottom: 10 } }), h("div", { className: "muted", style: { fontSize: 13 } }, "Creating backup…")),
      h("div", { className: "card" },
        h("div", { className: "card-h" }, h("h3", null, "Backup history")),
        h("div", { className: "tablewrap" }, h("table", { className: "data" },
          h("thead", null, h("tr", null, h("th", null, "When"), h("th", null, "Type"), h("th", null, "Destination"), h("th", { className: "num" }, "Size"), h("th", null, "Status"), h("th", null, ""))),
          h("tbody", null, list.map((b) => h("tr", { key: b.id, style: { cursor: "default" } },
            h("td", { className: "mono", style: { fontSize: 12.5 } }, b.when),
            h("td", null, h("span", { className: "tag" }, b.type)),
            h("td", { className: "muted", style: { fontSize: 13 } }, b.dest),
            h("td", { className: "num" }, b.size),
            h("td", null, b.status === "ok" ? h("span", { className: "chip chip-ok" }, h("span", { className: "d" }), "Success") : h("span", { className: "chip chip-bad" }, h(Icon, { name: "alert" }), "Failed")),
            h("td", null, b.status === "ok" && h("button", { className: "btn btn-quiet btn-sm", onClick: () => toast("Restore from " + b.when + "?") }, "Restore")))))))));
    return h(window.DesktopScreen, { title: "Backups" }, body);
  }

  /* ---------------- 68 SETUP WIZARD (8 steps) ---------------- */
  const STEPS = [
    { id: "profile", title: "School profile", icon: "building", desc: "Name, address and contact" },
    { id: "structure", title: "Academic structure", icon: "graduation", desc: "Levels, arms and terms" },
    { id: "assessment", title: "Assessment rules", icon: "clipboard", desc: "CA weights and grade bands" },
    { id: "fees", title: "Fees", icon: "card", desc: "Fee structure per level" },
    { id: "integrations", title: "Integrations", icon: "plug", desc: "Payments, email, SMS" },
    { id: "access", title: "Access & roles", icon: "shield", desc: "Who can do what" },
    { id: "admin", title: "Super-admin", icon: "key", desc: "Your owner account" },
    { id: "finish", title: "Finish", icon: "check", desc: "Review and launch" },
  ];

  function SetupWizard({ navigate }) {
    const [step, setStep] = useState(0);
    const cur = STEPS[step];
    const brand = D.BRANDS[document.documentElement.getAttribute("data-brand")];
    const pct = Math.round((step) / (STEPS.length - 1) * 100);

    return h("div", { style: { minHeight: "100%", display: "flex", flexDirection: "column", background: "var(--paper)" } },
      h("div", { style: { display: "flex", flex: 1, minHeight: 0 } },
        // rail
        h("div", { className: "desktop-only", style: { width: 280, flex: "none", borderRight: "1px solid var(--line)", background: "var(--surface)", padding: 24, display: "flex", flexDirection: "column" } },
          h("div", { className: "row", style: { gap: 11, marginBottom: 28 } }, h("div", { className: "logo" }, brand.short), h("div", null, h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 700, fontSize: 15 } }, "Halo setup"), h("div", { className: "muted", style: { fontSize: 12 } }, "First-boot wizard"))),
          h("div", { style: { display: "flex", flexDirection: "column", gap: 2, flex: 1 } }, STEPS.map((s, i) => h("button", { key: s.id, onClick: () => setStep(i), style: { display: "flex", alignItems: "center", gap: 12, padding: "10px 12px", borderRadius: 10, border: "none", background: i === step ? "var(--brand-soft)" : "transparent", textAlign: "left", cursor: "pointer" } },
            h("span", { style: { width: 26, height: 26, borderRadius: 99, flex: "none", display: "grid", placeItems: "center", fontSize: 12, fontWeight: 700, background: i < step ? "var(--ok)" : i === step ? "var(--brand)" : "var(--surface-3)", color: i <= step ? "var(--on-brand)" : "var(--ink-500)" } }, i < step ? h(Icon, { name: "check" }) : i + 1),
            h("span", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600, fontSize: 13.5, color: i === step ? "var(--brand-strong)" : "var(--ink-800)" } }, s.title), h("div", { className: "muted", style: { fontSize: 11.5 } }, s.desc))))),
          h("div", { style: { height: 5, borderRadius: 99, background: "var(--surface-3)", overflow: "hidden", marginTop: 16 } }, h("div", { style: { height: "100%", width: pct + "%", background: "var(--brand)", transition: ".3s" } })),
          h("div", { className: "muted", style: { fontSize: 11.5, marginTop: 8, textAlign: "center" } }, "Step " + (step + 1) + " of " + STEPS.length)),
        // panel
        h("div", { style: { flex: 1, overflowY: "auto", display: "flex", flexDirection: "column" }, className: "scroll" },
          h("div", { style: { flex: 1, padding: "40px 40px 24px", maxWidth: 680, width: "100%", margin: "0 auto" } },
            h("div", { style: { width: 52, height: 52, borderRadius: 14, background: "var(--brand-soft)", color: "var(--brand-strong)", display: "grid", placeItems: "center", fontSize: 24, marginBottom: 18 } }, h(Icon, { name: cur.icon })),
            h("div", { className: "eyebrow", style: { marginBottom: 8 } }, "Step " + (step + 1) + " · " + cur.desc),
            h("h1", { style: { fontSize: 30, marginBottom: 22 } }, cur.title),
            h(StepBody, { id: cur.id, brand, navigate })),
          h("div", { style: { borderTop: "1px solid var(--line)", padding: "16px 40px", display: "flex", justifyContent: "space-between", maxWidth: 760, width: "100%", margin: "0 auto", boxSizing: "border-box" } },
            h(Button, { kind: "ghost", disabled: step === 0, onClick: () => setStep(step - 1) }, "Back"),
            step === STEPS.length - 1
              ? h(Button, { kind: "primary", icon: "check", onClick: () => { toast("School is live! Welcome to Halo."); navigate("__role:admin"); } }, "Launch school")
              : h(Button, { kind: "primary", iconRight: "chevright", onClick: () => setStep(step + 1) }, "Continue")))));
  }

  function StepBody({ id, brand, navigate }) {
    if (id === "profile") return h("div", { style: { display: "flex", flexDirection: "column", gap: 16 } },
      h(Field, { label: "School name", required: true }, h(Input, { defaultValue: brand.name })),
      h(Field, { label: "Motto" }, h(Input, { defaultValue: brand.motto })),
      h("div", { className: "formgrid" }, h(Field, { label: "Email" }, h(Input, { defaultValue: "admin@brightfuture.edu.ng" })), h(Field, { label: "Phone" }, h(Input, { lead: "+234", defaultValue: "803 000 0000" }))),
      h(Field, { label: "Address" }, h(Input, { defaultValue: "12 Allen Avenue, Ikeja, Lagos" })));
    if (id === "structure") return h("div", null,
      h("p", { className: "muted", style: { fontSize: 14, marginBottom: 16, lineHeight: 1.5 } }, "We've pre-filled the standard Nigerian structure. You can fine-tune levels and arms later in Settings."),
      h("div", { className: "card", style: { padding: 4 } }, ["Primary 1–6", "JSS 1–3 (A & B arms)", "SS 1–3 (Science / Arts / Commercial)"].map((l, i) =>
        h("div", { key: l, style: { display: "flex", alignItems: "center", gap: 10, padding: "13px 16px", borderTop: i ? "1px solid var(--line-soft)" : "none" } }, h(Icon, { name: "check", style: { color: "var(--ok)" } }), h("span", { style: { fontSize: 14, fontWeight: 500 } }, l)))),
      h("div", { style: { marginTop: 14 } }, h(SetupChecks, { items: [["3-term session", true], ["Competition ranking", true], ["Departments in senior secondary", true]] })));
    if (id === "assessment") return h("div", null,
      h("p", { className: "muted", style: { fontSize: 14, marginBottom: 16, lineHeight: 1.5 } }, "Default split: CA1 20 + CA2 20 + Exam 60 = 100, with WAEC-style grade bands."),
      h("div", { className: "row", style: { gap: 12 } }, [["CA 1", "20"], ["CA 2", "20"], ["Exam", "60"]].map(([l, v]) => h("div", { key: l, className: "card", style: { padding: 16, textAlign: "center", flex: 1 } }, h("div", { className: "eyebrow" }, l), h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 28 } }, v)))),
      h("div", { style: { marginTop: 14 } }, h(SetupChecks, { items: [["A1–F9 grade bands", true], ["Promotion threshold 45%", true]] })));
    if (id === "fees") return h("div", null,
      h("p", { className: "muted", style: { fontSize: 14, marginBottom: 16, lineHeight: 1.5 } }, "Set fees per level now, or skip and add them in Finance settings."),
      h("div", { className: "card", style: { padding: 4 } }, D.FEE_STRUCTURES.slice(0, 4).map((f, i) => h("div", { key: f.id, style: { display: "flex", justifyContent: "space-between", padding: "13px 16px", borderTop: i ? "1px solid var(--line-soft)" : "none" } }, h("span", { style: { fontWeight: 500, fontSize: 14 } }, f.level), h("span", { className: "naira", style: { fontWeight: 600 } }, D.fmt(f.items.reduce((a, x) => a + x[1], 0)))))));
    if (id === "integrations") return h("div", null,
      h("p", { className: "muted", style: { fontSize: 14, marginBottom: 16, lineHeight: 1.5 } }, "Connect the essentials now — you can add the rest later."),
      h("div", { style: { display: "flex", flexDirection: "column", gap: 10 } }, D.INTEGRATIONS.slice(0, 4).map((it) =>
        h("div", { key: it.id, className: "card", style: { padding: 14, display: "flex", alignItems: "center", gap: 12 } },
          h("div", { style: { width: 34, height: 34, borderRadius: 9, background: "var(--surface-2)", border: "1px solid var(--line)", display: "grid", placeItems: "center" } }, h(Icon, { name: it.category === "Payments" ? "card" : it.category === "Email" ? "mail" : it.category === "SMS" ? "phone" : "star" })),
          h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600, fontSize: 13.5 } }, it.name), h("div", { className: "muted", style: { fontSize: 12 } }, it.category)),
          it.connected ? h("span", { className: "chip chip-ok" }, h("span", { className: "d" }), "Connected") : h(Button, { kind: "ghost", size: "sm" }, "Connect")))));
    if (id === "access") return h("div", null,
      h("p", { className: "muted", style: { fontSize: 14, marginBottom: 16, lineHeight: 1.5 } }, "Halo ships with 8 predefined roles. Customise them anytime in Roles & access."),
      h("div", { className: "row", style: { gap: 8, flexWrap: "wrap" } }, D.ROLE_DEFS.filter((r) => r.predefined).map((r) => h("span", { key: r.id, className: "chip chip-neutral" }, h(Icon, { name: "shield" }), r.name))));
    if (id === "admin") return h("div", { style: { display: "flex", flexDirection: "column", gap: 16 } },
      h("p", { className: "muted", style: { fontSize: 14, lineHeight: 1.5 } }, "This is the owner account with full access. Keep these credentials safe."),
      h("div", { className: "formgrid" }, h(Field, { label: "Full name", required: true }, h(Input, { defaultValue: "Mrs. Folake Adebayo" })), h(Field, { label: "Email", required: true }, h(Input, { defaultValue: "admin@brightfuture.edu.ng" }))),
      h(Field, { label: "Password", required: true, hint: "At least 8 characters" }, h(Input, { type: "password", defaultValue: "password" })));
    // finish
    return h("div", null,
      h("p", { style: { fontSize: 15, lineHeight: 1.6, marginBottom: 18 } }, "Everything's ready. Launch to open ", h("b", null, brand.name), " on Halo — you'll land on the admin dashboard with all modules live."),
      h("div", { className: "card", style: { padding: 4 } }, [["School profile", "Configured"], ["Academic structure", "Standard NG · 3 terms"], ["Assessment", "CA 40 / Exam 60 · A1–F9"], ["Fees", "4 levels set"], ["Integrations", "Paystack, ZeptoMail, AI"], ["Roles", "8 predefined"], ["Super-admin", "Created"]].map(([k, v], i) =>
        h("div", { key: k, style: { display: "flex", justifyContent: "space-between", alignItems: "center", padding: "12px 16px", borderTop: i ? "1px solid var(--line-soft)" : "none" } }, h("span", { className: "row", style: { gap: 9, fontSize: 14, fontWeight: 500 } }, h(Icon, { name: "check", style: { color: "var(--ok)" } }), k), h("span", { className: "muted", style: { fontSize: 13 } }, v)))));
  }
  function SetupChecks({ items }) {
    return h("div", { style: { display: "flex", flexDirection: "column", gap: 9 } }, items.map(([label, on]) =>
      h("label", { key: label, className: "checkrow" }, h("span", { className: "checkbox" + (on ? " on" : "") }, h(Icon, { name: "check" })), h("span", { style: { fontSize: 14 } }, label))));
  }

  Object.assign(window, { AuditLog, Backups });
})();
