{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "auth-flow",
  "title": "Sign-in flow",
  "description": "Neotax's sign-in, monochrome: email, then a lookup picks the step (6-digit code, password, passkey, Google-only, create account, two-step, forgot password). Server calls are props; Korean or English strings.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "@dgit/auth-page"
  ],
  "files": [
    {
      "path": "registry/dgit/blocks/auth-flow.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useLayoutEffect, useRef, useState, type FormEvent, type ReactNode } from \"react\";\nimport { CircleAlert, LoaderCircle, MailOpen } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\nimport { AuthButton, AuthCodeBoxes, AuthDivider, AuthField, AuthLayout } from \"@/registry/dgit/blocks/auth-page\";\n\n/**\n * The whole sign-in flow on one screen, from Neotax's (auth.neotax.tech): type an email, press Continue, and\n * the app's `lookup` says whether the account exists and how it signs in. The screen then branches\n * (`stepAfterLookup`):\n *\n *   no account          → create account (name, password) → 6-digit code    (signup on)\n *                       → 6-digit code by email                              (signup off, code on)\n *   has a passkey       → passkey prompt → on cancel: password, else back to email\n *   has a password      → password · \"Forgot password?\" → reset mail → \"Mail sent\"\n *   email code          → 6-digit code by email                              (code on)\n *   Google-only account → one \"Continue with Google\" button\n *   2-step account      → authenticator code or a recovery code (when a sign-in answers `twoFactor: true`)\n *\n * The block holds no URLs and no app logic: every server call is a prop, and `onDone` decides where to go.\n * Strings are Korean by default; pass `text={AUTH_TEXT_EN}` (or any part of it) for English.\n *\n *   <AuthFlow\n *     brand={<Logo />}\n *     methods={{ code: true, google: true }}\n *     lookup={(email) => api.post(\"/login/lookup\", { email })}\n *     sendCode={(email) => api.post(\"/login/code\", { email })}\n *     verifyCode={({ email, code }) => api.post(\"/login/code/verify\", { email, code })}\n *     google={() => auth.signIn.social({ provider: \"google\" })}\n *     onDone={() => location.replace(next)}\n *     text={{ emailTitle: \"보더에 로그인하기\" }}\n *   />\n */\n\n// ── Types\n\n/** Which ways in the app offers. Off by default; the screen only shows what's on. */\nexport interface AuthMethods {\n  /** 6-digit code by email (passwordless). */\n  code?: boolean;\n  password?: boolean;\n  passkey?: boolean;\n  google?: boolean;\n  /** New accounts make a name (and a password, when `password` is on) and confirm a code. */\n  signup?: boolean;\n  /** Authenticator-app step after a sign-in that answers `twoFactor: true`. */\n  twoFactor?: boolean;\n}\n\n/** What the account has, from `lookup`. `code: false` keeps an account off email codes (e.g. Google-only). */\nexport type LookupAnswer =\n  | { ok?: true; account: \"none\" }\n  | { ok?: true; account: \"exists\"; methods: { password?: boolean; passkey?: boolean; google?: boolean; code?: boolean } };\n\nexport type AuthErrorCode =\n  | \"generic\"\n  | \"email_empty\"\n  | \"email_invalid\"\n  | \"email_hangul\"\n  | \"no_account\"\n  | \"invite_required\"\n  | \"rate_limited\"\n  | \"password_empty\"\n  | \"password_invalid\"\n  | \"password_too_short\"\n  | \"password_too_long\"\n  | \"name_required\"\n  | \"name_too_long\"\n  | \"name_invalid_chars\"\n  | \"account_exists\"\n  | \"invitation_mismatch\"\n  | \"code_incomplete\"\n  | \"code_invalid\"\n  | \"code_expired\"\n  | \"too_many_attempts\"\n  | \"recently_sent\"\n  | \"retry_after\"\n  | \"too_many_codes\"\n  | \"send_failed\"\n  | \"no_pending_signup\"\n  | \"google_failed\"\n  | \"google_two_factor\"\n  | \"passkey_failed\"\n  | \"passkey_failed_password\"\n  | \"two_factor_invalid\"\n  | \"recovery_empty\"\n  | \"recovery_invalid\"\n  | \"session_expired\"\n  | \"sign_in_failed\";\n\n/** A refused call. `error` picks the line from `text.errors` (unknown codes show the generic line); `message` replaces it. */\nexport interface AuthFailure {\n  ok: false;\n  error?: AuthErrorCode | (string & {});\n  message?: string;\n  /** For `recently_sent`: \"Try again in N seconds.\" */\n  retryAfterSeconds?: number;\n}\n/** A sign-in call's answer. `twoFactor: true` = the first factor passed and the authenticator step comes next. */\nexport type AuthResult = { ok: true; twoFactor?: boolean } | AuthFailure;\n\nexport type CodePurpose = \"sign-in\" | \"sign-up\";\nexport type AuthStep = \"email\" | \"code\" | \"password\" | \"passkey\" | \"google\" | \"signup\" | \"twofactor\" | \"forgot\" | \"sent\" | \"routing\";\n\nexport interface AuthFlowProps {\n  methods: AuthMethods;\n  /** Does the account exist, and how does it sign in. Without it: code if on, else password. */\n  lookup?: (email: string) => Promise<LookupAnswer | AuthFailure>;\n  /** Mail a 6-digit code (sign-in, or a new account's confirmation and its resend). */\n  sendCode?: (email: string, purpose: CodePurpose) => Promise<AuthResult>;\n  /** Check the code. For `sign-up` the new account's password comes along (Neotax signs in with it). */\n  verifyCode?: (input: { email: string; code: string; purpose: CodePurpose; password?: string }) => Promise<AuthResult>;\n  password?: (input: { email: string; password: string }) => Promise<AuthResult>;\n  /** The browser's passkey prompt. `autoFill: true` is the email field's passkey autofill, started on load. */\n  passkey?: (input: { email: string | null; autoFill: boolean }) => Promise<AuthResult>;\n  /** Start Google sign-in. Usually it leaves the page (resolve nothing); a refusal shows the Google error. */\n  google?: () => Promise<AuthResult | void>;\n  /** Create the account. `next: \"verify\"` (default) goes to the code step; `\"signed_in\"` is done. */\n  signup?: (input: { email: string; name: string; password?: string }) => Promise<{ ok: true; next?: \"verify\" | \"signed_in\" } | AuthFailure>;\n  twoFactor?: (input: { code: string; recovery: boolean }) => Promise<AuthResult>;\n  /** Mail a password reset link. */\n  resetPassword?: (email: string) => Promise<AuthResult>;\n  /** Signed in: go where the app goes next. The screen shows a spinner until it resolves; a throw shows `sign_in_failed`. */\n  onDone: () => void | Promise<void>;\n\n  /** Prefill (an invitation's email, say). */\n  initialEmail?: string;\n  /** Show an error from the start, e.g. `google_failed` when Google sent the person back with an error. */\n  initialError?: AuthErrorCode;\n  /** Show only the spinner (back from Google, the app is deciding where to go). */\n  finishing?: boolean;\n  passwordMin?: number;\n  passwordMax?: number;\n  /** Strings: Korean by default. Pass `AUTH_TEXT_EN`, or only the lines to change. */\n  text?: Partial<Omit<AuthText, \"errors\">> & { errors?: Partial<AuthText[\"errors\"]> };\n\n  /** `AuthLayout`'s brand (top left), `app` (\"Signing in to …\") and footer. */\n  brand?: ReactNode;\n  app?: string;\n  footer?: ReactNode;\n  /** Only the column, without `AuthLayout` (to put it in your own page). */\n  bare?: boolean;\n  /** Email-code step without Continue: six fixed boxes, checked the moment the sixth digit lands (typed or pasted);\n   * \"Send a new code\" is a text link. Off (default): boxes as wide as the button, Continue and an outline resend. */\n  codeAuto?: boolean;\n  className?: string;\n}\n\n// ── Strings\n\nexport interface AuthText {\n  emailTitle: string;\n  emailSub: string;\n  emailLabel: string;\n  emailPlaceholder: string;\n  emailSuggestion: string;\n  continue: string;\n  or: string;\n  google: string;\n  back: string;\n  busy: string;\n  signingIn: string;\n  passwordTitle: string;\n  passwordLabel: string;\n  forgotLink: string;\n  signIn: string;\n  passkeyTitle: string;\n  passkeySub: string;\n  passkeyRetry: string;\n  usePassword: string;\n  googleTitle: string;\n  googleSub: string;\n  codeTitle: string;\n  codeSub: string;\n  verifyTitle: string;\n  codeLabel: string;\n  codeHint: string;\n  codeSent: string;\n  resendCode: string;\n  otherEmail: string;\n  signupTitle: string;\n  nameLabel: string;\n  newPasswordLabel: string;\n  createAccount: string;\n  twoFactorTitle: string;\n  twoFactorSub: string;\n  recoverySub: string;\n  twoFactorLabel: string;\n  recoveryLabel: string;\n  twoFactorHint: string;\n  useRecovery: string;\n  useApp: string;\n  forgotTitle: string;\n  forgotSub: string;\n  sendReset: string;\n  sentTitle: string;\n  sentSub: string;\n  resendReset: string;\n  errors: Record<AuthErrorCode, string>;\n}\n\n/** Neotax's lines ({email}, {min}, {max}, {seconds} are filled in). */\nexport const AUTH_TEXT_KO: AuthText = {\n  emailTitle: \"로그인하기\",\n  emailSub: \"\",\n  emailLabel: \"이메일\",\n  emailPlaceholder: \"이메일 주소\",\n  emailSuggestion: \"혹시 {email} 인가요?\",\n  continue: \"계속하기\",\n  or: \"또는\",\n  google: \"구글로 계속하기\",\n  back: \"돌아가기\",\n  busy: \"처리 중\",\n  signingIn: \"로그인하는 중\",\n  passwordTitle: \"비밀번호 입력하기\",\n  passwordLabel: \"비밀번호\",\n  forgotLink: \"비밀번호를 잊으셨나요?\",\n  signIn: \"로그인하기\",\n  passkeyTitle: \"패스키로 확인해 주세요\",\n  passkeySub: \"브라우저 창에서 {email} 의 패스키로 확인하세요.\",\n  passkeyRetry: \"패스키로 다시 하기\",\n  usePassword: \"비밀번호로 로그인하기\",\n  googleTitle: \"구글로 로그인하기\",\n  googleSub: \"{email} 은 구글 계정으로 만든 계정이에요.\",\n  codeTitle: \"메일함을 확인해 주세요\",\n  codeSub: \"{email} 로 보낸 6자리 코드를 입력하세요.\",\n  verifyTitle: \"이메일 확인\",\n  codeLabel: \"메일로 받은 6자리 코드\",\n  codeHint: \"메일이 안 왔으면 스팸함을 확인해 주세요.\",\n  codeSent: \"새 코드를 보냈어요. 메일이 안 왔으면 스팸함을 확인해 주세요.\",\n  resendCode: \"코드 다시 받기\",\n  otherEmail: \"다른 이메일로\",\n  signupTitle: \"계정 만들기\",\n  nameLabel: \"이름\",\n  newPasswordLabel: \"비밀번호 ({min}자 이상)\",\n  createAccount: \"계정 만들기\",\n  twoFactorTitle: \"2단계 로그인\",\n  twoFactorSub: \"인증 앱에 보이는 6자리 코드를 입력하세요.\",\n  recoverySub: \"등록할 때 받은 복구 코드 하나를 입력하세요. 한 번 쓰면 못 써요.\",\n  twoFactorLabel: \"인증 앱의 6자리 코드\",\n  recoveryLabel: \"복구 코드\",\n  twoFactorHint: \"코드는 30초마다 바뀌어요.\",\n  useRecovery: \"복구 코드로 로그인하기\",\n  useApp: \"인증 앱 코드로 로그인하기\",\n  forgotTitle: \"비밀번호 찾기\",\n  forgotSub: \"가입한 이메일로 재설정 링크를 보내요.\",\n  sendReset: \"재설정 메일 보내기\",\n  sentTitle: \"메일을 보냈어요\",\n  sentSub: \"{email} 의 링크를 열어 새 비밀번호를 정하세요. 링크는 1시간 동안 쓸 수 있어요.\",\n  resendReset: \"메일 다시 보내기\",\n  errors: {\n    generic: \"일시적인 오류가 발생했어요\",\n    email_empty: \"이메일 주소를 입력해 주세요.\",\n    email_invalid: \"이메일 형식이 맞지 않아요.\",\n    email_hangul: \"한글이 들어 있어요. 한/영 키를 영문으로 바꿔 입력해 주세요.\",\n    no_account: \"이 이메일로 만든 계정이 없어요.\",\n    invite_required: \"초대받은 이메일로만 들어올 수 있어요.\",\n    rate_limited: \"요청이 너무 많아요. 잠시 뒤 다시 시도해 주세요.\",\n    password_empty: \"비밀번호를 입력해 주세요.\",\n    password_invalid: \"비밀번호가 맞지 않아요.\",\n    password_too_short: \"비밀번호는 {min}자 이상이어야 해요.\",\n    password_too_long: \"비밀번호는 {max}자 이하로 정해 주세요.\",\n    name_required: \"이름을 입력해 주세요.\",\n    name_too_long: \"이름은 50자 이하로 적어 주세요.\",\n    name_invalid_chars: \"이름에 쓸 수 없는 글자가 있어요.\",\n    account_exists: \"이미 계정이 있는 이메일이에요. 돌아가서 로그인해 주세요.\",\n    invitation_mismatch: \"초대받은 이메일로만 가입할 수 있어요.\",\n    code_incomplete: \"6자리 코드를 입력해 주세요.\",\n    code_invalid: \"코드가 맞지 않아요.\",\n    code_expired: \"코드가 만료됐어요. 코드를 다시 받아 주세요.\",\n    too_many_attempts: \"여러 번 틀렸어요. 코드를 다시 받아 주세요.\",\n    recently_sent: \"방금 코드를 보냈어요. 1분 뒤 다시 시도해 주세요.\",\n    retry_after: \"{seconds}초 뒤에 다시 보낼 수 있어요.\",\n    too_many_codes: \"오늘 보낼 수 있는 코드를 다 보냈어요. 내일 다시 시도해 주세요.\",\n    send_failed: \"메일을 보내지 못했어요. 잠시 뒤 다시 시도해 주세요.\",\n    no_pending_signup: \"가입을 마치지 못했어요. 처음부터 다시 해 주세요.\",\n    google_failed: \"구글 로그인을 마치지 못했어요. 다시 시도해 주세요.\",\n    google_two_factor: \"2단계 로그인 계정은 이메일로 로그인해 주세요.\",\n    passkey_failed: \"패스키 확인을 마치지 못했어요. 다시 시도해 주세요.\",\n    passkey_failed_password: \"패스키 확인을 마치지 못했어요. 비밀번호로 로그인해 주세요.\",\n    two_factor_invalid: \"코드가 맞지 않아요. 인증 앱에서 새 코드를 확인해 주세요.\",\n    recovery_empty: \"복구 코드를 입력해 주세요.\",\n    recovery_invalid: \"복구 코드가 맞지 않아요.\",\n    session_expired: \"시간이 지났어요. 처음부터 다시 로그인해 주세요.\",\n    sign_in_failed: \"로그인을 마치지 못했어요. 다시 시도해 주세요.\",\n  },\n};\n\nexport const AUTH_TEXT_EN: AuthText = {\n  emailTitle: \"Log in\",\n  emailSub: \"\",\n  emailLabel: \"Email\",\n  emailPlaceholder: \"Email address\",\n  emailSuggestion: \"Did you mean {email}?\",\n  continue: \"Continue\",\n  or: \"or\",\n  google: \"Continue with Google\",\n  back: \"Back\",\n  busy: \"Working\",\n  signingIn: \"Signing in\",\n  passwordTitle: \"Enter your password\",\n  passwordLabel: \"Password\",\n  forgotLink: \"Forgot password?\",\n  signIn: \"Log in\",\n  passkeyTitle: \"Confirm with your passkey\",\n  passkeySub: \"Use the passkey for {email} in the browser window.\",\n  passkeyRetry: \"Try the passkey again\",\n  usePassword: \"Log in with password\",\n  googleTitle: \"Log in with Google\",\n  googleSub: \"{email} was made with a Google account.\",\n  codeTitle: \"Check your email\",\n  codeSub: \"Enter the 6-digit code we sent to {email}.\",\n  verifyTitle: \"Confirm your email\",\n  codeLabel: \"6-digit code from the email\",\n  codeHint: \"No mail? Check your spam folder.\",\n  codeSent: \"We sent a new code. No mail? Check your spam folder.\",\n  resendCode: \"Send a new code\",\n  otherEmail: \"Use another email\",\n  signupTitle: \"Create your account\",\n  nameLabel: \"Name\",\n  newPasswordLabel: \"Password ({min}+ characters)\",\n  createAccount: \"Create account\",\n  twoFactorTitle: \"Two-step login\",\n  twoFactorSub: \"Enter the 6-digit code in your authenticator app.\",\n  recoverySub: \"Enter one of your recovery codes. Each works once.\",\n  twoFactorLabel: \"6-digit code from the app\",\n  recoveryLabel: \"Recovery code\",\n  twoFactorHint: \"The code changes every 30 seconds.\",\n  useRecovery: \"Use a recovery code\",\n  useApp: \"Use the authenticator app\",\n  forgotTitle: \"Reset your password\",\n  forgotSub: \"We'll mail a reset link to your email.\",\n  sendReset: \"Send reset link\",\n  sentTitle: \"Check your email\",\n  sentSub: \"Open the link sent to {email} to set a new password. It works for 1 hour.\",\n  resendReset: \"Send again\",\n  errors: {\n    generic: \"Something went wrong. Try again.\",\n    email_empty: \"Enter your email address.\",\n    email_invalid: \"That doesn't look like an email address.\",\n    email_hangul: \"Korean input is on. Switch to English and type again.\",\n    no_account: \"No account uses this email.\",\n    invite_required: \"Only invited emails can sign in.\",\n    rate_limited: \"Too many tries. Wait a moment and try again.\",\n    password_empty: \"Enter your password.\",\n    password_invalid: \"Wrong password.\",\n    password_too_short: \"Use at least {min} characters.\",\n    password_too_long: \"Use {max} characters or fewer.\",\n    name_required: \"Enter your name.\",\n    name_too_long: \"Use 50 characters or fewer.\",\n    name_invalid_chars: \"The name has characters we can't use.\",\n    account_exists: \"This email already has an account. Go back and log in.\",\n    invitation_mismatch: \"Sign up with the email that was invited.\",\n    code_incomplete: \"Enter the 6-digit code.\",\n    code_invalid: \"Wrong code.\",\n    code_expired: \"The code expired. Get a new one.\",\n    too_many_attempts: \"Too many wrong tries. Get a new code.\",\n    recently_sent: \"We just sent a code. Try again in a minute.\",\n    retry_after: \"You can send again in {seconds} seconds.\",\n    too_many_codes: \"No more codes today. Try again tomorrow.\",\n    send_failed: \"We couldn't send the mail. Try again soon.\",\n    no_pending_signup: \"Sign-up didn't finish. Start again.\",\n    google_failed: \"Google sign-in didn't finish. Try again.\",\n    google_two_factor: \"Two-step accounts log in with email.\",\n    passkey_failed: \"The passkey check didn't finish. Try again.\",\n    passkey_failed_password: \"The passkey check didn't finish. Use your password.\",\n    two_factor_invalid: \"Wrong code. Check the app for a new one.\",\n    recovery_empty: \"Enter a recovery code.\",\n    recovery_invalid: \"Wrong recovery code.\",\n    session_expired: \"Time ran out. Log in again from the start.\",\n    sign_in_failed: \"Sign-in didn't finish. Try again.\",\n  },\n};\n\n// ── Rules (pure, exported for apps and tests)\n\n/**\n * The step after the email. Neotax's order (no account → sign-up; passkey → password → Google-only),\n * with the email code where the password goes for apps that use codes. Only methods the app has on count.\n * \"none\" = no account and no way to make one here.\n */\nexport function stepAfterLookup(answer: LookupAnswer, on: AuthMethods): \"signup\" | \"code\" | \"passkey\" | \"password\" | \"google\" | \"none\" {\n  if (answer.account === \"none\") return on.signup ? \"signup\" : on.code ? \"code\" : \"none\";\n  const has = answer.methods;\n  if (on.passkey && has.passkey) return \"passkey\";\n  if (on.password && has.password) return \"password\";\n  if (on.code && has.code !== false) return \"code\";\n  if (on.google && has.google) return \"google\";\n  return on.password ? \"password\" : on.code ? \"code\" : on.google ? \"google\" : \"none\";\n}\n\n/** After a cancelled or failed passkey: the password if the account has one, else back to the email. */\nexport function stepAfterPasskeyFailure(has: { password?: boolean } | null, on: AuthMethods): \"password\" | \"email\" {\n  return on.password && has?.password ? \"password\" : \"email\";\n}\n\nconst EMAIL_LOCAL = /^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*$/;\nconst EMAIL_DOMAIN = /^(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\\.)+[A-Za-z]{2,63}$/;\nconst HANGUL = /[ᄀ-ᇿ㄰-㆏ꥠ-꥿가-힣ힰ-퟿]/;\n\nfunction isEmailAddress(value: string): boolean {\n  if (value.length === 0 || value.length > 254) return false;\n  const at = value.lastIndexOf(\"@\");\n  if (at <= 0 || at > 64 || value.indexOf(\"@\") !== at) return false;\n  return EMAIL_LOCAL.test(value.slice(0, at)) && EMAIL_DOMAIN.test(value.slice(at + 1));\n}\n\n// Dubeolsik keyboard: jamo → the Latin key in the same place (double jamo = both keys).\nconst JAMO_KEYS: Record<string, string> = {\n  ㄱ: \"r\", ㄲ: \"R\", ㄳ: \"rt\", ㄴ: \"s\", ㄵ: \"sw\", ㄶ: \"sg\", ㄷ: \"e\", ㄸ: \"E\", ㄹ: \"f\", ㄺ: \"fr\", ㄻ: \"fa\", ㄼ: \"fq\", ㄽ: \"ft\", ㄾ: \"fx\",\n  ㄿ: \"fv\", ㅀ: \"fg\", ㅁ: \"a\", ㅂ: \"q\", ㅃ: \"Q\", ㅄ: \"qt\", ㅅ: \"t\", ㅆ: \"T\", ㅇ: \"d\", ㅈ: \"w\", ㅉ: \"W\", ㅊ: \"c\", ㅋ: \"z\", ㅌ: \"x\", ㅍ: \"v\",\n  ㅎ: \"g\", ㅏ: \"k\", ㅐ: \"o\", ㅑ: \"i\", ㅒ: \"O\", ㅓ: \"j\", ㅔ: \"p\", ㅕ: \"u\", ㅖ: \"P\", ㅗ: \"h\", ㅘ: \"hk\", ㅙ: \"ho\", ㅚ: \"hl\", ㅛ: \"y\", ㅜ: \"n\",\n  ㅝ: \"nj\", ㅞ: \"np\", ㅟ: \"nl\", ㅠ: \"b\", ㅡ: \"m\", ㅢ: \"ml\", ㅣ: \"l\",\n};\nconst CHO = \"ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ\";\nconst JUNG = \"ㅏㅐㅑㅒㅓㅔㅕㅖㅗㅘㅙㅚㅛㅜㅝㅞㅟㅠㅡㅢㅣ\";\nconst JONG = [\"\", ...\"ㄱㄲㄳㄴㄵㄶㄷㄹㄺㄻㄼㄽㄾㄿㅀㅁㅂㅄㅅㅆㅇㅈㅊㅋㅌㅍㅎ\"];\n\n/** Text typed with the Korean layout on, back to the Latin keys pressed (「ㅠㅐㅠㅠㅛ」 → \"bobby\"). */\nexport function hangulKeysToLatin(value: string): string {\n  let out = \"\";\n  for (const ch of value.normalize(\"NFC\")) {\n    const code = ch.charCodeAt(0);\n    if (code >= 0xac00 && code <= 0xd7a3) {\n      const i = code - 0xac00;\n      out += JAMO_KEYS[CHO[Math.floor(i / 588)]!]! + JAMO_KEYS[JUNG[Math.floor((i % 588) / 28)]!]!;\n      const jong = JONG[i % 28]!;\n      if (jong) out += JAMO_KEYS[jong]!;\n    } else {\n      out += JAMO_KEYS[ch] ?? ch;\n    }\n  }\n  return out;\n}\n\n/** The email field's check (Neotax's): trimmed and lower-cased when fine; Hangul input gets a Latin suggestion. */\nexport function checkEmail(value: string): { ok: true; email: string } | { ok: false; error: \"email_empty\" | \"email_hangul\" | \"email_invalid\"; suggestion: string | null } {\n  const email = value.trim();\n  if (!email) return { ok: false, error: \"email_empty\", suggestion: null };\n  if (HANGUL.test(email)) {\n    const latin = hangulKeysToLatin(email).toLowerCase();\n    return { ok: false, error: \"email_hangul\", suggestion: isEmailAddress(latin) ? latin : null };\n  }\n  if (!isEmailAddress(email)) return { ok: false, error: \"email_invalid\", suggestion: null };\n  return { ok: true, email: email.toLowerCase() };\n}\n\n// ── Parts\n\nconst fill = (line: string, vars: Record<string, string | number | undefined>) => line.replace(/\\{(\\w+)\\}/g, (m, k: string) => (vars[k] === undefined ? m : String(vars[k])));\n\n/** Neotax's sizes on the auth-page pills: 40px buttons, 14px/500 text, 20px icons. */\nconst btn = \"gap-2 px-6 text-sm leading-5 [&_svg]:size-5\";\n/** Neotax's field: 44px, 14px text (16px on touch, so iOS doesn't zoom), a 2px ring on focus, red when wrong. */\nconst field = (bad: boolean) =>\n  cn(\n    \"h-11 px-4 text-base transition-[border-color,box-shadow] read-only:text-muted-foreground sm:text-sm pointer-coarse:text-base\",\n    bad ? \"border-destructive focus:border-destructive focus:ring-1 focus:ring-destructive\" : \"hover:border-gray-500 focus:border-ring focus:ring-1 focus:ring-ring\",\n  );\n\nfunction Spinner({ label }: { label: string }) {\n  return <LoaderCircle className=\"animate-spin\" role=\"status\" aria-label={label} />;\n}\n\n/** A button's label, or the spinner while its call runs (never \"…중\" text). */\nfunction Busy({ busy, label, children }: { busy: boolean; label: string; children: ReactNode }) {\n  return busy ? <Spinner label={label} /> : <>{children}</>;\n}\n\n/** The colored Google \"G\". */\nexport function GoogleIcon() {\n  return (\n    <svg viewBox=\"0 0 18 18\" aria-hidden=\"true\">\n      <path fill=\"#4285F4\" d=\"M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.48h4.84a4.14 4.14 0 0 1-1.8 2.72v2.26h2.91c1.7-1.57 2.68-3.88 2.68-6.62z\" />\n      <path fill=\"#34A853\" d=\"M9 18c2.43 0 4.47-.81 5.96-2.18l-2.91-2.26c-.81.54-1.84.86-3.05.86-2.34 0-4.33-1.58-5.04-3.71H.96v2.33A9 9 0 0 0 9 18z\" />\n      <path fill=\"#FBBC05\" d=\"M3.96 10.71A5.41 5.41 0 0 1 3.68 9c0-.59.1-1.17.28-1.71V4.96H.96A9 9 0 0 0 0 9c0 1.45.35 2.83.96 4.04l3-2.33z\" />\n      <path fill=\"#EA4335\" d=\"M9 3.58c1.32 0 2.51.45 3.44 1.35l2.58-2.58C13.46.89 11.43 0 9 0A9 9 0 0 0 .96 4.96L3.96 7.29C4.67 5.16 6.66 3.58 9 3.58z\" />\n    </svg>\n  );\n}\n\n/** An error line: under its field, or centered under the title when no field owns it. */\nexport function AuthError({ children, center }: { children: ReactNode; center?: boolean }) {\n  if (!children) return null;\n  return (\n    <p role=\"alert\" className={cn(\"mt-1 flex items-start gap-1.5 text-xs leading-4 text-destructive [&_svg]:mt-px [&_svg]:size-3.5 [&_svg]:shrink-0\", center && \"mt-0 mb-4 justify-center text-center\")}>\n      <CircleAlert aria-hidden=\"true\" />\n      <span>{children}</span>\n    </p>\n  );\n}\n\nfunction Heading({ title, sub, mark }: { title: ReactNode; sub?: ReactNode; mark?: ReactNode }) {\n  return (\n    <div className=\"mb-6 text-center\">\n      {mark ? <div className=\"mx-auto mb-4 flex size-12 items-center justify-center rounded-full bg-gray-100 text-foreground [&_svg]:size-6\">{mark}</div> : null}\n      {title ? <h1 className=\"m-0 text-heading-30 text-balance max-sm:text-2xl max-sm:leading-8 max-sm:tracking-[-0.6px]\">{title}</h1> : null}\n      {sub ? <p className=\"mt-2 mb-0 text-sm leading-5 text-muted-foreground text-balance\">{sub}</p> : null}\n    </div>\n  );\n}\n\nfunction Label({ htmlFor, children, bad, sr }: { htmlFor: string; children: ReactNode; bad?: boolean; sr?: boolean }) {\n  return (\n    <label htmlFor={htmlFor} className={cn(\"mb-1.5 text-sm leading-[14px]\", bad && \"text-destructive\", sr && \"sr-only\")}>\n      {children}\n    </label>\n  );\n}\n\n// ── The flow\n\ntype Field = \"email\" | \"password\" | \"name\" | \"code\";\ntype Problem = { field: Field | null; message: string };\ntype BusyKind = null | \"submit\" | \"google\" | \"resend\";\n\n/** Which field a code belongs under (others are centered under the title). */\nconst FIELD_OF: Partial<Record<string, Field>> = {\n  email_empty: \"email\",\n  email_invalid: \"email\",\n  email_hangul: \"email\",\n  password_empty: \"password\",\n  password_invalid: \"password\",\n  password_too_short: \"password\",\n  password_too_long: \"password\",\n  name_required: \"name\",\n  name_too_long: \"name\",\n  name_invalid_chars: \"name\",\n  code_incomplete: \"code\",\n  code_invalid: \"code\",\n  code_expired: \"code\",\n  too_many_attempts: \"code\",\n  retry_after: \"code\",\n  two_factor_invalid: \"code\",\n  recovery_empty: \"code\",\n  recovery_invalid: \"code\",\n};\n\n/** What a missing prop answers: the generic error. */\nconst NOT_SET: AuthFailure = { ok: false };\n\nconst isFailure = (r: unknown): r is AuthFailure => typeof r === \"object\" && r !== null && (r as { ok?: unknown }).ok === false;\n\nexport function AuthFlow(props: AuthFlowProps) {\n  const { methods: on, passwordMin = 8, passwordMax = 128 } = props;\n  const t: AuthText = { ...AUTH_TEXT_KO, ...props.text, errors: { ...AUTH_TEXT_KO.errors, ...props.text?.errors } };\n\n  const [step, setStep] = useState<AuthStep>(props.finishing ? \"routing\" : \"email\");\n  const [email, setEmail] = useState(props.initialEmail ?? \"\");\n  const [password, setPassword] = useState(\"\");\n  const [name, setName] = useState(\"\");\n  const [code, setCode] = useState(\"\");\n  const [purpose, setPurpose] = useState<CodePurpose>(\"sign-in\");\n  const [recovery, setRecovery] = useState(false);\n  const [known, setKnown] = useState<{ password?: boolean; passkey?: boolean } | null>(null);\n  const [passkeyFailed, setPasskeyFailed] = useState(false);\n  const [problem, setProblem] = useState<Problem | null>(() => (props.initialError ? { field: null, message: t.errors[props.initialError] ?? t.errors.generic } : null));\n  const [suggestion, setSuggestion] = useState<string | null>(null);\n  const [notice, setNotice] = useState(\"\");\n  const [busy, setBusy] = useState<BusyKind>(null);\n  const [forgotFrom, setForgotFrom] = useState<AuthStep>(\"password\");\n  /** Bumped on every step change: a reply that comes back after the person moved on is dropped. */\n  const gen = useRef(0);\n  const busyRef = useRef(false);\n\n  const refs = {\n    email: useRef<HTMLInputElement>(null),\n    password: useRef<HTMLInputElement>(null),\n    name: useRef<HTMLInputElement>(null),\n    code: useRef<HTMLInputElement>(null),\n  };\n\n  // Each step focuses its first field.\n  useLayoutEffect(() => {\n    const first: Partial<Record<AuthStep, { current: HTMLInputElement | null }>> = { email: refs.email, forgot: refs.email, password: refs.password, signup: refs.name, code: refs.code, twofactor: refs.code };\n    const target = first[step];\n    target?.current?.focus();\n    // Only when the step changes.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [step]);\n\n  // `finishing` and `initialError` can change after mount (back from Google, the app decides): spinner while\n  // finishing, then the email step with the error, if any.\n  const mounted = useRef(false);\n  useEffect(() => {\n    if (!mounted.current) {\n      mounted.current = true;\n      return;\n    }\n    if (props.finishing) return go(\"routing\");\n    if (step === \"routing\") go(\"email\");\n    if (props.initialError) fail({ error: props.initialError });\n    // Only when these props change.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [props.finishing, props.initialError]);\n\n  // Back from Google with the browser's back button (page restored from the back-forward cache): no spinner.\n  useEffect(() => {\n    const onShow = (e: PageTransitionEvent) => {\n      if (!e.persisted) return;\n      busyRef.current = false;\n      setBusy(null);\n    };\n    window.addEventListener(\"pageshow\", onShow);\n    return () => window.removeEventListener(\"pageshow\", onShow);\n  }, []);\n\n  // The email field's passkey autofill: browsers with a passkey offer it when the field is tapped.\n  useEffect(() => {\n    if (!on.passkey || !props.passkey || props.finishing || typeof PublicKeyCredential === \"undefined\") return;\n    let alive = true;\n    (async () => {\n      try {\n        if (!(await PublicKeyCredential.isConditionalMediationAvailable?.())) return;\n        const r = await props.passkey!({ email: null, autoFill: true });\n        if (alive && r.ok) await finish(r);\n      } catch {\n        // Cancelled (another check started) or unsupported: stay quiet.\n      }\n    })();\n    return () => {\n      alive = false;\n    };\n    // Once.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  const message = (f: AuthFailure | { error: string; retryAfterSeconds?: number; message?: string }) => {\n    const key = f.error === \"recently_sent\" && f.retryAfterSeconds ? \"retry_after\" : f.error;\n    const line = f.message ?? (key && key in t.errors ? t.errors[key as AuthErrorCode] : t.errors.generic);\n    return { key: key ?? \"generic\", text: fill(line, { min: passwordMin, max: passwordMax, seconds: f.retryAfterSeconds, email }) };\n  };\n\n  function clear() {\n    setProblem(null);\n    setSuggestion(null);\n    setNotice(\"\");\n  }\n\n  /** Change step. Calls still running for the old step are dropped, and their spinner goes. */\n  function go(to: AuthStep) {\n    gen.current++;\n    busyRef.current = false;\n    setBusy(null);\n    clear();\n    setStep(to);\n  }\n\n  /** Show a failure: under its field when this step has that field, else centered. */\n  function fail(f: AuthFailure | { error: AuthErrorCode; retryAfterSeconds?: number }, owner?: Field) {\n    const m = message(f);\n    setProblem({ field: owner ?? FIELD_OF[m.key] ?? null, message: m.text });\n  }\n\n  /**\n   * One server call at a time, with a spinner on the button that started it. `live()` turns false once the\n   * step changes (Back, another email): check it after every await. A throw is the generic error.\n   */\n  async function run(kind: Exclude<BusyKind, null>, work: (live: () => boolean) => Promise<void>) {\n    if (busyRef.current) return;\n    const g = gen.current;\n    const live = () => g === gen.current;\n    busyRef.current = true;\n    setBusy(kind);\n    try {\n      await work(live);\n    } catch {\n      if (live()) setProblem({ field: null, message: t.errors.generic });\n    } finally {\n      if (live()) {\n        busyRef.current = false;\n        setBusy(null);\n      }\n    }\n  }\n\n  /** Signed in (or the first factor passed). */\n  async function finish(r: AuthResult) {\n    if (r.ok && r.twoFactor) {\n      setCode(\"\");\n      setRecovery(false);\n      go(\"twofactor\");\n      return;\n    }\n    go(\"routing\");\n    const g = gen.current;\n    try {\n      await props.onDone();\n    } catch {\n      if (g !== gen.current) return;\n      go(\"email\");\n      setProblem({ field: null, message: t.errors.sign_in_failed });\n    }\n  }\n\n  function badEmail(): string | null {\n    const c = checkEmail(email);\n    if (c.ok) return c.email;\n    fail({ error: c.error }, \"email\");\n    if (c.suggestion) setSuggestion(c.suggestion);\n    return null;\n  }\n\n  async function toCode(value: string, p: CodePurpose, live: () => boolean) {\n    if (!props.sendCode) throw new Error(\"sendCode missing\");\n    const r = await props.sendCode(value, p);\n    if (!live()) return;\n    if (isFailure(r)) return fail(r);\n    setPurpose(p);\n    setCode(\"\");\n    go(\"code\");\n  }\n\n  async function startPasskey(has: { password?: boolean } | null, address: string) {\n    go(\"passkey\");\n    const g = gen.current;\n    let r: AuthResult;\n    try {\n      r = props.passkey ? await props.passkey({ email: address, autoFill: false }) : NOT_SET;\n    } catch {\n      r = NOT_SET;\n    }\n    if (g !== gen.current) return;\n    if (r.ok) return finish(r);\n    if (stepAfterPasskeyFailure(has, on) === \"password\") {\n      setPasskeyFailed(true);\n      setPassword(\"\");\n      go(\"password\");\n      fail({ error: \"passkey_failed_password\" });\n    } else {\n      go(\"email\");\n      fail({ error: \"passkey_failed\" });\n    }\n  }\n\n  function toEmail() {\n    setPassword(\"\");\n    setPasskeyFailed(false);\n    go(\"email\");\n  }\n\n  function toPassword() {\n    setPasskeyFailed(false);\n    setPassword(\"\");\n    go(\"password\");\n  }\n\n  function onEmail(e: FormEvent) {\n    e.preventDefault();\n    clear();\n    const value = badEmail();\n    if (!value) return;\n    setEmail(value);\n    void run(\"submit\", async (live) => {\n      let answer: LookupAnswer;\n      if (props.lookup) {\n        const r = await props.lookup(value);\n        if (!live()) return;\n        if (isFailure(r)) return fail(r);\n        answer = r;\n      } else {\n        answer = { account: \"exists\", methods: { password: true, code: true } };\n      }\n      const has = answer.account === \"exists\" ? answer.methods : null;\n      setKnown(has);\n      const to = stepAfterLookup(answer, on);\n      if (to === \"none\") return fail({ error: \"no_account\" });\n      if (to === \"code\") return toCode(value, answer.account === \"none\" ? \"sign-up\" : \"sign-in\", live);\n      if (to === \"passkey\") {\n        void startPasskey(has, value);\n        return;\n      }\n      setPassword(\"\");\n      setPasskeyFailed(false);\n      go(to);\n    });\n  }\n\n  function onPassword(e: FormEvent) {\n    e.preventDefault();\n    clear();\n    if (!password) return fail({ error: \"password_empty\" });\n    void run(\"submit\", async (live) => {\n      const r = props.password ? await props.password({ email, password }) : NOT_SET;\n      if (!live()) return;\n      if (isFailure(r)) return fail(r);\n      await finish(r);\n    });\n  }\n\n  function onSignup(e: FormEvent) {\n    e.preventDefault();\n    clear();\n    if (!name.trim()) return fail({ error: \"name_required\" });\n    if (on.password && password.length < passwordMin) return fail({ error: \"password_too_short\" });\n    if (on.password && password.length > passwordMax) return fail({ error: \"password_too_long\" });\n    void run(\"submit\", async (live) => {\n      const r = props.signup\n        ? await props.signup({ email, name: name.trim(), ...(on.password ? { password } : {}) })\n        : NOT_SET;\n      if (!live()) return;\n      if (isFailure(r)) return fail(r);\n      if (r.next === \"signed_in\") return finish({ ok: true });\n      setPurpose(\"sign-up\");\n      setCode(\"\");\n      go(\"code\");\n    });\n  }\n\n  function onCode(e: FormEvent) {\n    e.preventDefault();\n    verify(code);\n  }\n\n  function verify(code: string) {\n    clear();\n    if (code.length !== 6) {\n      fail({ error: \"code_incomplete\" });\n      refs.code.current?.focus();\n      return;\n    }\n    void run(\"submit\", async (live) => {\n      const r = props.verifyCode\n        ? await props.verifyCode({ email, code, purpose, ...(purpose === \"sign-up\" && password ? { password } : {}) })\n        : NOT_SET;\n      if (!live()) return;\n      if (isFailure(r)) {\n        // A wrong or expired code is useless: empty the boxes for the next one.\n        if (r.error === \"code_invalid\" || r.error === \"code_expired\") setCode(\"\");\n        fail(r, \"code\");\n        refs.code.current?.focus();\n        return;\n      }\n      await finish(r);\n    });\n  }\n\n  function resend() {\n    clear();\n    void run(\"resend\", async (live) => {\n      if (!props.sendCode) throw new Error(\"sendCode missing\");\n      const r = await props.sendCode(email, purpose);\n      if (!live()) return;\n      if (isFailure(r)) return fail(r, \"code\");\n      setCode(\"\");\n      setNotice(t.codeSent);\n      refs.code.current?.focus();\n    });\n  }\n\n  function onTwoFactor(e: FormEvent) {\n    e.preventDefault();\n    clear();\n    const value = recovery ? code.trim() : code;\n    if (recovery ? !value : value.length !== 6) {\n      fail({ error: recovery ? \"recovery_empty\" : \"code_incomplete\" });\n      refs.code.current?.focus();\n      return;\n    }\n    void run(\"submit\", async (live) => {\n      const r = props.twoFactor ? await props.twoFactor({ code: value, recovery }) : NOT_SET;\n      if (!live()) return;\n      if (isFailure(r)) return fail(r.error || r.message ? r : { error: recovery ? \"recovery_invalid\" : \"two_factor_invalid\" }, \"code\");\n      await finish({ ok: true });\n    });\n  }\n\n  function sendReset(e?: FormEvent) {\n    e?.preventDefault();\n    clear();\n    const value = badEmail();\n    if (!value) return;\n    setEmail(value);\n    const from = step;\n    void run(from === \"sent\" ? \"resend\" : \"submit\", async (live) => {\n      const r = props.resetPassword ? await props.resetPassword(value) : NOT_SET;\n      if (!live()) return;\n      if (isFailure(r)) return fail(r);\n      if (from !== \"sent\") go(\"sent\");\n    });\n  }\n\n  function startGoogle() {\n    if (busyRef.current) return;\n    clear();\n    const g = gen.current;\n    busyRef.current = true;\n    setBusy(\"google\");\n    (async () => {\n      let r: AuthResult | void;\n      try {\n        r = props.google ? await props.google() : NOT_SET;\n      } catch {\n        r = { ok: false, error: \"google_failed\" };\n      }\n      if (g !== gen.current) return;\n      if (!r) return; // Leaving for Google: keep the spinner (pageshow clears it if they come back).\n      busyRef.current = false;\n      setBusy(null);\n      if (isFailure(r)) fail({ ...r, error: r.error ?? \"google_failed\" });\n      else await finish(r);\n    })();\n  }\n\n  const errorOf = (f: Field) => (problem && problem.field === f ? problem.message : \"\");\n  const formError = (fields: Field[]) => (problem && (problem.field === null || !fields.includes(problem.field)) ? <AuthError center>{problem.message}</AuthError> : null);\n  const submitting = busy === \"submit\";\n\n  const googleButton = (primary: boolean) => (\n    <AuthButton type=\"button\" primary={primary} className={btn} disabled={busy === \"google\"} aria-busy={busy === \"google\" || undefined} onClick={startGoogle}>\n      <Busy busy={busy === \"google\"} label={t.busy}>\n        <GoogleIcon />\n        {t.google}\n      </Busy>\n    </AuthButton>\n  );\n\n  const auto = Boolean(props.codeAuto);\n  const link = \"cursor-pointer border-0 bg-transparent p-0 text-inherit underline underline-offset-2 hover:text-foreground disabled:cursor-default disabled:opacity-60\";\n\n  const submit = (label: string) => (\n    <AuthButton type=\"submit\" primary className={btn} disabled={submitting} aria-busy={submitting || undefined}>\n      <Busy busy={submitting} label={t.busy}>\n        {label}\n      </Busy>\n    </AuthButton>\n  );\n\n  const outline = (label: ReactNode, onClick: () => void, extra?: { busy?: boolean }) => (\n    <AuthButton type=\"button\" className={btn} onClick={onClick} disabled={extra?.busy} aria-busy={extra?.busy || undefined}>\n      <Busy busy={Boolean(extra?.busy)} label={t.busy}>\n        {label}\n      </Busy>\n    </AuthButton>\n  );\n\n  const emailField = (id: string, labelled: boolean) => (\n    <div className=\"flex flex-col gap-1\">\n      <Label htmlFor={id} sr={!labelled} bad={Boolean(errorOf(\"email\"))}>\n        {t.emailLabel}\n      </Label>\n      <AuthField\n        id={id}\n        ref={refs.email}\n        type=\"email\"\n        name=\"email\"\n        placeholder={t.emailPlaceholder}\n        autoComplete={on.passkey ? \"username webauthn\" : \"username\"}\n        value={email}\n        onChange={(e) => {\n          setEmail(e.target.value);\n          setSuggestion(null);\n        }}\n        aria-invalid={Boolean(errorOf(\"email\")) || undefined}\n        className={field(Boolean(errorOf(\"email\")))}\n      />\n      <AuthError>{errorOf(\"email\")}</AuthError>\n      {suggestion ? (\n        <p className=\"mt-1 text-xs leading-4 text-muted-foreground\">\n          <button\n            type=\"button\"\n            className=\"cursor-pointer border-0 bg-transparent p-0 text-foreground underline underline-offset-2\"\n            onClick={() => {\n              setEmail(suggestion);\n              clear();\n              refs.email.current?.focus();\n            }}\n          >\n            {fill(t.emailSuggestion, { email: suggestion })}\n          </button>\n        </p>\n      ) : null}\n    </div>\n  );\n\n  const readOnlyEmail = (\n    <div className=\"flex flex-col gap-1\">\n      <Label htmlFor=\"auth-email-shown\">{t.emailLabel}</Label>\n      <AuthField id=\"auth-email-shown\" type=\"email\" name=\"email\" autoComplete=\"username\" value={email} readOnly className={field(false)} />\n    </div>\n  );\n\n  const passwordField = (id: string, label: string, autoComplete: string, aside?: ReactNode, focus?: boolean) => (\n    <div className=\"flex flex-col gap-1\">\n      <div className=\"flex items-baseline justify-between\">\n        <Label htmlFor={id} bad={Boolean(errorOf(\"password\"))}>\n          {label}\n        </Label>\n        {aside}\n      </div>\n      <AuthField\n        id={id}\n        ref={focus ? refs.password : undefined}\n        type=\"password\"\n        name=\"password\"\n        autoComplete={autoComplete}\n        value={password}\n        onChange={(e) => setPassword(e.target.value)}\n        aria-invalid={Boolean(errorOf(\"password\")) || undefined}\n        className={field(Boolean(errorOf(\"password\")))}\n      />\n      <AuthError>{errorOf(\"password\")}</AuthError>\n    </div>\n  );\n\n  const usesEmail = Boolean(on.code || on.password || on.passkey || on.signup);\n  let body: ReactNode;\n\n  switch (step) {\n    case \"email\":\n      body = (\n        <>\n          <Heading title={t.emailTitle} sub={t.emailSub} />\n          {formError(usesEmail ? [\"email\"] : [])}\n          {usesEmail ? (\n            <form className=\"m-0 flex flex-col gap-4\" noValidate onSubmit={onEmail}>\n              {emailField(\"auth-email\", false)}\n              {submit(t.continue)}\n            </form>\n          ) : null}\n          {on.google ? (\n            <>\n              {usesEmail ? <AuthDivider className=\"my-4 text-xs leading-4\">{t.or}</AuthDivider> : null}\n              {googleButton(false)}\n            </>\n          ) : null}\n        </>\n      );\n      break;\n\n    case \"password\":\n      body = (\n        <>\n          <Heading title={t.passwordTitle} />\n          {formError([\"password\"])}\n          <form className=\"m-0 flex flex-col gap-4\" noValidate onSubmit={onPassword}>\n            {readOnlyEmail}\n            {passwordField(\n              \"auth-password\",\n              t.passwordLabel,\n              \"current-password\",\n              props.resetPassword ? (\n                <button\n                  type=\"button\"\n                  className=\"cursor-pointer border-0 bg-transparent p-0 text-[13px] leading-[14px] text-muted-foreground underline underline-offset-2 hover:text-foreground\"\n                  onClick={() => {\n                    setForgotFrom(\"password\");\n                    go(\"forgot\");\n                  }}\n                >\n                  {t.forgotLink}\n                </button>\n              ) : null,\n              true,\n            )}\n            <div className=\"flex flex-col gap-3\">\n              {submit(t.signIn)}\n              {passkeyFailed ? outline(t.passkeyRetry, () => void startPasskey(known, email)) : outline(t.back, toEmail)}\n            </div>\n          </form>\n        </>\n      );\n      break;\n\n    case \"passkey\":\n      body = (\n        <>\n          <div role=\"status\">\n            <Heading mark={<LoaderCircle className=\"animate-spin\" />} title={t.passkeyTitle} sub={fill(t.passkeySub, { email })} />\n          </div>\n          <div className=\"flex flex-col gap-3\">{on.password && known?.password ? outline(t.usePassword, toPassword) : outline(t.back, toEmail)}</div>\n        </>\n      );\n      break;\n\n    case \"google\":\n      body = (\n        <>\n          <Heading title={t.googleTitle} sub={fill(t.googleSub, { email })} />\n          {formError([])}\n          <div className=\"flex flex-col gap-3\">\n            {googleButton(true)}\n            {outline(t.back, toEmail)}\n          </div>\n        </>\n      );\n      break;\n\n    case \"signup\":\n      body = (\n        <>\n          <Heading title={t.signupTitle} />\n          {formError(on.password ? [\"name\", \"password\"] : [\"name\"])}\n          <form className=\"m-0 flex flex-col gap-4\" noValidate onSubmit={onSignup}>\n            {readOnlyEmail}\n            <div className=\"flex flex-col gap-1\">\n              <Label htmlFor=\"auth-name\" bad={Boolean(errorOf(\"name\"))}>\n                {t.nameLabel}\n              </Label>\n              <AuthField\n                id=\"auth-name\"\n                ref={refs.name}\n                name=\"name\"\n                autoComplete=\"name\"\n                maxLength={50}\n                value={name}\n                onChange={(e) => setName(e.target.value)}\n                aria-invalid={Boolean(errorOf(\"name\")) || undefined}\n                className={field(Boolean(errorOf(\"name\")))}\n              />\n              <AuthError>{errorOf(\"name\")}</AuthError>\n            </div>\n            {on.password ? passwordField(\"auth-new-password\", fill(t.newPasswordLabel, { min: passwordMin }), \"new-password\") : null}\n            <div className=\"flex flex-col gap-3\">\n              {submit(t.createAccount)}\n              {outline(t.back, toEmail)}\n            </div>\n          </form>\n        </>\n      );\n      break;\n\n    case \"code\": {\n      const bad = errorOf(\"code\");\n      body = (\n        <>\n          <Heading title={purpose === \"sign-up\" ? t.verifyTitle : t.codeTitle} sub={fill(t.codeSub, { email })} />\n          {formError([\"code\"])}\n          <form className=\"m-0 flex flex-col gap-4\" noValidate onSubmit={onCode}>\n            <div className=\"flex justify-center\">\n              <AuthCodeBoxes\n                id=\"auth-code\"\n                name=\"code\"\n                inputRef={refs.code}\n                value={code}\n                label={t.codeLabel}\n                bad={Boolean(bad)}\n                fill={!auto}\n                readOnly={auto && submitting}\n                onChange={(v) => {\n                  if (problem?.field === \"code\") setProblem(null);\n                  setCode(v);\n                  // codeAuto: the sixth digit is the submit (once per code — a wrong one empties the boxes).\n                  if (auto && v.length === 6 && v !== code && !submitting) verify(v);\n                }}\n              />\n            </div>\n            {bad ? (\n              <div className=\"-mt-3 flex justify-center\">\n                <AuthError>{bad}</AuthError>\n              </div>\n            ) : auto && submitting ? (\n              <div className=\"flex h-4 justify-center text-muted-foreground [&_svg]:size-4\">\n                <Spinner label={t.busy} />\n              </div>\n            ) : (\n              <p className=\"m-0 text-center text-xs leading-4 text-muted-foreground\">{notice || t.codeHint}</p>\n            )}\n            {auto ? (\n              <p className=\"m-0 text-center text-xs leading-4 text-muted-foreground\">\n                <button type=\"button\" className={link} onClick={resend} disabled={busy === \"resend\"} aria-busy={busy === \"resend\" || undefined}>\n                  {t.resendCode}\n                </button>\n              </p>\n            ) : (\n              <div className=\"flex flex-col gap-3\">\n                {submit(t.continue)}\n                {outline(t.resendCode, resend, { busy: busy === \"resend\" })}\n              </div>\n            )}\n          </form>\n          <p className={cn(\"mb-0 text-center text-xs leading-4 text-muted-foreground\", auto ? \"mt-2\" : \"mt-4\")}>\n            <button type=\"button\" className={link} onClick={toEmail}>\n              {t.otherEmail}\n            </button>\n          </p>\n        </>\n      );\n      break;\n    }\n\n    case \"twofactor\": {\n      const bad = errorOf(\"code\");\n      body = (\n        <>\n          <Heading title={t.twoFactorTitle} sub={recovery ? t.recoverySub : t.twoFactorSub} />\n          {formError([\"code\"])}\n          <form className=\"m-0 flex flex-col gap-4\" noValidate onSubmit={onTwoFactor}>\n            {recovery ? (\n              <div className=\"flex flex-col gap-1\">\n                <Label htmlFor=\"auth-recovery\" bad={Boolean(bad)}>\n                  {t.recoveryLabel}\n                </Label>\n                <AuthField\n                  id=\"auth-recovery\"\n                  ref={refs.code}\n                  autoComplete=\"off\"\n                  autoCapitalize=\"off\"\n                  spellCheck={false}\n                  value={code}\n                  onChange={(e) => setCode(e.target.value)}\n                  aria-invalid={Boolean(bad) || undefined}\n                  className={field(Boolean(bad))}\n                />\n                <AuthError>{bad}</AuthError>\n              </div>\n            ) : (\n              <>\n                <div className=\"flex justify-center\">\n                  <AuthCodeBoxes\n                    id=\"auth-two-factor\"\n                    inputRef={refs.code}\n                    value={code}\n                    label={t.twoFactorLabel}\n                    bad={Boolean(bad)}\n                    fill\n                    onChange={(v) => {\n                      if (problem?.field === \"code\") setProblem(null);\n                      setCode(v);\n                    }}\n                  />\n                </div>\n                {bad ? (\n                  <div className=\"-mt-3 flex justify-center\">\n                    <AuthError>{bad}</AuthError>\n                  </div>\n                ) : (\n                  <p className=\"m-0 text-center text-xs leading-4 text-muted-foreground\">{t.twoFactorHint}</p>\n                )}\n              </>\n            )}\n            <div className=\"flex flex-col gap-3\">\n              {submit(t.signIn)}\n              {outline(recovery ? t.useApp : t.useRecovery, () => {\n                clear();\n                setCode(\"\");\n                setRecovery((r) => !r);\n                setTimeout(() => refs.code.current?.focus(), 0);\n              })}\n            </div>\n          </form>\n        </>\n      );\n      break;\n    }\n\n    case \"forgot\":\n      body = (\n        <>\n          <Heading title={t.forgotTitle} sub={t.forgotSub} />\n          {formError([\"email\"])}\n          <form className=\"m-0 flex flex-col gap-4\" noValidate onSubmit={sendReset}>\n            {emailField(\"auth-forgot-email\", false)}\n            <div className=\"flex flex-col gap-3\">\n              {submit(t.sendReset)}\n              {outline(t.back, () => go(forgotFrom))}\n            </div>\n          </form>\n        </>\n      );\n      break;\n\n    case \"sent\":\n      body = (\n        <>\n          <div role=\"status\">\n            <Heading mark={<MailOpen />} title={t.sentTitle} sub={fill(t.sentSub, { email })} />\n          </div>\n          {formError([])}\n          <div className=\"flex flex-col gap-3\">{outline(t.resendReset, () => sendReset(), { busy: busy === \"resend\" })}</div>\n        </>\n      );\n      break;\n\n    case \"routing\":\n      body = (\n        <div role=\"status\" aria-label={t.signingIn} className=\"flex justify-center [&_svg]:size-6\">\n          <LoaderCircle className=\"animate-spin\" aria-hidden=\"true\" />\n        </div>\n      );\n      break;\n  }\n\n  const column = (\n    <section data-step={step} className={cn(\"flex w-full flex-col text-foreground [word-break:keep-all]\", props.className)}>\n      {body}\n    </section>\n  );\n  if (props.bare) return column;\n  return (\n    <AuthLayout brand={props.brand} app={props.app} footer={props.footer}>\n      {column}\n    </AuthLayout>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:block"
}