/* ============================================================
   HALO SMS — 68 Setup wizard (8 steps, fully configurable)
   Every step has real, editable inputs held in one config state;
   the Finish step reflects exactly what you configured.
   ============================================================ */
(function () {
  const { useState, h } = window.HReact;
  const D = window.HALO;

  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 initialConfig(brand) {
    return {
      profile: { name: brand.name, motto: brand.motto, email: "admin@" + brand.id.replace(/-/g, "") + ".edu.ng", phone: "803 000 0000", address: "12 Allen Avenue, Ikeja, Lagos" },
      structure: {
        levels: [
          { id: "l1", name: "Primary 4", arms: [""], dept: false },
          { id: "l2", name: "JSS 1", arms: ["A", "B"], dept: false },
          { id: "l3", name: "JSS 2", arms: ["A", "B"], dept: false },
          { id: "l4", name: "SS 2", arms: ["Science", "Arts"], dept: true },
          { id: "l5", name: "SS 3", arms: ["Science", "Arts"], dept: true },
        ],
        terms: 3, ranking: true, departments: ["Science", "Arts", "Commercial"],
      },
      assessment: { ca1: 20, ca2: 20, exam: 60, promotion: 45, ranking: true },
      fees: D.FEE_STRUCTURES.reduce((m, f) => { m[f.level] = f.items.reduce((a, x) => a + x[1], 0); return m; }, {}),
      integrations: { paystack: true, zeptomail: true, termii: false, openrouter: true, push: false, gdrive: true },
      access: D.ROLE_DEFS.filter((r) => r.predefined).reduce((m, r) => { m[r.id] = true; return m; }, {}),
      admin: { name: "Mrs. Folake Adebayo", email: "admin@brightfuture.edu.ng", password: "" },
    };
  }

  function SetupWizard({ navigate }) {
    const brand = D.BRANDS[document.documentElement.getAttribute("data-brand")];
    const [step, setStep] = useState(0);
    const [cfg, setCfg] = useState(() => initialConfig(brand));
    const [errors, setErrors] = useState({});
    const cur = STEPS[step];
    const pct = Math.round(step / (STEPS.length - 1) * 100);
    const set = (section, patch) => setCfg((c) => ({ ...c, [section]: { ...c[section], ...patch } }));

    // per-step validation gate
    function validate() {
      const e = {};
      if (cur.id === "profile" && !cfg.profile.name.trim()) e.name = "School name is required";
      if (cur.id === "assessment") { const sum = Number(cfg.assessment.ca1) + Number(cfg.assessment.ca2) + Number(cfg.assessment.exam); if (sum !== 100) e.assessment = "Weights must total 100 (currently " + sum + ")"; }
      if (cur.id === "structure" && cfg.structure.levels.length === 0) e.structure = "Add at least one class level";
      if (cur.id === "access" && !Object.values(cfg.access).some(Boolean)) e.access = "Enable at least one role";
      if (cur.id === "admin") { if (!cfg.admin.name.trim()) e.adminName = "Required"; if (!cfg.admin.email.trim()) e.adminEmail = "Required"; if (cfg.admin.password.length < 8) e.adminPw = "At least 8 characters"; }
      setErrors(e); return Object.keys(e).length === 0;
    }
    function next() { if (validate()) { setStep(step + 1); } else { toast("Please complete this step", "bad"); } }

    return h("div", { style: { minHeight: "100%", display: "flex", flexDirection: "column", background: "var(--paper)" } },
      h("div", { style: { display: "flex", flex: 1, minHeight: 0 } },
        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: () => i <= step && 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: i <= step ? "pointer" : "default", opacity: i <= step ? 1 : 0.55 } },
            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)),
        h("div", { style: { flex: 1, overflowY: "auto", display: "flex", flexDirection: "column" }, className: "scroll" },
          h("div", { style: { flex: 1, padding: "40px 40px 24px", maxWidth: 700, width: "100%", margin: "0 auto", boxSizing: "border-box" } },
            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, cfg, set, setCfg, errors, brand, goTo: setStep })),
          h("div", { style: { borderTop: "1px solid var(--line)", padding: "16px 40px", display: "flex", justifyContent: "space-between", maxWidth: 780, 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(cfg.profile.name + " is live! Welcome to Halo."); navigate("__role:admin"); } }, "Launch school")
              : h(Button, { kind: "primary", iconRight: "chevright", onClick: next }, "Continue")))));
  }

  /* ---------------- step bodies (all editable) ---------------- */
  function StepBody({ id, cfg, set, setCfg, errors, brand, goTo }) {
    if (id === "profile") return h("div", { style: { display: "flex", flexDirection: "column", gap: 16 } },
      h(Field, { label: "School name", required: true, error: errors.name }, h(Input, { value: cfg.profile.name, error: !!errors.name, onChange: (e) => set("profile", { name: e.target.value }) })),
      h(Field, { label: "Motto / tagline" }, h(Input, { value: cfg.profile.motto, onChange: (e) => set("profile", { motto: e.target.value }) })),
      h("div", { className: "formgrid" },
        h(Field, { label: "Contact email" }, h(Input, { value: cfg.profile.email, onChange: (e) => set("profile", { email: e.target.value }) })),
        h(Field, { label: "Phone" }, h(Input, { lead: "+234", value: cfg.profile.phone, onChange: (e) => set("profile", { phone: e.target.value }) }))),
      h(Field, { label: "Address" }, h(Input, { value: cfg.profile.address, onChange: (e) => set("profile", { address: e.target.value }) })));

    if (id === "structure") return h(StructureStep, { cfg, set, setCfg, errors });
    if (id === "assessment") return h(AssessmentStep, { cfg, set, errors });
    if (id === "fees") return h(FeesStep, { cfg, setCfg });
    if (id === "integrations") return h(IntegrationsStep, { cfg, setCfg });
    if (id === "access") return h(AccessStep, { cfg, setCfg, errors });

    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, error: errors.adminName }, h(Input, { value: cfg.admin.name, error: !!errors.adminName, onChange: (e) => set("admin", { name: e.target.value }) })),
        h(Field, { label: "Email", required: true, error: errors.adminEmail }, h(Input, { value: cfg.admin.email, error: !!errors.adminEmail, onChange: (e) => set("admin", { email: e.target.value }) }))),
      h(Field, { label: "Password", required: true, error: errors.adminPw, hint: errors.adminPw ? null : "At least 8 characters" }, h(Input, { type: "password", value: cfg.admin.password, error: !!errors.adminPw, onChange: (e) => set("admin", { password: e.target.value }), placeholder: "Choose a strong password" })));

    // finish — reflects actual config
    const sum = Number(cfg.assessment.ca1) + Number(cfg.assessment.ca2) + Number(cfg.assessment.exam);
    const armCount = cfg.structure.levels.reduce((a, l) => a + (Array.isArray(l.arms) ? l.arms.length : 1), 0);
    const conns = Object.keys(cfg.integrations).filter((k) => cfg.integrations[k]);
    const roleCount = Object.values(cfg.access).filter(Boolean).length;
    const feeLevels = Object.keys(cfg.fees).length;
    const rows = [
      ["School profile", cfg.profile.name, "profile"],
      ["Academic structure", cfg.structure.levels.length + " levels · " + armCount + " arms · " + cfg.structure.terms + " terms", "structure"],
      ["Assessment", "CA " + (Number(cfg.assessment.ca1) + Number(cfg.assessment.ca2)) + " / Exam " + cfg.assessment.exam + " · promote ≥ " + cfg.assessment.promotion + "%", "assessment"],
      ["Fees", feeLevels + " levels configured", "fees"],
      ["Integrations", conns.length + " connected", "integrations"],
      ["Roles", roleCount + " enabled", "access"],
      ["Super-admin", cfg.admin.name || "—", "admin"],
    ];
    return h("div", null,
      h("p", { style: { fontSize: 15, lineHeight: 1.6, marginBottom: 18 } }, "Here's exactly what you configured. Tap any row to jump back and change it, then launch ", h("b", null, cfg.profile.name), "."),
      sum !== 100 && h("div", { className: "consequence", style: { marginBottom: 14 } }, h(Icon, { name: "alert", style: { fontSize: 17 } }), h("div", null, h("b", null, "Assessment weights total " + sum + ", not 100."), " Go back to step 3 to fix before launching.")),
      h("div", { className: "card", style: { padding: 4 } }, rows.map(([k, v, target], i) =>
        h("button", { key: k, onClick: () => goTo(STEPS.findIndex((s) => s.id === target)), style: { display: "flex", justifyContent: "space-between", alignItems: "center", padding: "13px 16px", borderTop: i ? "1px solid var(--line-soft)" : "none", border: "none", borderRadius: 0, background: "none", width: "100%", textAlign: "left", cursor: "pointer" } },
          h("span", { className: "row", style: { gap: 9, fontSize: 14, fontWeight: 500 } }, h(Icon, { name: "check", style: { color: "var(--ok)" } }), k),
          h("span", { className: "row", style: { gap: 8 } }, h("span", { className: "muted", style: { fontSize: 13 } }, v), h(Icon, { name: "pencil", style: { fontSize: 13, color: "var(--ink-400)" } }))))));
  }

  /* ---- Structure: levels with a clean arm-count stepper + name preview ---- */
  function armNames(name, arms) {
    const base = (name || "Class").trim();
    if (!arms || arms.length <= 1) return [base + (arms && arms[0] ? " " + arms[0].trim() : "")].map((x) => x.trim());
    return arms.map((a) => (base + " " + (a || "").trim()).trim());
  }
  function nextDefaultLabel(arms) {
    // suggest next letter not already used; falls back to A,B,C…
    for (let i = 0; i < 26; i++) { const L = String.fromCharCode(65 + i); if (!arms.some((a) => (a || "").trim().toUpperCase() === L)) return L; }
    return "Arm " + (arms.length + 1);
  }
  function StructureStep({ cfg, set, setCfg, errors }) {
    const s = cfg.structure;
    const setLevels = (levels) => set("structure", { levels });
    const setArm = (li, ai, val) => setLevels(s.levels.map((l, i) => i === li ? { ...l, arms: l.arms.map((a, j) => j === ai ? val : a) } : l));
    const addArm = (li) => setLevels(s.levels.map((l, i) => i === li ? { ...l, arms: [...l.arms, nextDefaultLabel(l.arms)] } : l));
    const rmArm = (li, ai) => setLevels(s.levels.map((l, i) => i === li ? { ...l, arms: l.arms.length > 1 ? l.arms.filter((_, j) => j !== ai) : l.arms } : l));
    const rmLevel = (li) => setLevels(s.levels.filter((_, i) => i !== li));
    const renameLevel = (li, name) => setLevels(s.levels.map((l, i) => i === li ? { ...l, name } : l));
    const addLevel = () => setLevels([...s.levels, { id: "l" + Date.now(), name: "New class", arms: ["A"], dept: false }]);
    return h("div", null,
      h("p", { className: "muted", style: { fontSize: 14, marginBottom: 16, lineHeight: 1.5 } }, "Name each class and label its arms however your school does — letters (A, B), colours (Blue, Green) or house names (Almond, Bluebird). The preview shows the full class names."),
      errors.structure && h("div", { className: "errmsg", style: { marginBottom: 12 } }, h(Icon, { name: "alert" }), errors.structure),
      h("div", { className: "card", style: { marginBottom: 16 } }, s.levels.map((l, li) => {
        const names = armNames(l.name, l.arms);
        const single = l.arms.length <= 1;
        return h("div", { key: l.id, style: { display: "flex", alignItems: "flex-start", gap: 14, padding: "14px 16px", borderTop: li ? "1px solid var(--line-soft)" : "none", flexWrap: "wrap" } },
          h("div", { className: "field", style: { gap: 4, width: 150 } }, h("label", { style: { fontSize: 11 } }, "Class name"), h("input", { className: "input", value: l.name, onChange: (e) => renameLevel(li, e.target.value), style: { height: 36, fontWeight: 600 } })),
          h("div", { className: "field", style: { gap: 4, flex: 1, minWidth: 220 } },
            h("label", { style: { fontSize: 11 } }, "Arm labels"),
            h("div", { className: "row", style: { gap: 7, flexWrap: "wrap" } },
              l.arms.map((a, ai) => h("span", { key: ai, className: "armchip" },
                h("input", { value: a, placeholder: single ? "(none)" : "Label", onChange: (e) => setArm(li, ai, e.target.value), style: { width: Math.max(34, (a.length || 4) * 8.5) + "px" }, "aria-label": "Arm label" }),
                l.arms.length > 1 && h("button", { className: "armx", onClick: () => rmArm(li, ai), title: "Remove arm", "aria-label": "Remove arm" }, h(Icon, { name: "x" })))),
              h("button", { className: "btn btn-quiet btn-sm", onClick: () => addArm(li) }, h(Icon, { name: "plus" }), "Arm")),
            h("div", { className: "row", style: { gap: 6, flexWrap: "wrap", marginTop: 8 } },
              names.map((nm, k) => h("span", { key: k, className: "tag", style: { background: "var(--brand-soft)", color: "var(--brand-strong)", borderColor: "transparent" } }, nm || "(unnamed)")),
              l.dept && h("span", { className: "chip chip-info", title: "Senior classes split by department" }, "+ depts"))),
          h("button", { className: "iconbtn", style: { width: 32, height: 32, flex: "none", marginTop: 18 }, onClick: () => rmLevel(li), title: "Remove class" }, h(Icon, { name: "trash" })));
      })),
      h(Button, { kind: "ghost", icon: "plus", onClick: addLevel, style: { marginBottom: 18 } }, "Add class"),
      h("div", { className: "card", style: { padding: 16, display: "flex", flexDirection: "column", gap: 14 } },
        h("div", { className: "row", style: { justifyContent: "space-between" } }, h("div", null, h("div", { style: { fontWeight: 600, fontSize: 14 } }, "Terms per session"), h("div", { className: "muted", style: { fontSize: 12.5, marginTop: 2 } }, "Nigerian schools typically run 3")), h(Segmented, { value: s.terms, onChange: (v) => set("structure", { terms: v }), options: [{ value: 2, label: "2" }, { value: 3, label: "3" }] })),
        h("div", { className: "divider" }),
        h("div", { className: "row", style: { justifyContent: "space-between" } }, h("div", null, h("div", { style: { fontWeight: 600, fontSize: 14 } }, "Competition ranking"), h("div", { className: "muted", style: { fontSize: 12.5, marginTop: 2 } }, "Show class positions on report sheets")), h(Toggle, { on: s.ranking, onChange: (v) => set("structure", { ranking: v }) }))));
  }

  /* ---- Assessment: editable weights + promotion ---- */
  function AssessmentStep({ cfg, set, errors }) {
    const a = cfg.assessment;
    const sum = Number(a.ca1) + Number(a.ca2) + Number(a.exam);
    const setW = (k) => (e) => set("assessment", { [k]: Number(e.target.value.replace(/[^0-9]/g, "") || 0) });
    return h("div", null,
      h("p", { className: "muted", style: { fontSize: 14, marginBottom: 16, lineHeight: 1.5 } }, "Set how continuous assessment and exams combine. Weights must total 100."),
      h("div", { className: "row", style: { gap: 12, alignItems: "flex-end" } },
        [["CA 1", "ca1"], ["CA 2", "ca2"], ["Exam", "exam"]].map(([l, k]) => h("div", { key: k, className: "field", style: { flex: 1 } }, h("label", null, l + " max"), h(Input, { value: String(a[k]), error: sum !== 100, onChange: setW(k) }))),
        h("div", { style: { textAlign: "center", paddingBottom: 8 } }, h("div", { className: "eyebrow" }, "Total"), h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 26, color: sum === 100 ? "var(--ok-fg)" : "var(--bad-fg)" } }, sum))),
      errors.assessment && h("div", { className: "errmsg", style: { marginTop: 10 } }, h(Icon, { name: "alert" }), errors.assessment),
      h("div", { className: "card", style: { padding: 16, marginTop: 18 } },
        h("div", { style: { fontWeight: 600, fontSize: 14 } }, "Promotion threshold"),
        h("div", { className: "muted", style: { fontSize: 12.5, margin: "3px 0 12px" } }, "Cumulative average to be promoted to the next class"),
        h("div", { className: "row", style: { gap: 14 } }, h("input", { type: "range", min: 30, max: 70, value: a.promotion, onChange: (e) => set("assessment", { promotion: Number(e.target.value) }), style: { flex: 1 } }), h("span", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 22, width: 56 }, className: "tnum" }, a.promotion + "%"))),
      h("div", { className: "card", style: { padding: 16, marginTop: 14 } },
        h("div", { className: "eyebrow", style: { marginBottom: 10 } }, "Grade bands (WAEC-style)"),
        h("div", { className: "row", style: { gap: 6, flexWrap: "wrap" } }, D.ASSESSMENT.gradeBands.map((b) => h("span", { key: b.grade, className: "tag" }, b.grade + " ≥ " + b.min)))));
  }

  /* ---- Fees: editable per level ---- */
  function FeesStep({ cfg, setCfg }) {
    const setFee = (level, v) => setCfg((c) => ({ ...c, fees: { ...c.fees, [level]: Number(v.replace(/[^0-9]/g, "") || 0) } }));
    return h("div", null,
      h("p", { className: "muted", style: { fontSize: 14, marginBottom: 16, lineHeight: 1.5 } }, "Set the per-term fee for each level. You can break these into line items later in Finance settings."),
      h("div", { className: "card", style: { padding: 4 } }, Object.keys(cfg.fees).map((level, i) =>
        h("div", { key: level, style: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: "11px 16px", borderTop: i ? "1px solid var(--line-soft)" : "none" } },
          h("span", { style: { fontWeight: 500, fontSize: 14 } }, level),
          h(Input, { value: String(cfg.fees[level]), lead: "₦", onChange: (e) => setFee(level, e.target.value), style: { width: 170 } })))));
  }

  /* ---- Integrations: connect toggles ---- */
  function IntegrationsStep({ cfg, setCfg }) {
    const toggle = (id) => setCfg((c) => ({ ...c, integrations: { ...c.integrations, [id]: !c.integrations[id] } }));
    return h("div", null,
      h("p", { className: "muted", style: { fontSize: 14, marginBottom: 16, lineHeight: 1.5 } }, "Switch on the services you'll use. You can add credentials any time in Settings → Integrations."),
      h("div", { className: "card" }, D.INTEGRATIONS.map((it, i) =>
        h("div", { key: it.id, style: { display: "flex", alignItems: "center", gap: 12, padding: "13px 16px", borderTop: i ? "1px solid var(--line-soft)" : "none" } },
          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" : it.category === "AI" ? "star" : it.category === "Backups" ? "database" : "bell" })),
          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.desc)),
          h(Toggle, { on: !!cfg.integrations[it.id], onChange: () => toggle(it.id) })))));
  }

  /* ---- Access: enable roles ---- */
  function AccessStep({ cfg, setCfg, errors }) {
    const toggle = (id) => setCfg((c) => ({ ...c, access: { ...c.access, [id]: !c.access[id] } }));
    return h("div", null,
      h("p", { className: "muted", style: { fontSize: 14, marginBottom: 16, lineHeight: 1.5 } }, "Choose which predefined roles to enable for your school. You can build custom roles later in Roles & access."),
      errors.access && h("div", { className: "errmsg", style: { marginBottom: 12 } }, h(Icon, { name: "alert" }), errors.access),
      h("div", { className: "card" }, D.ROLE_DEFS.filter((r) => r.predefined).map((r, i) =>
        h("div", { key: r.id, style: { display: "flex", alignItems: "center", gap: 12, padding: "13px 16px", borderTop: i ? "1px solid var(--line-soft)" : "none" } },
          h("div", { style: { width: 32, height: 32, borderRadius: 9, background: "var(--brand-soft)", color: "var(--brand-strong)", display: "grid", placeItems: "center" } }, h(Icon, { name: "shield" })),
          h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600, fontSize: 13.5 } }, r.name), h("div", { className: "muted", style: { fontSize: 12 } }, r.desc)),
          r.id === "super-admin" ? h("span", { className: "chip chip-ok" }, "Required") : h(Toggle, { on: !!cfg.access[r.id], onChange: () => toggle(r.id) })))));
  }

  window.SetupWizard = SetupWizard;
})();
