// 2FA enrollment — shown once for a manager/admin who hasn't set up an authenticator.
// GPS-007b: privileged accounts require a second factor. A leaked/observed PIN alone
// can't log in once this is enabled.
const { useState: useStateTE, useEffect: useEffectTE } = React;

function TotpEnroll({ user, onDone, onCancel }) {
  const [setup, setSetup] = useStateTE(null);   // { qr, secret, otpauth_url }
  const [loadErr, setLoadErr] = useStateTE(null);
  const [code, setCode] = useStateTE("");
  const [busy, setBusy] = useStateTE(false);
  const [err, setErr] = useStateTE(null);
  const [showSecret, setShowSecret] = useStateTE(false);

  useEffectTE(() => {
    let alive = true;
    (async () => {
      try {
        const r = await fetch("/api/auth/totp/setup", { method: "POST" });
        const d = await r.json().catch(() => ({}));
        if (!r.ok) throw new Error(d.error || "Couldn't start 2FA setup");
        if (alive) setSetup(d);
      } catch (e) { if (alive) setLoadErr(e.message); }
    })();
    return () => { alive = false; };
  }, []);

  async function confirm() {
    if (code.length !== 6 || busy) return;
    setBusy(true); setErr(null);
    try {
      const r = await fetch("/api/auth/totp/enable", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ code }),
      });
      const d = await r.json().catch(() => ({}));
      if (!r.ok) throw new Error(d.error || "Invalid code");
      onDone && onDone();
    } catch (e) { setErr(e.message); setCode(""); }
    finally { setBusy(false); }
  }

  return (
    <div className="min-h-screen w-full bg-zinc-950 text-zinc-100 flex flex-col items-center justify-center px-5 py-10 relative">
      <window.TopStripe />
      <div className="w-full max-w-[440px] flex flex-col items-center text-center gap-6">
        <div className="flex items-center gap-3">
          <window.BrandMark size={40} />
          <window.BrandWordmark />
        </div>

        <div>
          <div className="text-[13px] uppercase tracking-[0.22em] text-amber-400 mb-2">Secure your account</div>
          <h1 className="font-display text-[40px] sm:text-[52px] leading-[0.95] tracking-tight">Set up two-factor</h1>
          <p className="text-zinc-400 text-[14px] mt-3 max-w-[380px] mx-auto">
            {user?.role === "admin" ? "Admin" : "Manager"} sign-ins require an authenticator code.
            Scan this with Google Authenticator, Authy, or 1Password, then enter the 6-digit code.
          </p>
        </div>

        {loadErr ? (
          <div className="text-red-300 text-[14px]">{loadErr}</div>
        ) : !setup ? (
          <div className="text-zinc-500 text-[14px]">Generating your secure key…</div>
        ) : (
          <>
            {setup.qr && (
              <img src={setup.qr} alt="Authenticator QR code"
                className="h-52 w-52 rounded-xl bg-white p-2" />
            )}
            <button onClick={() => setShowSecret((s) => !s)}
              className="text-[12px] text-zinc-500 hover:text-zinc-300 underline underline-offset-4">
              {showSecret ? "Hide key" : "Can't scan? Enter the key manually"}
            </button>
            {showSecret && (
              <div className="font-mono text-[15px] tracking-[0.15em] text-zinc-200 bg-zinc-900 border border-zinc-800 rounded-lg px-4 py-3 break-all select-all">
                {setup.secret}
              </div>
            )}

            <div className="w-full flex flex-col items-center gap-3 mt-2">
              <input
                inputMode="numeric" autoComplete="one-time-code" maxLength={6} value={code}
                onChange={(e) => setCode(e.target.value.replace(/\D/g, "").slice(0, 6))}
                onKeyDown={(e) => { if (e.key === "Enter") confirm(); }}
                placeholder="000000" autoFocus
                className="w-[220px] text-center font-mono text-[34px] tracking-[0.4em] bg-zinc-900 border-2 border-zinc-800 focus:border-zinc-500 rounded-xl py-3 outline-none tabular-nums"
              />
              {err && <div className="text-red-300 text-[13px]">{err}</div>}
              <button onClick={confirm} disabled={code.length !== 6 || busy}
                className="h-12 w-[220px] rounded-xl bg-[#C41230] text-white font-semibold text-[15px] hover:bg-red-700 disabled:opacity-40 transition">
                {busy ? "Verifying…" : "Turn on 2FA"}
              </button>
              {onCancel && (
                <button onClick={onCancel} className="text-[13px] text-zinc-500 hover:text-zinc-300">
                  Sign out
                </button>
              )}
            </div>
          </>
        )}
      </div>
    </div>
  );
}

window.TotpEnroll = TotpEnroll;
