function MfaEnrollStep({ onDone, data }) {
  const [mode, setMode] = React.useState(null);
  const [totp, setTotp] = React.useState(null);
  const [err, setErr] = React.useState(null);
  const [busy, setBusy] = React.useState(false);

  async function setupPasskey() {
    setErr(null); setBusy(true);
    try {
      const r = await fetch(`${window.__bs_api}/api/auth/mfa/passkey/register/options`, {
        method: "POST", credentials: "include",
        headers: { "content-type": "application/json", "x-csrf-token": window.__bs_csrf },
      });
      if (!r.ok) throw new Error("Could not fetch passkey options.");
      const { options, challenge_key } = await r.json();
      const cred = await navigator.credentials.create({ publicKey: options });
      const verify = await fetch(`${window.__bs_api}/api/auth/mfa/passkey/register/verify`, {
        method: "POST", credentials: "include",
        headers: { "content-type": "application/json", "x-csrf-token": window.__bs_csrf },
        body: JSON.stringify({ challenge_key, response: cred, name: "Default device" }),
      });
      if (!verify.ok) throw new Error("Passkey registration failed.");
      onDone();
    } catch (e) {
      setErr(e.message || String(e));
    } finally { setBusy(false); }
  }

  async function setupTotp() {
    setErr(null); setBusy(true);
    try {
      const r = await fetch(`${window.__bs_api}/api/auth/mfa/totp/setup`, {
        method: "POST", credentials: "include",
        headers: { "content-type": "application/json", "x-csrf-token": window.__bs_csrf },
      });
      if (!r.ok) throw new Error("TOTP setup failed.");
      setTotp(await r.json()); setMode("totp");
    } catch (e) { setErr(e.message || String(e)); }
    finally { setBusy(false); }
  }

  async function confirmTotp(e) {
    e.preventDefault();
    setErr(null); setBusy(true);
    try {
      const code = new FormData(e.currentTarget).get("code");
      const v = await fetch(`${window.__bs_api}/api/auth/mfa/totp/verify`, {
        method: "POST", credentials: "include",
        headers: { "content-type": "application/json", "x-csrf-token": window.__bs_csrf },
        body: JSON.stringify({ code, name: "Authenticator" }),
      });
      if (!v.ok) throw new Error("Wrong code.");
      onDone();
    } catch (e) { setErr(e.message || String(e)); }
    finally { setBusy(false); }
  }

  if (mode === "totp" && totp) {
    return (
      <form onSubmit={confirmTotp} className="bs-form bs-auth-form">
        <p>Scan the URI below with your authenticator app, then enter the 6-digit code:</p>
        <pre className="bs-auth-totp-uri">{totp.provisioning_uri}</pre>
        <label className="bs-formfield">
          <span>6-digit code</span>
          <input name="code" required pattern="[0-9]{6}" inputMode="numeric" />
        </label>
        <button type="submit" className="bs-formsubmit" disabled={busy}>Confirm</button>
        {err && <p className="bs-auth-error">{err}</p>}
      </form>
    );
  }

  return (
    <div className="bs-mfa-picker">
      <button onClick={setupPasskey} className="bs-formsubmit" disabled={busy}>{data.primaryCta}</button>
      <button onClick={setupTotp} className="bs-formsubmit bs-formsubmit-alt" disabled={busy}>{data.secondaryCta}</button>
      {err && <p className="bs-auth-error">{err}</p>}
    </div>
  );
}
window.MfaEnrollStep = MfaEnrollStep;
