// auth.jsx - sign up / log in + profile-type branch (exported to window)
const { useState: useStateA } = React;

function Auth({ tweaks, onComplete, onBack, isDark, onToggleTheme, fromGuest = false, guestCount = 0, guestValue = 0, guestProfile = "individual", initialMode = "signup", resetToken = null }) {
  // step: profile -> form -> (handled by parent onComplete -> onboarding chat)
  // Always start by asking who the account is for, including when saving a guest
  // vault. We pre-highlight the type inferred from the chat, but the user confirms
  // personal vs business, so each routes to the right experience.
  const [step, setStep] = useStateA("profile");
  const [profile, setProfile] = useStateA(fromGuest ? guestProfile : null);
  // Honour initialMode even for guests: a guest may be routed to LOG IN (they
  // already have an account) with their guest vault carrying over after auth.
  const [mode, setMode] = useStateA(initialMode); // signup | login
  const logoV = tweaks.logoVariant || "vault";
  const D = window.VC_DATA;
  const fmtV = D ? D.fmtNaira(guestValue) : guestValue;

  const choose = (p) => { setProfile(p); setStep("form"); };

  return (
    <div className="vc-auth-grid" style={{ height: "100%", display: "grid", gridTemplateColumns: "1.1fr 1fr", background: "var(--bg)" }}>
      {/* LEFT - brand panel */}
      <div className="vc-auth-brand" style={{ position: "relative", overflow: "hidden", padding: "40px 54px", display: "flex", flexDirection: "column", justifyContent: "space-between", background: "linear-gradient(150deg,var(--accent) 0%,var(--accent-2) 55%,#9a80ff 100%)" }}>
        <div style={{ position: "absolute", inset: 0, opacity: 0.5, background: "radial-gradient(60% 50% at 90% 10%, rgba(255,255,255,.25), transparent 60%), radial-gradient(50% 40% at 10% 100%, rgba(255,255,255,.18), transparent 60%)" }} />
        <div style={{ position: "relative", zIndex: 2 }}>
          <div onClick={onBack} style={{ cursor: "pointer", display: "inline-flex" }}><window.Logo variant={logoV} size={34} onDark /></div>
        </div>
        <div style={{ position: "relative", zIndex: 2 }}>
          {fromGuest && guestCount > 0 ? (
            <>
              <div style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "6px 13px", borderRadius: 999, background: "rgba(255,255,255,.18)", backdropFilter: "blur(6px)", color: "#fff", fontSize: 12.5, fontWeight: 700, marginBottom: 18 }}>
                <window.Icon name="vault" size={14} />Your vault is ready to save
              </div>
              <h1 className="display" style={{ fontSize: 44, color: "#fff", lineHeight: 1.05 }}>Lock in everything<br/>you just told Cova.</h1>
              <p style={{ color: "rgba(255,255,255,.9)", fontSize: 17, marginTop: 16, maxWidth: 380, lineHeight: 1.5 }}>Create your account and your vault - <b>{guestCount} asset{guestCount > 1 ? "s" : ""} worth {fmtV}</b> - moves straight in. Nothing to re-enter.</p>
              <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 30 }}>
                {[["check", "Your conversation continues, uninterrupted"], ["vault", "Every asset already valued & scored"], ["shield", "Get matched cover in one more step"]].map(([ic, tx]) => (
                  <div key={tx} style={{ display: "flex", alignItems: "center", gap: 12, color: "#fff" }}>
                    <span style={{ display: "grid", placeItems: "center", width: 36, height: 36, borderRadius: 11, background: "rgba(255,255,255,.18)", backdropFilter: "blur(6px)" }}><window.Icon name={ic} size={19} /></span>
                    <span style={{ fontSize: 15, fontWeight: 600 }}>{tx}</span>
                  </div>
                ))}
              </div>
            </>
          ) : (
            <>
              <h1 className="display" style={{ fontSize: 46, color: "#fff", lineHeight: 1.05 }}>Everything you own,<br/>in one secure vault.</h1>
              <p style={{ color: "rgba(255,255,255,.88)", fontSize: 17, marginTop: 16, maxWidth: 380, lineHeight: 1.5 }}>Track real replacement costs, spot coverage gaps, and insure in plain language.</p>
              <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 32 }}>
                {[["vault","Your VaultLog, private & encrypted"],["sparkle","Cova co-pilot for every decision"],["shield","Cover individually or bundled"]].map(([ic,tx]) => (
                  <div key={tx} style={{ display: "flex", alignItems: "center", gap: 12, color: "#fff" }}>
                    <span style={{ display: "grid", placeItems: "center", width: 36, height: 36, borderRadius: 11, background: "rgba(255,255,255,.18)", backdropFilter: "blur(6px)" }}><window.Icon name={ic} size={19} /></span>
                    <span style={{ fontSize: 15, fontWeight: 600 }}>{tx}</span>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>
        <div style={{ position: "relative", zIndex: 2, color: "rgba(255,255,255,.7)", fontSize: 13 }}>Trusted by businesses and individuals across Nigeria</div>
      </div>

      {/* RIGHT - auth flow */}
      <div style={{ position: "relative", display: "grid", placeItems: "center", padding: 40, overflowY: "auto" }}>
        <button onClick={onToggleTheme} style={{ position: "absolute", top: 24, right: 24, display: "grid", placeItems: "center", width: 40, height: 40, borderRadius: 999, color: "var(--text-muted)", border: "1px solid var(--border)" }}><window.Icon name={isDark ? "sun" : "moon"} size={18} /></button>

        {resetToken && <ResetPwForm token={resetToken} onDone={(acct) => onComplete((acct && acct.type) || null, "login", acct)} />}

        {!resetToken && step === "profile" && (
          <div style={{ width: "100%", maxWidth: 420, animation: "vc-fade-up .5s var(--ease) both" }}>
            {fromGuest && guestCount > 0 && (
              <div style={{ display: "inline-flex", alignItems: "center", gap: 7, padding: "5px 12px", borderRadius: 999, background: "var(--accent-soft)", color: "var(--accent-ink)", fontSize: 12.5, fontWeight: 700, marginBottom: 12 }}>
                <window.Icon name="vault" size={14} />{guestCount} asset{guestCount > 1 ? "s" : ""} ready to save
              </div>
            )}
            <h2 className="display" style={{ fontSize: 30 }}>{mode === "login" ? "Welcome back" : (fromGuest ? "Let's save your vault" : "Let's set up your vault")}</h2>
            <p style={{ color: "var(--text-muted)", fontSize: 15.5, marginTop: 8 }}>
              {mode === "login"
                ? "Which vault are you logging into? Personal and business are kept separate."
                : (fromGuest ? "First, is this for you, or for your business? We'll set up the right kind of account and carry everything you just told Cova straight into it." : "Who is VaultCova for? This tailors your whole experience.")}
            </p>
            <div style={{ display: "grid", gap: 14, marginTop: 26 }}>
              <ProfileCard icon="user" title={mode === "login" ? "My personal vault" : "For myself"} desc="Home, car, valuables & personal electronics" onClick={() => choose("individual")} hint={!fromGuest || mode === "login" ? null : guestProfile === "individual" ? "Suggested" : null} />
              <ProfileCard icon="building" title={mode === "login" ? "My business vault" : "For my business"} desc="Fleet, premises, plant, inventory & cargo" onClick={() => choose("business")} accent hint={!fromGuest || mode === "login" ? null : guestProfile === "business" ? "Suggested" : null} />
            </div>
            <div style={{ textAlign: "center", marginTop: 26, fontSize: 14, color: "var(--text-muted)" }}>
              {mode === "login"
                ? <>New to VaultCova? <button onClick={() => setMode("signup")} style={{ color: "var(--accent)", fontWeight: 700 }}>Create a vault</button></>
                : <>Already have a vault? <button onClick={() => setMode("login")} style={{ color: "var(--accent)", fontWeight: 700 }}>Log in</button></>}
            </div>
          </div>
        )}

        {!resetToken && step === "form" && (
          <AuthForm mode={mode} profile={profile} onBack={() => setStep("profile")} onSubmit={(identity) => onComplete(profile, mode, identity)} setMode={setMode} fromGuest={fromGuest} guestCount={guestCount} />
        )}
      </div>
    </div>
  );
}

function ProfileCard({ icon, title, desc, onClick, accent, hint }) {
  const [h, setH] = useStateA(false);
  return (
    <button onClick={onClick} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)} style={{
      display: "flex", alignItems: "center", gap: 16, padding: 20, borderRadius: 18, textAlign: "left",
      background: "var(--surface)", border: "1.5px solid " + (h || hint ? "var(--accent)" : "var(--border)"),
      boxShadow: h ? "var(--shadow-glow)" : "var(--shadow-sm)", transition: "all .25s var(--ease)",
      transform: h ? "translateY(-2px)" : "none",
    }}>
      <span style={{ display: "grid", placeItems: "center", width: 52, height: 52, borderRadius: 15, background: accent ? "var(--accent)" : "var(--accent-soft)", color: accent ? "#fff" : "var(--accent)", flexShrink: 0 }}><window.Icon name={icon} size={26} /></span>
      <div style={{ flex: 1 }}>
        <div className="display" style={{ fontSize: 19, display: "flex", alignItems: "center", gap: 8 }}>{title}{hint && <span style={{ fontSize: 10.5, fontWeight: 700, padding: "2px 8px", borderRadius: 999, background: "var(--accent-soft)", color: "var(--accent-ink)" }}>{hint}</span>}</div>
        <div style={{ fontSize: 13.5, color: "var(--text-muted)", marginTop: 3 }}>{desc}</div>
      </div>
      <window.Icon name="arrowR" size={20} style={{ color: h ? "var(--accent)" : "var(--text-faint)" }} />
    </button>
  );
}

function AuthForm({ mode, profile, onBack, onSubmit, setMode, fromGuest = false, guestCount = 0 }) {
  const [loading, setLoading] = useStateA(false);
  // Names are collected as first name + surname everywhere. The account's full
  // name is "First Surname". For a business, this is the OWNER's name — the
  // business's own name is captured separately by Cova (set_business_name).
  const [firstName, setFirstName] = useStateA("");
  const [surname, setSurname] = useStateA("");
  const [bizName, setBizName] = useStateA("");
  const name = `${firstName.trim()} ${surname.trim()}`.trim();
  const [email, setEmail] = useStateA("");
  const [password, setPassword] = useStateA("");
  const [error, setError] = useStateA(null);
  const [note, setNote] = useStateA(null);
  const [forgot, setForgot] = useStateA(null); // null | "form" | "sent" — forgot-password sub-flow (login only)
  const isBiz = profile === "business";

  // Real authentication: sign-up creates a per-email account (scrypt-hashed
  // password) and login verifies against it. The server sets the session
  // cookie; the app then loads THAT account's vault.
  const submit = (e) => {
    e.preventDefault();
    if (loading) return;
    setError(null); setNote(null);
    if (mode === "signup" && (firstName.trim().length < 1 || surname.trim().length < 1)) { setError("Enter your first name and surname."); return; }
    if (mode === "signup" && isBiz && bizName.trim().length < 2) { setError("Enter your business name."); return; }
    if (!email.trim()) { setError("Enter your email address."); return; }
    if (password.length < 8) { setError("Password must be at least 8 characters."); return; }
    setLoading(true);
    fetch(mode === "signup" ? "/api/auth/signup" : "/api/auth/login", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(mode === "signup" ? { name: name.trim(), email: email.trim(), password, type: profile, businessName: isBiz ? bizName.trim() : "" } : { email: email.trim(), password }),
    })
      .then((r) => r.json().then((d) => ({ ok: r.ok, d })).catch(() => ({ ok: false, d: {} })))
      .then(({ ok, d }) => {
        if (!ok) { setLoading(false); setError(d.error || "Something went wrong. Try again."); return; }
        onSubmit(d); // the authenticated account: { id, name, role, type }
      })
      .catch(() => { setLoading(false); setError("Couldn't reach VaultCova. Check your connection and try again."); });
  };

  // Forgot-password sub-flow: ask for the email, then confirm. The server
  // answers identically whether or not the account exists (no email oracle).
  const sendReset = (e) => {
    e.preventDefault();
    if (loading) return;
    if (!email.trim()) { setError("Enter your email address."); return; }
    setError(null); setLoading(true);
    fetch("/api/auth/forgot", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: email.trim() }) })
      .then(() => { setLoading(false); setForgot("sent"); })
      .catch(() => { setLoading(false); setError("Couldn't reach VaultCova. Check your connection and try again."); });
  };
  if (forgot) {
    return (
      <form onSubmit={sendReset} style={{ width: "100%", maxWidth: 400, animation: "vc-fade-up .5s var(--ease) both" }}>
        <button type="button" onClick={() => { setForgot(null); setError(null); }} style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 13.5, fontWeight: 600, color: "var(--text-muted)", marginBottom: 18 }}><window.Icon name="arrowR" size={15} style={{ transform: "rotate(180deg)" }} /> Back to log in</button>
        <h2 className="display" style={{ fontSize: 28 }}>Reset your password</h2>
        {forgot === "sent" ? (
          <>
            <p style={{ color: "var(--text-muted)", fontSize: 14.5, marginTop: 10, lineHeight: 1.55 }}>
              If <b>{email.trim()}</b> has a VaultCova account, a reset link is on its way. It works for <b>1 hour</b>.
            </p>
            <p style={{ color: "var(--text-faint)", fontSize: 13, marginTop: 10, lineHeight: 1.5 }}>
              Nothing arriving? Check spam, or contact <b>support@vaultcova.com</b> and our team will issue you a reset link directly.
            </p>
          </>
        ) : (
          <>
            <p style={{ color: "var(--text-muted)", fontSize: 14.5, marginTop: 6 }}>Enter your account email and we'll send you a link to choose a new password.</p>
            <div style={{ display: "grid", gap: 13, marginTop: 24 }}>
              <Field label="Email address" placeholder="you@company.com" type="email" value={email} onChange={setEmail} icon="doc" />
            </div>
            {error && (
              <div role="alert" style={{ display: "flex", alignItems: "center", gap: 9, marginTop: 14, padding: "11px 13px", borderRadius: 11, background: "var(--danger-soft)", color: "var(--danger)", fontSize: 13.5, fontWeight: 600 }}>
                <window.Icon name="alert" size={16} style={{ flexShrink: 0 }} />{error}
              </div>
            )}
            <window.Btn type="submit" size="lg" iconR={loading ? null : "arrowR"} style={{ width: "100%", marginTop: 22, justifyContent: "center" }}>
              {loading ? <span style={{ display: "inline-flex", alignItems: "center", gap: 9 }}><Spinner /> Sending…</span> : "Send reset link"}
            </window.Btn>
          </>
        )}
      </form>
    );
  }

  return (
    <form onSubmit={submit} style={{ width: "100%", maxWidth: 400, animation: "vc-fade-up .5s var(--ease) both" }}>
      <button type="button" onClick={onBack} style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 13.5, fontWeight: 600, color: "var(--text-muted)", marginBottom: 18 }}><window.Icon name="arrowR" size={15} style={{ transform: "rotate(180deg)" }} /> Back</button>
      <div style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "5px 12px", borderRadius: 999, background: "var(--accent-soft)", color: "var(--accent-ink)", fontSize: 12.5, fontWeight: 700, marginBottom: 14 }}>
        <window.Icon name={isBiz ? "building" : "user"} size={14} />{isBiz ? "Business account" : "Personal account"}
      </div>
      <h2 className="display" style={{ fontSize: 28 }}>{mode === "login" ? "Welcome back" : (fromGuest ? "Save your vault" : "Create your vault")}</h2>
      <p style={{ color: "var(--text-muted)", fontSize: 14.5, marginTop: 6 }}>{mode === "login" ? (fromGuest ? "Log in and we'll add what you just built to your vault." : "Log in to your VaultLog.") : (fromGuest ? "One step - then your vault opens with everything intact." : "A minute to set up. No card required.")}</p>

      <div style={{ display: "grid", gap: 13, marginTop: 24 }}>
        {mode === "signup" && (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
            <Field label="First name" placeholder="e.g. Adebola" value={firstName} onChange={setFirstName} icon="user" />
            <Field label="Surname" placeholder="e.g. Okafor" value={surname} onChange={setSurname} icon="user" />
          </div>
        )}
        {mode === "signup" && isBiz && <div style={{ fontSize: 12, color: "var(--text-faint)", marginTop: -4 }}>Your name as the account owner.</div>}
        {mode === "signup" && isBiz && <Field label="Business name" placeholder="e.g. ABC Logistics Ltd." value={bizName} onChange={setBizName} icon="building" />}
        <Field label="Email address" placeholder="you@company.com" type="email" value={email} onChange={setEmail} icon="doc" />
        <PwField label="Password" requirements={mode === "signup"} value={password} onChange={setPassword} />
        {mode === "login" && (
          <div style={{ textAlign: "right", marginTop: -6 }}>
            <button type="button" onClick={() => setForgot("form")} style={{ fontSize: 13, fontWeight: 700, color: "var(--accent)" }}>Forgot password?</button>
          </div>
        )}
      </div>

      {error && (
        <div role="alert" style={{ display: "flex", alignItems: "center", gap: 9, marginTop: 14, padding: "11px 13px", borderRadius: 11, background: "var(--danger-soft)", color: "var(--danger)", fontSize: 13.5, fontWeight: 600 }}>
          <window.Icon name="alert" size={16} style={{ flexShrink: 0 }} />{error}
        </div>
      )}
      {note && (
        <div style={{ display: "flex", alignItems: "center", gap: 9, marginTop: 14, padding: "11px 13px", borderRadius: 11, background: "var(--accent-soft)", color: "var(--accent-ink)", fontSize: 13.5, fontWeight: 600 }}>
          <window.Icon name="sparkle" size={16} style={{ flexShrink: 0 }} />{note}
        </div>
      )}

      <window.Btn type="submit" size="lg" iconR={loading ? null : "arrowR"} style={{ width: "100%", marginTop: 22, justifyContent: "center" }}>
        {loading ? <span style={{ display: "inline-flex", alignItems: "center", gap: 9 }}><Spinner /> {mode === "login" ? "Opening your vault…" : (fromGuest ? "Saving your vault…" : "Setting up your vault…")}</span> : (mode === "login" ? "Log in" : (fromGuest ? "Save vault & continue" : "Create vault & meet Cova"))}
      </window.Btn>

      <div style={{ display: "flex", alignItems: "center", gap: 12, margin: "20px 0", color: "var(--text-faint)", fontSize: 12.5 }}>
        <div style={{ flex: 1, height: 1, background: "var(--border)" }} /> or <div style={{ flex: 1, height: 1, background: "var(--border)" }} />
      </div>
      <window.Btn variant="outline" size="lg" style={{ width: "100%", justifyContent: "center" }} onClick={(e) => { e.preventDefault(); setNote("BVN / NIN sign-in is coming soon. Use email & password for now."); }}>Continue with BVN / NIN</window.Btn>

      <div style={{ textAlign: "center", marginTop: 22, fontSize: 14, color: "var(--text-muted)" }}>
        {mode === "signup" ? "Already have a vault? " : "New to VaultCova? "}
        <button type="button" onClick={() => setMode(mode === "signup" ? "login" : "signup")} style={{ color: "var(--accent)", fontWeight: 700 }}>{mode === "signup" ? "Log in" : "Create one"}</button>
      </div>
    </form>
  );
}

function Field({ label, placeholder, type = "text", icon, defaultValue, value, onChange }) {
  const [f, setF] = useStateA(false);
  const controlled = value !== undefined;
  return (
    <label style={{ display: "block", minWidth: 0 }}>
      <span style={{ fontSize: 13, fontWeight: 600, color: "var(--text-muted)" }}>{label}</span>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 6, padding: "0 14px", borderRadius: 12, background: "var(--surface)", border: "1.5px solid " + (f ? "var(--accent)" : "var(--surface-3)"), boxShadow: f ? "none" : "var(--shadow-sm)", transition: "border-color .2s", minWidth: 0 }}>
        <window.Icon name={icon} size={17} style={{ color: f ? "var(--accent)" : "var(--text-faint)", flexShrink: 0 }} />
        <input type={type} placeholder={placeholder} {...(controlled ? { value, onChange: (e) => onChange(e.target.value) } : { defaultValue })} onFocus={() => setF(true)} onBlur={() => setF(false)}
          style={{ flex: 1, minWidth: 0, border: "none", outline: "none", background: "transparent", padding: "13px 0", fontSize: 15, color: "var(--text)" }} />
      </div>
    </label>
  );
}

// Password input with a show/hide toggle and, on sign-up, a live requirements
// checklist so users set a strong password. Controlled: the form owns the value.
function PwField({ label, requirements, value, onChange }) {
  const [f, setF] = useStateA(false);
  const [show, setShow] = useStateA(false);
  const v = value || "";
  const checks = [["8+ characters", v.length >= 8], ["Uppercase", /[A-Z]/.test(v)], ["Lowercase", /[a-z]/.test(v)], ["Number", /[0-9]/.test(v)]];
  const allOk = checks.every((c) => c[1]);
  return (
    <label style={{ display: "block", minWidth: 0 }}>
      <span style={{ fontSize: 13, fontWeight: 600, color: "var(--text-muted)" }}>{label}</span>
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 6, padding: "0 14px", borderRadius: 12, background: "var(--surface)", border: "1.5px solid " + (f ? "var(--accent)" : "var(--surface-3)"), boxShadow: f ? "none" : "var(--shadow-sm)", transition: "border-color .2s", minWidth: 0 }}>
        <window.Icon name="vault" size={17} style={{ color: f ? "var(--accent)" : "var(--text-faint)", flexShrink: 0 }} />
        <input type={show ? "text" : "password"} value={v} onChange={(e) => onChange && onChange(e.target.value)} placeholder="••••••••" onFocus={() => setF(true)} onBlur={() => setF(false)}
          style={{ flex: 1, minWidth: 0, border: "none", outline: "none", background: "transparent", padding: "13px 0", fontSize: 15, color: "var(--text)" }} />
        <button type="button" onClick={() => setShow((s) => !s)} tabIndex={-1} style={{ fontSize: 12.5, fontWeight: 700, color: "var(--text-muted)", flexShrink: 0 }}>{show ? "Hide" : "Show"}</button>
      </div>
      {requirements && v.length > 0 && !allOk && (
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "4px 10px", marginTop: 8, fontSize: 11.5 }}>
          {checks.map(([lbl, ok]) => <span key={lbl} style={{ color: ok ? "var(--success)" : "var(--text-faint)" }}>{ok ? "✓" : "○"} {lbl}</span>)}
        </div>
      )}
    </label>
  );
}

// Redeem a reset link (?reset=TOKEN): choose a new password, get signed in.
// The server validates the token (1h, single use) and answers with the same
// account shape as login, so the app proceeds exactly like a normal sign-in.
function ResetPwForm({ token, onDone }) {
  const [pw, setPw] = useStateA("");
  const [pw2, setPw2] = useStateA("");
  const [error, setError] = useStateA(null);
  const [loading, setLoading] = useStateA(false);
  const submit = (e) => {
    e.preventDefault();
    if (loading) return;
    if (pw.length < 8) { setError("Password must be at least 8 characters."); return; }
    if (pw !== pw2) { setError("Passwords don't match."); return; }
    setError(null); setLoading(true);
    fetch("/api/auth/reset", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token, password: pw }) })
      .then((r) => r.json().then((d) => ({ ok: r.ok, d })).catch(() => ({ ok: false, d: {} })))
      .then(({ ok, d }) => {
        if (!ok) { setLoading(false); setError(d.error || "This reset link has expired. Request a new one."); return; }
        try { history.replaceState({}, "", location.pathname); } catch (err) {} // drop ?reset= so a refresh can't re-submit a dead token
        onDone(d);
      })
      .catch(() => { setLoading(false); setError("Couldn't reach VaultCova. Check your connection and try again."); });
  };
  return (
    <form onSubmit={submit} style={{ width: "100%", maxWidth: 400, animation: "vc-fade-up .5s var(--ease) both" }}>
      <div style={{ display: "inline-flex", alignItems: "center", gap: 8, padding: "5px 12px", borderRadius: 999, background: "var(--accent-soft)", color: "var(--accent-ink)", fontSize: 12.5, fontWeight: 700, marginBottom: 14 }}>
        <window.Icon name="vault" size={14} />Password reset
      </div>
      <h2 className="display" style={{ fontSize: 28 }}>Choose a new password</h2>
      <p style={{ color: "var(--text-muted)", fontSize: 14.5, marginTop: 6 }}>Set it and you're straight back into your vault.</p>
      <div style={{ display: "grid", gap: 13, marginTop: 24 }}>
        <PwField label="New password" requirements value={pw} onChange={setPw} />
        <PwField label="Confirm new password" value={pw2} onChange={setPw2} />
      </div>
      {error && (
        <div role="alert" style={{ display: "flex", alignItems: "center", gap: 9, marginTop: 14, padding: "11px 13px", borderRadius: 11, background: "var(--danger-soft)", color: "var(--danger)", fontSize: 13.5, fontWeight: 600 }}>
          <window.Icon name="alert" size={16} style={{ flexShrink: 0 }} />{error}
        </div>
      )}
      <window.Btn type="submit" size="lg" iconR={loading ? null : "arrowR"} style={{ width: "100%", marginTop: 22, justifyContent: "center" }}>
        {loading ? <span style={{ display: "inline-flex", alignItems: "center", gap: 9 }}><Spinner /> Updating…</span> : "Set password & open my vault"}
      </window.Btn>
    </form>
  );
}

function Spinner({ size = 16 }) {
  return <span style={{ display: "inline-block", width: size, height: size, border: "2px solid rgba(255,255,255,.4)", borderTopColor: "#fff", borderRadius: 999, animation: "vc-spin .7s linear infinite" }} />;
}

Object.assign(window, { Auth, Spinner });
