/* ============================================================
   HALO SMS — root: state, layout switch, routing
   ============================================================ */
(function () {
  const { useState, useEffect, h } = window.HReact;
  const D = window.HALO;
  const STAFF = ["admin", "principal", "class-teacher", "subject-teacher", "bursar"];
  const AUTH_SCREENS = ["login", "forgot", "reset", "first-login"];

  function defaultRoute(role) { return "dashboard"; }

  function SetupStub({ navigate }) {
    return h("div", { style: { flex: 1, display: "grid", placeItems: "center", padding: 24, overflowY: "auto" } },
      h("div", { style: { maxWidth: 520, textAlign: "center" } },
        h("div", { style: { width: 60, height: 60, borderRadius: 17, background: "var(--brand-soft)", color: "var(--brand-strong)", display: "grid", placeItems: "center", fontSize: 28, margin: "0 auto 20px" } }, h(Icon, { name: "graduation" })),
        h("h1", { style: { fontSize: 28 } }, "First-boot setup wizard"),
        h("p", { className: "muted", style: { fontSize: 15, lineHeight: 1.6, marginTop: 12 } },
          "The 8-step guided setup — school profile, academic structure, assessment rules, fees, integrations, access, super-admin and finish — is scheduled for Batch 5."),
        h("div", { style: { display: "flex", flexWrap: "wrap", gap: 8, justifyContent: "center", margin: "22px 0" } },
          ["School profile","Academic structure","Assessment rules","Fees","Integrations","Access","Super-admin","Done"].map((s, i) =>
            h("span", { key: s, className: "chip chip-neutral" }, h("span", { className: "mono", style: { color: "var(--brand)" } }, "0" + (i + 1)), s))),
        h(Button, { kind: "primary", onClick: () => navigate("__role:admin") }, "Skip to the dashboard")));
  }

  function App() {
    const [theme, setTheme] = useState(() => localStorage.getItem("halo-theme") || "light");
    const [brand, setBrand] = useState(() => localStorage.getItem("halo-brand") || "bright-future");
    const [role, setRoleRaw] = useState(() => localStorage.getItem("halo-role") || "admin");
    const [authed, setAuthed] = useState(false);
    const [route, setRoute] = useState("login");
    const [roster, setRoster] = useState(() => D.students.map((s) => ({ ...s })));
    const [staffList, setStaffList] = useState(() => D.staff.map((s) => ({ ...s })));
    const [roles, setRoles] = useState(() => D.ROLE_DEFS.map((r) => ({ ...r })));
    const [guardianList, setGuardianList] = useState(() => Object.values(D.guardians).map((g) => ({ ...g })));
    const [assess, setAssess] = useState(() => ({ ...D.ASSESSMENT }));

    useEffect(() => { document.documentElement.setAttribute("data-theme", theme); localStorage.setItem("halo-theme", theme); }, [theme]);
    useEffect(() => { document.documentElement.setAttribute("data-brand", brand); localStorage.setItem("halo-brand", brand); }, [brand]);
    useEffect(() => { localStorage.setItem("halo-role", role); }, [role]);

    function setRole(r) {
      setRoleRaw(r);
      if (r === "setup") { setAuthed(true); setRoute("setup"); return; }
      setAuthed(true); // demo: switching role previews the app directly
      setRoute(defaultRoute(r));
    }
    function navigate(r) {
      if (r === "signout") { setAuthed(false); setRoute("login"); return; }
      if (r.startsWith("__role:")) { setRole(r.split(":")[1]); return; }
      setRoute(r);
      const el = document.querySelector(".page, .familywrap, .scroll"); // gentle scroll reset
      if (el) el.scrollTop = 0;
    }
    function upsertStudent(s) {
      setRoster((prev) => { const i = prev.findIndex((x) => x.id === s.id); if (i === -1) return [s, ...prev]; const n = prev.slice(); n[i] = s; return n; });
    }

    const upsert = (s) => upsertStudent(s);
    function upsertStaff(s) { setStaffList((p) => { const i = p.findIndex((x) => x.id === s.id); if (i === -1) return [s, ...p]; const n = p.slice(); n[i] = s; return n; }); }
    function upsertRole(r) { setRoles((p) => { const i = p.findIndex((x) => x.id === r.id); if (i === -1) return [...p, r]; const n = p.slice(); n[i] = r; return n; }); }
    function upsertGuardian(g) { setGuardianList((p) => { const i = p.findIndex((x) => x.id === g.id); if (i === -1) return [g, ...p]; const n = p.slice(); n[i] = g; return n; }); }
    function onLinkUpdate(gid, linked, primaryMap) {
      setGuardianList((p) => p.map((g) => g.id === gid ? { ...g, children: linked } : g));
      setRoster((prev) => prev.map((s) => {
        if (primaryMap[s.id]) return { ...s, guardian: gid, primary: true };
        if (s.guardian === gid && linked.includes(s.id) && !primaryMap[s.id]) return { ...s, primary: false };
        return s;
      }));
    }

    let body;
    if (!authed) {
      const screen = AUTH_SCREENS.includes(route) ? route : "login";
      body = h(window.Auth, { screen, navigate, onAuth: () => { setAuthed(true); setRoute(role === "setup" ? "setup" : defaultRoute(role)); } });
    } else if (role === "setup") {
      body = h(window.SetupWizard, { navigate });
    } else if (role === "parent") {
      body = h(window.ParentApp, { roster, upsertStudent: upsert });
    } else if (role === "student") {
      body = h(window.StudentApp, { roster });
    } else {
      body = h(window.StaffShell, { role, setRole, route: AUTH_SCREENS.includes(route) ? "dashboard" : route, navigate, onSignOut: () => navigate("signout"),
        roster, upsertStudent: upsert, staffList, upsertStaff, roles, upsertRole, guardianList, upsertGuardian, onLinkUpdate, assess, setAssess });
    }

    const [tourRun, setTourRun] = useState(false);

    return h("div", { className: "app" },
      h(window.DemoToolbar, { role, setRole, theme, setTheme, brand, setBrand, onTour: () => setTourRun(true) }),
      h("div", { style: { flex: 1, minHeight: 0, display: "flex", flexDirection: "column" } }, body),
      h(window.Tour, { run: tourRun, role: authed ? role : "guest", onClose: () => setTourRun(false) }),
      h(ToastHost, null));
  }

  ReactDOM.createRoot(document.getElementById("root")).render(h(App, null));
})();
