{
  "name": "card-field",
  "type": "registry:component",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "files": [
    {
      "type": "registry:component",
      "content": "\"use client\";\n\n/**\n * @author: @dorianbaffier\n * @description: Card Field\n * @version: 1.0.0\n * @date: 2026-10-22\n * @license: MIT\n * @website: https://kokonutui.com\n * @github: https://github.com/kokonut-labs/kokonutui\n */\n\nimport { Check, CreditCard, Lock } from \"lucide-react\";\nimport {\n  AnimatePresence,\n  animate,\n  motion,\n  useMotionValue,\n  useReducedMotion,\n} from \"motion/react\";\nimport {\n  type ChangeEvent,\n  type KeyboardEvent,\n  type ReactNode,\n  type RefObject,\n  useEffect,\n  useId,\n  useLayoutEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport { cn } from \"@/lib/utils\";\n\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\nconst NOT_DIGIT = /\\D/g;\nconst TEST_CARD = \"4242424242424242\";\n\ntype Brand = \"visa\" | \"mastercard\" | \"amex\" | \"discover\" | \"unknown\";\n\ninterface BrandSpec {\n  brand: Brand;\n  match: RegExp;\n  groups: number[];\n  cvc: number;\n}\n\nconst BRANDS: BrandSpec[] = [\n  { brand: \"amex\", match: /^3[47]/, groups: [4, 6, 5], cvc: 4 },\n  { brand: \"visa\", match: /^4/, groups: [4, 4, 4, 4], cvc: 3 },\n  {\n    brand: \"mastercard\",\n    match: /^(5[1-5]|2[2-7])/,\n    groups: [4, 4, 4, 4],\n    cvc: 3,\n  },\n  {\n    brand: \"discover\",\n    match: /^(6011|65|64[4-9])/,\n    groups: [4, 4, 4, 4],\n    cvc: 3,\n  },\n];\nconst UNKNOWN: BrandSpec = {\n  brand: \"unknown\",\n  match: /^/,\n  groups: [4, 4, 4, 4],\n  cvc: 3,\n};\n\nconst BRAND_NAMES: Record<Brand, string> = {\n  visa: \"Visa\",\n  mastercard: \"Mastercard\",\n  amex: \"American Express\",\n  discover: \"Discover\",\n  unknown: \"Card\",\n};\n\nexport interface CardDetails {\n  brand: Brand;\n  last4: string;\n  /** MM/YY */\n  expiry: string;\n}\n\nexport interface CardFieldProps {\n  /** What the button charges. */\n  amount?: number;\n  currency?: string;\n  /** Charge the card. Return a promise and the button waits for it. */\n  onPay?: (card: CardDetails) => Promise<void> | void;\n  /** Shows a \"Use test card\" link that types 4242… in for you. */\n  testMode?: boolean;\n  className?: string;\n}\n\nconst specFor = (digits: string) =>\n  BRANDS.find((spec) => spec.match.test(digits)) ?? UNKNOWN;\n\nconst lengthOf = (spec: BrandSpec) =>\n  spec.groups.reduce((sum, size) => sum + size, 0);\n\n/** Cuts digits into the brand's groups: Amex is 4-6-5, the rest 4-4-4-4. */\nfunction groupsOf(digits: string, spec: BrandSpec) {\n  const out: string[] = [];\n  let at = 0;\n  for (const size of spec.groups) {\n    if (at >= digits.length) {\n      break;\n    }\n    out.push(digits.slice(at, at + size));\n    at += size;\n  }\n  return out;\n}\n\nfunction luhn(digits: string) {\n  let sum = 0;\n  for (let i = 0; i < digits.length; i++) {\n    let d = Number(digits.at(-1 - i));\n    if (i % 2 === 1) {\n      d *= 2;\n      if (d > 9) {\n        d -= 9;\n      }\n    }\n    sum += d;\n  }\n  return sum % 10 === 0;\n}\n\n/** \"1\" waits for the second digit; \"4\" means April, so it becomes \"04\". */\nfunction formatExpiry(digits: string) {\n  let d = digits;\n  if (d.length === 1 && Number(d) > 1) {\n    d = `0${d}`;\n  }\n  if (d.length <= 2) {\n    return d.length === 2 ? `${d} / ` : d;\n  }\n  return `${d.slice(0, 2)} / ${d.slice(2, 4)}`;\n}\n\nfunction expiryProblem(digits: string) {\n  if (digits.length < 4) {\n    return null;\n  }\n  const month = Number(digits.slice(0, 2));\n  const year = 2000 + Number(digits.slice(2, 4));\n  if (month < 1 || month > 12) {\n    return \"That month doesn't exist\";\n  }\n  const now = new Date();\n  const thisMonth = now.getFullYear() * 12 + now.getMonth();\n  if (year * 12 + month - 1 < thisMonth) {\n    return \"This card has expired\";\n  }\n  return null;\n}\n\nfunction BrandMark({ brand, back }: { brand: Brand; back: boolean }) {\n  if (back) {\n    // Where the security code lives: the back for most cards, the front for Amex.\n    return brand === \"amex\" ? (\n      <svg aria-hidden=\"true\" className=\"h-5 w-8\" viewBox=\"0 0 32 20\">\n        <rect\n          className=\"fill-zinc-100 stroke-zinc-300 dark:fill-zinc-800 dark:stroke-zinc-600\"\n          height=\"19\"\n          rx=\"3\"\n          width=\"31\"\n          x=\"0.5\"\n          y=\"0.5\"\n        />\n        <rect\n          className=\"fill-zinc-300 dark:fill-zinc-600\"\n          height=\"2\"\n          rx=\"1\"\n          width=\"12\"\n          x=\"4\"\n          y=\"12\"\n        />\n        <rect\n          className=\"fill-orange-500\"\n          height=\"5\"\n          rx=\"1.5\"\n          width=\"9\"\n          x=\"19\"\n          y=\"4\"\n        />\n      </svg>\n    ) : (\n      <svg aria-hidden=\"true\" className=\"h-5 w-8\" viewBox=\"0 0 32 20\">\n        <rect\n          className=\"fill-zinc-100 stroke-zinc-300 dark:fill-zinc-800 dark:stroke-zinc-600\"\n          height=\"19\"\n          rx=\"3\"\n          width=\"31\"\n          x=\"0.5\"\n          y=\"0.5\"\n        />\n        <rect\n          className=\"fill-zinc-700 dark:fill-zinc-400\"\n          height=\"4\"\n          width=\"31\"\n          x=\"0.5\"\n          y=\"3\"\n        />\n        <rect\n          className=\"fill-white dark:fill-zinc-900\"\n          height=\"4\"\n          rx=\"1\"\n          width=\"16\"\n          x=\"4\"\n          y=\"10\"\n        />\n        <rect\n          className=\"fill-orange-500\"\n          height=\"5\"\n          rx=\"1.5\"\n          width=\"7\"\n          x=\"21\"\n          y=\"9.5\"\n        />\n      </svg>\n    );\n  }\n  switch (brand) {\n    case \"visa\":\n      return (\n        <svg aria-hidden=\"true\" className=\"h-5 w-8\" viewBox=\"0 0 32 20\">\n          <rect\n            className=\"fill-white stroke-zinc-200 dark:stroke-zinc-700\"\n            height=\"19\"\n            rx=\"3\"\n            width=\"31\"\n            x=\"0.5\"\n            y=\"0.5\"\n          />\n          <text\n            fill=\"#1a1f71\"\n            fontFamily=\"Arial, sans-serif\"\n            fontSize=\"9\"\n            fontStyle=\"italic\"\n            fontWeight=\"800\"\n            textAnchor=\"middle\"\n            x=\"16\"\n            y=\"13.4\"\n          >\n            VISA\n          </text>\n        </svg>\n      );\n    case \"mastercard\":\n      return (\n        <svg aria-hidden=\"true\" className=\"h-5 w-8\" viewBox=\"0 0 32 20\">\n          <rect\n            className=\"fill-zinc-900 dark:fill-zinc-800\"\n            height=\"20\"\n            rx=\"3.5\"\n            width=\"32\"\n          />\n          <circle cx=\"13\" cy=\"10\" fill=\"#eb001b\" r=\"5.5\" />\n          <circle cx=\"19\" cy=\"10\" fill=\"#f79e1b\" r=\"5.5\" />\n          <path\n            d=\"M16 5.4a5.5 5.5 0 0 1 0 9.2a5.5 5.5 0 0 1 0-9.2z\"\n            fill=\"#ff5f00\"\n          />\n        </svg>\n      );\n    case \"amex\":\n      return (\n        <svg aria-hidden=\"true\" className=\"h-5 w-8\" viewBox=\"0 0 32 20\">\n          <rect fill=\"#1f72cd\" height=\"20\" rx=\"3.5\" width=\"32\" />\n          <text\n            fill=\"white\"\n            fontFamily=\"Arial, sans-serif\"\n            fontSize=\"7.4\"\n            fontWeight=\"800\"\n            letterSpacing=\"0.2\"\n            textAnchor=\"middle\"\n            x=\"16\"\n            y=\"12.6\"\n          >\n            AMEX\n          </text>\n        </svg>\n      );\n    case \"discover\":\n      return (\n        <svg aria-hidden=\"true\" className=\"h-5 w-8\" viewBox=\"0 0 32 20\">\n          <rect\n            className=\"fill-white stroke-zinc-200 dark:stroke-zinc-700\"\n            height=\"19\"\n            rx=\"3\"\n            width=\"31\"\n            x=\"0.5\"\n            y=\"0.5\"\n          />\n          <circle cx=\"23.5\" cy=\"10\" fill=\"#f58220\" r=\"3.6\" />\n          <text\n            fill=\"#231f20\"\n            fontFamily=\"Arial, sans-serif\"\n            fontSize=\"5.4\"\n            fontWeight=\"800\"\n            x=\"4\"\n            y=\"12\"\n          >\n            DISC\n          </text>\n        </svg>\n      );\n    default:\n      return (\n        <CreditCard\n          aria-hidden\n          className=\"h-5 w-8 text-zinc-400 dark:text-zinc-500\"\n          strokeWidth={1.5}\n        />\n      );\n  }\n}\n\ninterface Fade {\n  duration: number;\n  ease: typeof EASE_OUT;\n}\ntype Slide =\n  | { duration: number }\n  | { type: \"spring\"; duration: number; bounce: number };\n\nfunction rowTone(error: boolean, focused: boolean) {\n  if (error) {\n    return \"border-red-400 dark:border-red-500/70\";\n  }\n  return focused\n    ? \"border-zinc-400 ring-4 ring-zinc-900/5 dark:border-zinc-600 dark:ring-white/5\"\n    : \"border-zinc-200 dark:border-zinc-800\";\n}\n\nfunction BrandSlot({\n  brand,\n  back,\n  fade,\n}: {\n  brand: Brand;\n  back: boolean;\n  fade: Fade;\n}) {\n  return (\n    <span className=\"relative flex h-5 w-8 shrink-0 items-center justify-center\">\n      <AnimatePresence initial={false} mode=\"popLayout\">\n        <motion.span\n          animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n          className=\"absolute inset-0 flex items-center justify-center\"\n          exit={{ opacity: 0, y: -6, filter: \"blur(2px)\" }}\n          initial={{ opacity: 0, y: 6, filter: \"blur(2px)\" }}\n          key={back ? `back-${brand}` : brand}\n          transition={fade}\n        >\n          <BrandMark back={back} brand={brand} />\n        </motion.span>\n      </AnimatePresence>\n      <span aria-live=\"polite\" className=\"sr-only\">\n        {brand === \"unknown\" ? \"\" : BRAND_NAMES[brand]}\n      </span>\n    </span>\n  );\n}\n\n/**\n * Runs steps a keystroke apart, with a pause after `pauseAfter` so the\n * number has time to slide away before expiry is typed.\n */\nfunction playSteps(\n  steps: (() => void)[],\n  timer: RefObject<ReturnType<typeof setTimeout> | undefined>,\n  pauseAfter: number\n) {\n  const run = (i: number) => {\n    if (i >= steps.length) {\n      return;\n    }\n    steps[i]();\n    timer.current = setTimeout(() => run(i + 1), i === pauseAfter ? 260 : 45);\n  };\n  run(0);\n}\n\n/** What typing into the expiry field leaves, as up to four digits. */\nfunction nextExpiry(previous: string, raw: string, inputType: string) {\n  let digits = raw.replace(NOT_DIGIT, \"\").slice(0, 4);\n  // Deleting the \" / \" takes the month digit with it.\n  if (\n    inputType === \"deleteContentBackward\" &&\n    previous.length === 2 &&\n    digits.length === 2\n  ) {\n    digits = digits.slice(0, 1);\n  }\n  if (digits.length === 1 && Number(digits) > 1) {\n    digits = `0${digits}`;\n  }\n  return digits;\n}\n\n/** Backspace in an empty field, or ← at its start, goes to the field before. */\nfunction stepsBack(event: KeyboardEvent<HTMLInputElement>, value: string) {\n  const input = event.currentTarget;\n  const atStart = input.selectionStart === 0 && input.selectionEnd === 0;\n  return (\n    (event.key === \"Backspace\" && value.length === 0) ||\n    (event.key === \"ArrowLeft\" && atStart)\n  );\n}\n\n/** Ghost digits show what's still to type, in the brand's grouping. */\nfunction ghostsFor(spec: BrandSpec, typedLength: number) {\n  let typed = typedLength;\n  return spec.groups.map((size) => {\n    const used = Math.min(size, typed);\n    typed -= used;\n    return \"0\".repeat(size - used);\n  });\n}\n\n/** The drawn copy of the number, under a clear input, so groups can fade and slide. */\nfunction NumberMirror({\n  spec,\n  groups,\n  typedLength,\n  collapsed,\n  hideGhost,\n  shift,\n  slide,\n  fade,\n  groupRefs,\n}: {\n  spec: BrandSpec;\n  groups: string[];\n  typedLength: number;\n  collapsed: boolean;\n  hideGhost: boolean;\n  shift: number;\n  slide: Slide;\n  fade: Fade;\n  groupRefs: RefObject<(HTMLSpanElement | null)[]>;\n}) {\n  const ghost = ghostsFor(spec, typedLength);\n  return (\n    <motion.div\n      animate={{ transform: `translateX(${-shift}px)` }}\n      aria-hidden=\"true\"\n      className=\"pointer-events-none absolute inset-y-0 left-0 flex items-center whitespace-pre text-[15px] text-zinc-900 tabular-nums tracking-wide dark:text-zinc-100\"\n      initial={false}\n      transition={slide}\n    >\n      {spec.groups.map((size, i) => {\n        const typed = groups[i] ?? \"\";\n        const isLast = i === spec.groups.length - 1;\n        return (\n          <motion.span\n            animate={{ opacity: collapsed && !isLast ? 0 : 1 }}\n            initial={false}\n            key={`${spec.brand}-${size}-${i.toString()}`}\n            ref={(el) => {\n              groupRefs.current[i] = el;\n            }}\n            transition={fade}\n          >\n            {typed}\n            <span\n              className={cn(\n                \"text-zinc-300 transition-opacity duration-150 dark:text-zinc-700\",\n                hideGhost && \"opacity-0\"\n              )}\n            >\n              {ghost[i]}\n            </span>\n            {isLast ? \"\" : \" \"}\n          </motion.span>\n        );\n      })}\n    </motion.div>\n  );\n}\n\nfunction Hint({\n  id,\n  error,\n  onCvc,\n  spec,\n  fade,\n}: {\n  id: string;\n  error: string | null;\n  onCvc: boolean;\n  spec: BrandSpec;\n  fade: Fade;\n}) {\n  let key = \"secure\";\n  let body: ReactNode = (\n    <>\n      <Lock aria-hidden className=\"size-3\" />\n      Encrypted end to end\n    </>\n  );\n  if (error) {\n    key = error;\n    body = error;\n  } else if (onCvc) {\n    key = \"cvc\";\n    body = `${spec.cvc} digits, ${spec.brand === \"amex\" ? \"on the front\" : \"on the back\"} of your card`;\n  }\n  return (\n    <div className=\"relative mt-2 h-4 text-xs\" id={id}>\n      <AnimatePresence initial={false} mode=\"popLayout\">\n        <motion.p\n          animate={{ opacity: 1, y: 0 }}\n          className={cn(\n            \"flex items-center gap-1.5\",\n            error\n              ? \"text-red-600 dark:text-red-400\"\n              : \"text-zinc-500 dark:text-zinc-400\"\n          )}\n          exit={{ opacity: 0, y: -4 }}\n          initial={{ opacity: 0, y: 4 }}\n          key={key}\n          transition={fade}\n        >\n          {body}\n        </motion.p>\n      </AnimatePresence>\n    </div>\n  );\n}\n\nconst PAY_TONES = {\n  off: \"bg-zinc-100 text-zinc-400 dark:bg-zinc-900 dark:text-zinc-600\",\n  ready:\n    \"bg-zinc-900 text-white hover:bg-zinc-800 dark:bg-zinc-100 dark:text-zinc-900 dark:hover:bg-white\",\n  paid: \"bg-emerald-600 text-white dark:bg-emerald-500 dark:text-emerald-950\",\n};\n\nfunction PayButton({\n  ready,\n  status,\n  money,\n  fade,\n  onPay,\n}: {\n  ready: boolean;\n  status: \"idle\" | \"paying\" | \"paid\";\n  money: string;\n  fade: Fade;\n  onPay: () => void;\n}) {\n  let payTone = ready ? PAY_TONES.ready : PAY_TONES.off;\n  if (status === \"paid\") {\n    payTone = PAY_TONES.paid;\n  }\n  let announcement = \"\";\n  if (status === \"paying\") {\n    announcement = \"Processing payment\";\n  } else if (status === \"paid\") {\n    announcement = `Paid ${money}`;\n  }\n  return (\n    <>\n      <span aria-live=\"polite\" className=\"sr-only\">\n        {announcement}\n      </span>\n      <button\n        aria-disabled={!ready}\n        className={cn(\n          \"mt-4 flex h-11 w-full items-center justify-center gap-2 rounded-xl font-medium text-sm outline-none\",\n          \"transition-colors duration-200 ease-out focus-visible:ring-2 focus-visible:ring-zinc-400 focus-visible:ring-offset-2 dark:focus-visible:ring-offset-zinc-950\",\n          payTone\n        )}\n        onClick={onPay}\n        type=\"button\"\n      >\n        <AnimatePresence initial={false} mode=\"popLayout\">\n          <motion.span\n            animate={{ opacity: 1, y: 0 }}\n            className=\"inline-flex items-center gap-2\"\n            exit={{ opacity: 0, y: -8 }}\n            initial={{ opacity: 0, y: 8 }}\n            key={status}\n            transition={fade}\n          >\n            {status === \"idle\" && `Pay ${money}`}\n            {status === \"paying\" && (\n              <>\n                <span className=\"size-3.5 animate-spin rounded-full border-2 border-current border-r-transparent\" />\n                Processing\n              </>\n            )}\n            {status === \"paid\" && (\n              <>\n                <Check aria-hidden className=\"size-4\" strokeWidth={2.5} />\n                Paid {money}\n              </>\n            )}\n          </motion.span>\n        </AnimatePresence>\n      </button>\n    </>\n  );\n}\n\n/**\n * A one-row card input for checkout. The number groups the way the brand\n * prints it, and once it checks out it slides away to its last four digits,\n * making room for expiry and security code in the same row.\n */\nexport default function CardField({\n  amount = 48,\n  currency = \"$\",\n  onPay,\n  testMode = true,\n  className,\n}: CardFieldProps) {\n  const [number, setNumber] = useState(\"\");\n  const [expiry, setExpiry] = useState(\"\");\n  const [cvc, setCvc] = useState(\"\");\n  const [editingNumber, setEditingNumber] = useState(true);\n  const [focus, setFocus] = useState<\"number\" | \"expiry\" | \"cvc\" | null>(null);\n  const [numberError, setNumberError] = useState(false);\n  const [status, setStatus] = useState<\"idle\" | \"paying\" | \"paid\">(\"idle\");\n  const reduceMotion = Boolean(useReducedMotion());\n  const shakeX = useMotionValue(0);\n\n  const numberRef = useRef<HTMLInputElement>(null);\n  const expiryRef = useRef<HTMLInputElement>(null);\n  const cvcRef = useRef<HTMLInputElement>(null);\n  const groupRefs = useRef<(HTMLSpanElement | null)[]>([]);\n  const caretRef = useRef<number | null>(null);\n  const fillTimer = useRef<ReturnType<typeof setTimeout>>(undefined);\n  const resetTimer = useRef<ReturnType<typeof setTimeout>>(undefined);\n  const [shift, setShift] = useState(0);\n  const id = useId();\n  const numberId = `${id}-number`;\n  const hintId = `${id}-hint`;\n\n  const spec = specFor(number);\n  const full = lengthOf(spec);\n  const numberDone = number.length === full && luhn(number);\n  const collapsed = numberDone && !editingNumber;\n  const groups = groupsOf(number, spec);\n  const expiryError = expiryProblem(expiry);\n  const expiryDone = expiry.length === 4 && !expiryError;\n  const cvcDone = cvc.length === spec.cvc;\n  const ready = numberDone && expiryDone && cvcDone;\n\n  const error = numberError\n    ? \"That card number doesn't look right\"\n    : expiryError;\n\n  useEffect(\n    () => () => {\n      clearTimeout(fillTimer.current);\n      clearTimeout(resetTimer.current);\n    },\n    []\n  );\n\n  // Keep the caret next to the digit it was after, across the spaces that\n  // formatting adds and removes.\n  useLayoutEffect(() => {\n    const input = numberRef.current;\n    if (caretRef.current === null || !input) {\n      return;\n    }\n    // Setting a selection on a field that isn't focused can pull focus to it.\n    if (document.activeElement !== input) {\n      caretRef.current = null;\n      return;\n    }\n    const want = caretRef.current;\n    caretRef.current = null;\n    let seen = 0;\n    let at = 0;\n    const value = input.value;\n    while (at < value.length && seen < want) {\n      if (value[at] !== \" \") {\n        seen += 1;\n      }\n      at += 1;\n    }\n    input.setSelectionRange(at, at);\n  });\n\n  // How far to slide the number so only its last group shows.\n  useLayoutEffect(() => {\n    if (!collapsed) {\n      setShift(0);\n      return;\n    }\n    const last = groupRefs.current[groups.length - 1];\n    setShift(last ? last.offsetLeft : 0);\n  }, [collapsed, groups.length]);\n\n  const collapse = () => {\n    setEditingNumber(false);\n    requestAnimationFrame(() => expiryRef.current?.focus());\n  };\n\n  // Editing after a payment keeps the new input: the pending reset would\n  // otherwise wipe it.\n  const touch = () => {\n    clearTimeout(resetTimer.current);\n    setStatus((current) => (current === \"paying\" ? current : \"idle\"));\n  };\n\n  const writeNumber = (digits: string, caretDigits: number | null) => {\n    const nextSpec = specFor(digits);\n    const clipped = digits.slice(0, lengthOf(nextSpec));\n    caretRef.current = caretDigits;\n    setNumber(clipped);\n    // A code typed for Amex is one digit too long for the other brands.\n    setCvc((current) => current.slice(0, nextSpec.cvc));\n    touch();\n    const complete = clipped.length === lengthOf(nextSpec);\n    const bad = complete && !luhn(clipped);\n    setNumberError(bad);\n    if (bad && !reduceMotion) {\n      animate(shakeX, [0, -8, 7, -4, 2, 0], {\n        duration: 0.36,\n        ease: \"easeOut\",\n      });\n    } else if (complete && !bad) {\n      collapse();\n    }\n  };\n\n  const onNumber = (event: ChangeEvent<HTMLInputElement>) => {\n    const raw = event.target.value;\n    const caret = event.target.selectionStart ?? raw.length;\n    const before = raw.slice(0, caret).replace(NOT_DIGIT, \"\").length;\n    writeNumber(raw.replace(NOT_DIGIT, \"\"), before);\n  };\n\n  const onExpiry = (event: ChangeEvent<HTMLInputElement>) => {\n    const digits = nextExpiry(\n      expiry,\n      event.target.value,\n      (event.nativeEvent as InputEvent).inputType\n    );\n    setExpiry(digits);\n    touch();\n    if (digits.length === 4 && !expiryProblem(digits)) {\n      cvcRef.current?.focus();\n    }\n  };\n\n  const onCvc = (event: ChangeEvent<HTMLInputElement>) => {\n    setCvc(event.target.value.replace(NOT_DIGIT, \"\").slice(0, spec.cvc));\n    touch();\n  };\n\n  const editNumber = () => {\n    setEditingNumber(true);\n    requestAnimationFrame(() => {\n      const input = numberRef.current;\n      if (input) {\n        input.focus();\n        input.setSelectionRange(input.value.length, input.value.length);\n      }\n    });\n  };\n\n  const onExpiryKey = (event: KeyboardEvent<HTMLInputElement>) => {\n    if (stepsBack(event, expiry)) {\n      event.preventDefault();\n      editNumber();\n    }\n  };\n\n  const onCvcKey = (event: KeyboardEvent<HTMLInputElement>) => {\n    if (stepsBack(event, cvc)) {\n      event.preventDefault();\n      const target = expiryRef.current;\n      target?.focus();\n      target?.setSelectionRange(target.value.length, target.value.length);\n    }\n    if (event.key === \"Enter\" && ready) {\n      pay();\n    }\n  };\n\n  const onNumberBlur = () => {\n    setFocus(null);\n    if (numberDone) {\n      setEditingNumber(false);\n    }\n  };\n\n  // Types the test card in like a person would, so you see the brand land\n  // and the number slide away.\n  const fillTestCard = () => {\n    clearTimeout(fillTimer.current);\n    setExpiry(\"\");\n    setCvc(\"\");\n    setEditingNumber(true);\n    numberRef.current?.focus();\n    const year = String((new Date().getFullYear() + 3) % 100).padStart(2, \"0\");\n    const steps = [\n      ...[...TEST_CARD].map(\n        (_, i) => () => writeNumber(TEST_CARD.slice(0, i + 1), i + 1)\n      ),\n      () => setExpiry(\"1\"),\n      () => setExpiry(\"12\"),\n      () => setExpiry(`12${year[0]}`),\n      () => {\n        setExpiry(`12${year}`);\n        cvcRef.current?.focus();\n      },\n      () => setCvc(\"1\"),\n      () => setCvc(\"12\"),\n      () => setCvc(\"123\"),\n    ];\n    playSteps(steps, fillTimer, TEST_CARD.length - 1);\n  };\n\n  const pay = async () => {\n    if (!ready || status !== \"idle\") {\n      return;\n    }\n    setStatus(\"paying\");\n    const details = {\n      brand: spec.brand,\n      last4: number.slice(-4),\n      expiry: `${expiry.slice(0, 2)}/${expiry.slice(2)}`,\n    };\n    try {\n      await (onPay?.(details) ??\n        new Promise((resolve) => setTimeout(resolve, 1100)));\n    } catch {\n      // A declined charge leaves the card as typed, ready to try again.\n      setStatus(\"idle\");\n      return;\n    }\n    setStatus(\"paid\");\n    clearTimeout(resetTimer.current);\n    resetTimer.current = setTimeout(() => {\n      setNumber(\"\");\n      setExpiry(\"\");\n      setCvc(\"\");\n      setEditingNumber(true);\n      setStatus(\"idle\");\n    }, 2400);\n  };\n\n  const slide = reduceMotion\n    ? { duration: 0 }\n    : { type: \"spring\" as const, duration: 0.45, bounce: 0 };\n  const fade = { duration: reduceMotion ? 0 : 0.2, ease: EASE_OUT };\n  const money = `${currency}${amount.toLocaleString(\"en-US\", { minimumFractionDigits: 2 })}`;\n\n  return (\n    <div\n      className={cn(\n        \"w-full max-w-sm rounded-3xl border border-zinc-200 bg-white p-5 dark:border-zinc-800 dark:bg-zinc-950\",\n        className\n      )}\n    >\n      <div className=\"flex items-baseline justify-between\">\n        <label\n          className=\"font-medium text-sm text-zinc-900 dark:text-zinc-100\"\n          htmlFor={numberId}\n        >\n          Card\n        </label>\n        {testMode && (\n          <button\n            className=\"rounded text-xs text-zinc-500 underline decoration-zinc-300 underline-offset-2 outline-none transition-colors duration-150 hover:text-zinc-900 focus-visible:ring-2 focus-visible:ring-zinc-400 dark:text-zinc-400 dark:decoration-zinc-700 dark:hover:text-zinc-100\"\n            onClick={fillTestCard}\n            type=\"button\"\n          >\n            Use test card\n          </button>\n        )}\n      </div>\n\n      <motion.div\n        className={cn(\n          \"mt-2 flex h-12 items-center gap-3 rounded-xl border bg-white px-3 transition-[border-color,box-shadow] duration-150 dark:bg-zinc-950\",\n          rowTone(Boolean(error), focus !== null)\n        )}\n        style={{ x: shakeX }}\n      >\n        <BrandSlot back={focus === \"cvc\"} brand={spec.brand} fade={fade} />\n\n        {/* The number. A clear input over a drawn copy, so the groups can\n            fade and slide while the caret stays native. */}\n        <div className=\"relative h-full min-w-0 flex-1 overflow-hidden\">\n          <NumberMirror\n            collapsed={collapsed}\n            fade={fade}\n            groupRefs={groupRefs}\n            groups={groups}\n            hideGhost={collapsed || (number.length === 0 && focus !== \"number\")}\n            shift={shift}\n            slide={slide}\n            spec={spec}\n            typedLength={number.length}\n          />\n          {number.length === 0 && focus !== \"number\" && (\n            <span className=\"pointer-events-none absolute inset-y-0 left-0 flex items-center text-[15px] text-zinc-400 dark:text-zinc-500\">\n              Card number\n            </span>\n          )}\n          <input\n            aria-describedby={hintId}\n            aria-invalid={numberError}\n            autoComplete=\"cc-number\"\n            className={cn(\n              \"absolute inset-0 h-full w-full bg-transparent text-[15px] text-transparent tabular-nums tracking-wide caret-zinc-900 outline-none dark:caret-zinc-100\",\n              collapsed && \"pointer-events-none\"\n            )}\n            id={numberId}\n            inputMode=\"numeric\"\n            onBlur={onNumberBlur}\n            onChange={onNumber}\n            onFocus={() => {\n              setFocus(\"number\");\n              setEditingNumber(true);\n            }}\n            onKeyDown={(event) => {\n              // Tab from a finished number lands in expiry, not past the row.\n              if (event.key === \"Tab\" && !event.shiftKey && numberDone) {\n                event.preventDefault();\n                collapse();\n              }\n            }}\n            ref={numberRef}\n            spellCheck={false}\n            tabIndex={collapsed ? -1 : 0}\n            value={groups.join(\" \")}\n          />\n          {collapsed && (\n            <button\n              aria-label={`Edit card number ending ${number.slice(-4)}`}\n              className=\"absolute inset-0 cursor-text rounded-md outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 focus-visible:ring-inset\"\n              onClick={editNumber}\n              type=\"button\"\n            />\n          )}\n        </div>\n\n        <AnimatePresence initial={false}>\n          {collapsed && (\n            <motion.div\n              animate={{ opacity: 1, x: 0 }}\n              className=\"flex shrink-0 items-center gap-3\"\n              exit={{\n                opacity: 0,\n                x: 12,\n                transition: { duration: reduceMotion ? 0 : 0.12 },\n              }}\n              initial={{ opacity: 0, x: 16 }}\n              key=\"rest\"\n              transition={{ ...slide, opacity: fade }}\n            >\n              <input\n                aria-invalid={Boolean(expiryError)}\n                aria-label=\"Expiry, month and year\"\n                autoComplete=\"cc-exp\"\n                className={cn(\n                  \"h-10 w-[4.6rem] bg-transparent text-[15px] tabular-nums outline-none placeholder:text-zinc-400 dark:placeholder:text-zinc-500\",\n                  expiryError\n                    ? \"text-red-600 dark:text-red-400\"\n                    : \"text-zinc-900 dark:text-zinc-100\"\n                )}\n                inputMode=\"numeric\"\n                onBlur={() => setFocus(null)}\n                onChange={onExpiry}\n                onFocus={() => setFocus(\"expiry\")}\n                onKeyDown={onExpiryKey}\n                placeholder=\"MM / YY\"\n                ref={expiryRef}\n                value={formatExpiry(expiry)}\n              />\n              <input\n                aria-label=\"Security code\"\n                autoComplete=\"cc-csc\"\n                className=\"h-10 w-[2.6rem] bg-transparent text-[15px] text-zinc-900 tabular-nums outline-none placeholder:text-zinc-400 dark:text-zinc-100 dark:placeholder:text-zinc-500\"\n                inputMode=\"numeric\"\n                onBlur={() => setFocus(null)}\n                onChange={onCvc}\n                onFocus={() => setFocus(\"cvc\")}\n                onKeyDown={onCvcKey}\n                placeholder={spec.cvc === 4 ? \"CVV\" : \"CVC\"}\n                ref={cvcRef}\n                value={cvc}\n              />\n            </motion.div>\n          )}\n        </AnimatePresence>\n      </motion.div>\n\n      <Hint\n        error={error}\n        fade={fade}\n        id={hintId}\n        onCvc={focus === \"cvc\"}\n        spec={spec}\n      />\n\n      <PayButton\n        fade={fade}\n        money={money}\n        onPay={pay}\n        ready={ready}\n        status={status}\n      />\n    </div>\n  );\n}\n",
      "path": "/components/kokonutui/card-field.tsx",
      "target": "components/kokonutui/card-field.tsx"
    }
  ]
}