/* ============================================================
   HALO SMS — Authentication & account
   login · first-login · forgot · reset · account & security
   ============================================================ */
(function () {
  const { useState, h } = window.HReact;
  const D = window.HALO;

  function brandMeta() { return D.BRANDS[document.documentElement.getAttribute("data-brand")]; }

  function AuthShell({ children }) {
    const b = brandMeta();
    return h("div", { style: { display: "flex", minHeight: "100%", height: "100%" } },
      // brand panel (desktop)
      h("div", { className: "desktop-only", style: { width: "44%", maxWidth: 560, background: "var(--brand)", color: "var(--on-brand)",
        position: "relative", overflow: "hidden", display: "flex", flexDirection: "column", justifyContent: "space-between", padding: 44 } },
        h("div", { style: { position: "absolute", inset: 0, opacity: .14,
          background: "radial-gradient(120% 80% at 90% 10%, var(--accent), transparent 60%)" } }),
        h("div", { style: { position: "relative", display: "flex", alignItems: "center", gap: 12 } },
          h("div", { style: { width: 42, height: 42, borderRadius: 12, background: "rgba(255,255,255,.18)", display: "grid", placeItems: "center", fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 18 } }, b.short),
          h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 700, fontSize: 17 } }, b.name)),
        h("div", { style: { position: "relative" } },
          h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 800, fontSize: 34, letterSpacing: "-0.02em", lineHeight: 1.1 } }, "Run the whole school from one calm place."),
          h("p", { style: { fontSize: 15, opacity: .85, marginTop: 16, lineHeight: 1.6, maxWidth: 380 } }, "Fees, results, assessments and people — for staff and families alike. " + b.motto + ".")),
        h("div", { style: { position: "relative", fontFamily: "var(--fs-mono)", fontSize: 11.5, opacity: .7, letterSpacing: ".05em" } }, "HALO SMS · " + b.type)),
      // form side
      h("div", { style: { flex: 1, display: "flex", alignItems: "center", justifyContent: "center", padding: 24, overflowY: "auto" } },
        h("div", { style: { width: "100%", maxWidth: 380 } },
          h("div", { className: "mobile-only", style: { display: "flex", alignItems: "center", gap: 11, marginBottom: 26, justifyContent: "center" } },
            h("div", { className: "logo" }, b.short), h("div", { style: { fontFamily: "var(--fs-display)", fontWeight: 700, fontSize: 17 } }, b.name)),
          children)));
  }

  function Login({ navigate, onAuth }) {
    const [mode, setMode] = useState("email");
    const [id, setId] = useState("folake.adebayo@brightfuture.edu.ng");
    const [pw, setPw] = useState("password");
    const [busy, setBusy] = useState(false);
    const [error, setError] = useState("");
    function go() {
      setError("");
      if (!id.trim() || !pw) { setError("Enter your details to continue"); return; }
      setBusy(true); setTimeout(() => { setBusy(false); onAuth(); }, 700);
    }
    return h(AuthShell, null,
      h("h1", { style: { fontSize: 26 } }, "Welcome back"),
      h("p", { className: "muted", style: { fontSize: 14, marginTop: 6, marginBottom: 22 } }, "Sign in to continue to your school."),
      h("button", { className: "btn btn-ghost btn-block btn-lg", style: { marginBottom: 16 }, onClick: () => { setBusy(true); setTimeout(onAuth, 600); } },
        h("span", { className: "ic", dangerouslySetInnerHTML: { __html: "<svg viewBox='0 0 24 24' width='18' height='18'><path fill='#4285F4' d='M21.6 12.2c0-.7-.06-1.3-.18-1.9H12v3.6h5.4a4.6 4.6 0 0 1-2 3v2.5h3.2c1.9-1.7 3-4.3 3-7.2'/><path fill='#34A853' d='M12 22c2.7 0 5-1 6.6-2.6l-3.2-2.5c-.9.6-2 1-3.4 1-2.6 0-4.8-1.7-5.6-4.1H3.1v2.6A10 10 0 0 0 12 22'/><path fill='#FBBC05' d='M6.4 13.8a6 6 0 0 1 0-3.6V7.6H3.1a10 10 0 0 0 0 8.8z'/><path fill='#EA4335' d='M12 6.4c1.5 0 2.8.5 3.8 1.5l2.8-2.8A10 10 0 0 0 3.1 7.6l3.3 2.6C7.2 8 9.4 6.4 12 6.4'/></svg>" } }),
        "Continue with Google"),
      h("div", { style: { display: "flex", alignItems: "center", gap: 12, margin: "4px 0 18px", color: "var(--ink-400)", fontSize: 12.5 } },
        h("div", { style: { flex: 1, height: 1, background: "var(--line)" } }), "or", h("div", { style: { flex: 1, height: 1, background: "var(--line)" } })),
      h("div", { style: { marginBottom: 14 } }, h(Segmented, { value: mode, onChange: setMode, options: [{ value: "email", label: "Email" }, { value: "phone", label: "Phone" }] })),
      h("div", { style: { display: "flex", flexDirection: "column", gap: 14 } },
        h(Field, { label: mode === "email" ? "Email address" : "Phone number" },
          h(Input, { value: id, onChange: (e) => setId(e.target.value), error: !!error, lead: mode === "phone" ? "+234" : null, type: mode === "email" ? "email" : "tel" })),
        h(Field, { label: "Password", error: error || null },
          h(Input, { type: "password", value: pw, onChange: (e) => setPw(e.target.value), error: !!error })),
        h("div", { style: { display: "flex", justifyContent: "flex-end", marginTop: -4 } },
          h("button", { className: "btn btn-quiet btn-sm", onClick: () => navigate("forgot") }, "Forgot password?")),
        h(Button, { kind: "primary", size: "lg", block: true, disabled: busy, onClick: go }, busy ? "Signing in…" : "Sign in"),
        h("div", { style: { textAlign: "center", marginTop: 6 } },
          h("button", { className: "btn btn-quiet btn-sm", onClick: () => navigate("first-login") }, "First time here? Set your password"))));
  }

  function Forgot({ navigate }) {
    const [sent, setSent] = useState(false);
    const [val, setVal] = useState("");
    return h(AuthShell, null,
      h(Button, { kind: "quiet", icon: "arrowleft", onClick: () => navigate("login"), style: { marginBottom: 18, marginLeft: -8 } }, "Back to sign in"),
      sent
        ? h("div", null,
            h("div", { style: { width: 48, height: 48, borderRadius: 13, background: "var(--ok-bg)", color: "var(--ok-fg)", display: "grid", placeItems: "center", fontSize: 22, marginBottom: 16 } }, h(Icon, { name: "mail" })),
            h("h1", { style: { fontSize: 24 } }, "Check your inbox"),
            h("p", { className: "muted", style: { fontSize: 14, marginTop: 8, lineHeight: 1.6 } }, "If an account exists for ", h("b", { style: { color: "var(--ink-800)" } }, val || "that address"), ", we've sent a link to reset your password. It expires in 30 minutes."),
            h(Button, { kind: "ghost", block: true, onClick: () => navigate("reset"), style: { marginTop: 20 } }, "I have a reset code"))
        : h("div", null,
            h("h1", { style: { fontSize: 24 } }, "Reset your password"),
            h("p", { className: "muted", style: { fontSize: 14, marginTop: 8, marginBottom: 20, lineHeight: 1.6 } }, "Enter the email or phone on your account and we'll send a reset link."),
            h(Field, { label: "Email or phone" }, h(Input, { value: val, onChange: (e) => setVal(e.target.value), placeholder: "you@example.com" })),
            h(Button, { kind: "primary", size: "lg", block: true, style: { marginTop: 16 }, onClick: () => setSent(true) }, "Send reset link")));
  }

  function strength(pw) {
    let s = 0; if (pw.length >= 8) s++; if (/[A-Z]/.test(pw)) s++; if (/[0-9]/.test(pw)) s++; if (/[^A-Za-z0-9]/.test(pw)) s++;
    return s;
  }
  function PasswordSet({ navigate, onAuth, first }) {
    const [pw, setPw] = useState("");
    const [c, setC] = useState("");
    const s = strength(pw);
    const labels = ["Too weak", "Weak", "Fair", "Good", "Strong"];
    const tones = ["bad", "bad", "warn", "ok", "ok"];
    const mismatch = c && c !== pw;
    const ok = pw.length >= 8 && s >= 3 && c === pw;
    return h(AuthShell, null,
      !first && h(Button, { kind: "quiet", icon: "arrowleft", onClick: () => navigate("login"), style: { marginBottom: 18, marginLeft: -8 } }, "Back to sign in"),
      h("div", { style: { width: 48, height: 48, borderRadius: 13, background: "var(--brand-soft)", color: "var(--brand-strong)", display: "grid", placeItems: "center", fontSize: 22, marginBottom: 16 } }, h(Icon, { name: first ? "key" : "lock" })),
      h("h1", { style: { fontSize: 24 } }, first ? "Set your password" : "Choose a new password"),
      h("p", { className: "muted", style: { fontSize: 14, marginTop: 8, marginBottom: 20, lineHeight: 1.6 } },
        first ? "Your account was created by the school. Choose a password you'll remember to finish setting up." : "Pick a strong password you haven't used before."),
      h("div", { style: { display: "flex", flexDirection: "column", gap: 14 } },
        h(Field, { label: "New password" }, h(Input, { type: "password", value: pw, onChange: (e) => setPw(e.target.value), placeholder: "At least 8 characters" })),
        pw && h("div", null,
          h("div", { style: { display: "flex", gap: 5, marginBottom: 6 } }, [0,1,2,3].map((i) =>
            h("div", { key: i, style: { flex: 1, height: 4, borderRadius: 99, background: i < s ? `var(--${tones[s]})` : "var(--surface-3)" } }))),
          h("div", { style: { fontSize: 12, color: `var(--${tones[s]}-fg)`, fontWeight: 600 } }, labels[s])),
        h(Field, { label: "Confirm password", error: mismatch ? "Passwords don't match" : null }, h(Input, { type: "password", value: c, onChange: (e) => setC(e.target.value), error: mismatch })),
        h(Button, { kind: "primary", size: "lg", block: true, disabled: !ok, onClick: () => { toast("Password set"); onAuth(); } }, first ? "Finish & sign in" : "Update password")));
  }

  function Auth({ screen, navigate, onAuth }) {
    if (screen === "forgot") return h(Forgot, { navigate });
    if (screen === "reset") return h(PasswordSet, { navigate, onAuth });
    if (screen === "first-login") return h(PasswordSet, { navigate, onAuth, first: true });
    return h(Login, { navigate, onAuth });
  }

  /* ------------- in-app: Account & security ------------- */
  function AccountSecurity() {
    const [modal, setModal] = useState(false);
    const sessions = [
      ["This device · Chrome on macOS", "Lagos, NG · active now", true],
      ["Safari on iPhone", "Lagos, NG · 2 days ago", false],
      ["Chrome on Windows", "Ibadan, NG · 1 week ago", false],
    ];
    return h("div", { className: "page-pad", style: { maxWidth: 760 } },
      h("div", { className: "eyebrow", style: { marginBottom: 7 } }, "Your account"),
      h("h1", { style: { fontSize: 27, marginBottom: 22 } }, "Account & security"),
      h("div", { className: "card", style: { marginBottom: 16 } },
        h("div", { className: "card-h" }, h("div", null, h("h3", null, "Password"), h("div", { className: "sub" }, "Last changed 3 months ago")),
          h(Button, { kind: "ghost", icon: "lock", onClick: () => setModal(true) }, "Change password")),
        h("div", { className: "card-pad", style: { display: "flex", gap: 14, alignItems: "center" } },
          h(Avatar, { name: D.IDENTITY.name, size: 46, variant: "brand" }),
          h("div", null, h("div", { style: { fontWeight: 600 } }, D.IDENTITY.name),
            h("div", { className: "muted", style: { fontSize: 13 } }, D.IDENTITY.email)))),
      h("div", { className: "card", style: { marginBottom: 16 } },
        h("div", { className: "card-h" }, h("h3", null, "Linked sign-in methods")),
        h("div", { className: "card-pad", style: { display: "flex", flexDirection: "column", gap: 12 } },
          [["mail", "Email & password", "folake.adebayo@brightfuture.edu.ng", true], ["google", "Google", "Connected", true], ["phone", "Phone OTP", "Not linked", false]].map(([ic, t, sub, on]) =>
            h("div", { key: t, style: { display: "flex", alignItems: "center", gap: 12 } },
              h("div", { className: "iconbtn", style: { cursor: "default" } }, h(Icon, { name: ic })),
              h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 600, fontSize: 14 } }, t), h("div", { className: "muted", style: { fontSize: 12.5 } }, sub)),
              h("span", { className: "chip " + (on ? "chip-ok" : "chip-neutral") }, on ? "Linked" : "Link"))))),
      h("div", { className: "card" },
        h("div", { className: "card-h" }, h("h3", null, "Active sessions")),
        h("div", null, sessions.map((s, i) =>
          h("div", { key: i, style: { display: "flex", alignItems: "center", gap: 12, padding: "14px 20px", borderTop: i ? "1px solid var(--line-soft)" : "none" } },
            h("div", { style: { width: 8, height: 8, borderRadius: 99, background: s[2] ? "var(--ok)" : "var(--ink-400)" } }),
            h("div", { style: { flex: 1 } }, h("div", { style: { fontWeight: 500, fontSize: 14 } }, s[0]), h("div", { className: "muted", style: { fontSize: 12.5 } }, s[1])),
            s[2] ? h("span", { className: "chip chip-ok" }, "Current") : h("button", { className: "btn btn-quiet btn-sm" }, "Revoke")))),
        h("div", { style: { padding: 16, borderTop: "1px solid var(--line)" } }, h(Button, { kind: "danger-soft", icon: "logout" }, "Sign out everywhere"))),
      modal && h(ChangePw, { onClose: () => setModal(false) }));
  }
  function ChangePw({ onClose }) {
    const [cur, setCur] = useState(""); const [pw, setPw] = useState(""); const [c, setC] = useState("");
    const ok = cur && pw.length >= 8 && pw === c;
    return h(Modal, { icon: "lock", title: "Change password", onClose,
      footer: h(React.Fragment, null, h(Button, { kind: "ghost", onClick: onClose }, "Cancel"),
        h(Button, { kind: "primary", disabled: !ok, onClick: () => { toast("Password updated"); onClose(); } }, "Update password")) },
      h("div", { style: { display: "flex", flexDirection: "column", gap: 14 } },
        h(Field, { label: "Current password" }, h(Input, { type: "password", value: cur, onChange: (e) => setCur(e.target.value) })),
        h(Field, { label: "New password", hint: "At least 8 characters" }, h(Input, { type: "password", value: pw, onChange: (e) => setPw(e.target.value) })),
        h(Field, { label: "Confirm new password", error: c && c !== pw ? "Doesn't match" : null }, h(Input, { type: "password", value: c, onChange: (e) => setC(e.target.value), error: c && c !== pw }))));
  }

  window.Auth = Auth;
  window.AccountSecurity = AccountSecurity;
})();
