{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "credit-card-input",
  "title": "Credit Card Input",
  "description": "A grouped card number, expiry and CVC field: brand detection with an animated mark, 4-4-4-4 or Amex 4-6-5 spacing, Luhn and expiry checks, and focus that moves on as each part is complete.",
  "dependencies": [
    "motion",
    "clsx",
    "tailwind-merge"
  ],
  "files": [
    {
      "path": "registry/new-york/credit-card-input/credit-card-input.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { motion, AnimatePresence } from \"motion/react\";\nimport { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nfunction cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs));\n}\n\nexport type CardBrand = \"visa\" | \"mastercard\" | \"amex\" | \"discover\" | \"troy\" | \"unknown\";\n\nexport interface CreditCardValue {\n  /** Digits only. */\n  number: string;\n  /** \"MM/YY\", possibly partial while typing. */\n  expiry: string;\n  cvc: string;\n  name: string;\n  brand: CardBrand;\n  /** Every shown field is filled in and passes its check (Luhn, future expiry, CVC length). */\n  isComplete: boolean;\n}\n\nexport type CreditCardInputSize = \"sm\" | \"md\" | \"lg\";\n\nexport interface CreditCardInputProps {\n  value?: Partial<CreditCardValue>;\n  defaultValue?: Partial<CreditCardValue>;\n  onValueChange?: (value: CreditCardValue) => void;\n  /** Adds a cardholder name row above the number. */\n  showName?: boolean;\n  label?: string;\n  helperText?: string;\n  size?: CreditCardInputSize;\n  theme?: \"dark\" | \"light\";\n  width?: number | string;\n  disabled?: boolean;\n  className?: string;\n}\n\nconst PALETTES = {\n  dark: { text: \"#F5F4F1\", muted: \"rgba(245,244,241,0.5)\", faint: \"rgba(245,244,241,0.3)\", bg: \"rgba(255,255,255,0.03)\", border: \"rgba(255,255,255,0.12)\", borderHover: \"rgba(255,255,255,0.24)\", focus: \"rgba(245,244,241,0.85)\", divider: \"rgba(255,255,255,0.09)\", chip: \"rgba(255,255,255,0.08)\", error: \"#FF7A6B\" },\n  light: { text: \"#0A0A0A\", muted: \"rgba(10,10,10,0.5)\", faint: \"rgba(10,10,10,0.3)\", bg: \"#FFFFFF\", border: \"rgba(10,10,10,0.16)\", borderHover: \"rgba(10,10,10,0.3)\", focus: \"rgba(10,10,10,0.85)\", divider: \"rgba(10,10,10,0.09)\", chip: \"rgba(10,10,10,0.06)\", error: \"#E5484D\" },\n};\n\nconst SIZES: Record<CreditCardInputSize, { font: number; row: number; padX: number; radius: number }> = {\n  sm: { font: 13, row: 38, padX: 12, radius: 11 },\n  md: { font: 14.5, row: 46, padX: 14, radius: 13 },\n  lg: { font: 16, row: 54, padX: 16, radius: 15 },\n};\n\nconst BRANDS: { brand: Exclude<CardBrand, \"unknown\">; test: RegExp; lengths: number[]; gaps: number[]; cvc: number }[] = [\n  { brand: \"amex\", test: /^3[47]/, lengths: [15], gaps: [4, 10], cvc: 4 },\n  { brand: \"troy\", test: /^9792/, lengths: [16], gaps: [4, 8, 12], cvc: 3 },\n  { brand: \"visa\", test: /^4/, lengths: [13, 16, 19], gaps: [4, 8, 12], cvc: 3 },\n  { brand: \"mastercard\", test: /^(5[1-5]|2(2[2-9]|[3-6]\\d|7[01]|720))/, lengths: [16], gaps: [4, 8, 12], cvc: 3 },\n  { brand: \"discover\", test: /^(6011|64[4-9]|65)/, lengths: [16, 19], gaps: [4, 8, 12], cvc: 3 },\n];\nconst UNKNOWN = { brand: \"unknown\" as const, lengths: [16, 19], gaps: [4, 8, 12], cvc: 3 };\n\nconst brandInfo = (digits: string) => BRANDS.find((b) => b.test.test(digits)) ?? UNKNOWN;\n// Length at which the number is \"done\" and focus moves on: 16 where allowed (Visa also allows 13/19), else the only length.\nconst typicalLength = (lengths: number[]) => (lengths.includes(16) ? 16 : lengths[0]);\n\nconst digitsIn = (s: string) => s.replace(/\\D/g, \"\");\n\nfunction luhn(digits: string) {\n  let sum = 0;\n  for (let i = 0; i < digits.length; i++) {\n    let d = Number(digits[digits.length - 1 - i]);\n    if (i % 2 === 1) {\n      d *= 2;\n      if (d > 9) d -= 9;\n    }\n    sum += d;\n  }\n  return digits.length > 0 && sum % 10 === 0;\n}\n\nfunction formatNumber(digits: string, gaps: number[]) {\n  let out = \"\";\n  for (let i = 0; i < digits.length; i++) {\n    if (gaps.includes(i)) out += \" \";\n    out += digits[i];\n  }\n  return out;\n}\n\n/** \"4\" -> \"04\", \"13\" -> \"1\" (month can't be 13), always shown as \"MM / YY\". */\nfunction normaliseExpiry(raw: string) {\n  let d = digitsIn(raw);\n  if (d.length === 1 && Number(d) > 1) d = `0${d}`;\n  if (d.length >= 2 && (Number(d.slice(0, 2)) > 12 || d.slice(0, 2) === \"00\")) d = d.slice(0, 1);\n  return d.slice(0, 4);\n}\nconst showExpiry = (d: string) => (d.length > 2 ? `${d.slice(0, 2)} / ${d.slice(2)}` : d);\n\nfunction expiryState(d: string): \"empty\" | \"partial\" | \"past\" | \"ok\" {\n  if (!d) return \"empty\";\n  if (d.length < 4) return \"partial\";\n  const month = Number(d.slice(0, 2));\n  const year = 2000 + Number(d.slice(2));\n  const now = new Date();\n  return year > now.getFullYear() || (year === now.getFullYear() && month >= now.getMonth() + 1) ? \"ok\" : \"past\";\n}\n\nfunction BrandMark({ brand, color }: { brand: CardBrand; color: string }) {\n  if (brand === \"mastercard\") {\n    return (\n      <svg width=\"26\" height=\"16\" viewBox=\"0 0 26 16\" fill=\"none\" aria-hidden=\"true\">\n        <circle cx=\"9\" cy=\"8\" r=\"6.5\" stroke={color} strokeWidth=\"1.5\" />\n        <circle cx=\"17\" cy=\"8\" r=\"6.5\" stroke={color} strokeWidth=\"1.5\" />\n      </svg>\n    );\n  }\n  if (brand === \"unknown\") {\n    return (\n      <svg width=\"24\" height=\"16\" viewBox=\"0 0 24 16\" fill=\"none\" stroke={color} strokeWidth=\"1.4\" aria-hidden=\"true\">\n        <rect x=\"1\" y=\"1\" width=\"22\" height=\"14\" rx=\"2.5\" />\n        <path d=\"M1 5.5h22M4.5 11h5\" strokeLinecap=\"round\" />\n      </svg>\n    );\n  }\n  const words: Record<string, { text: string; italic?: boolean; spacing?: string }> = {\n    visa: { text: \"VISA\", italic: true, spacing: \"0.02em\" },\n    amex: { text: \"AMEX\", spacing: \"0.06em\" },\n    discover: { text: \"DISC\", spacing: \"0.04em\" },\n    troy: { text: \"troy\", spacing: \"0\" },\n  };\n  const w = words[brand];\n  return (\n    <span aria-hidden=\"true\" style={{ color, fontSize: 11, fontWeight: 800, fontStyle: w.italic ? \"italic\" : \"normal\", letterSpacing: w.spacing, lineHeight: \"16px\" }}>\n      {w.text}\n    </span>\n  );\n}\n\nfunction CardBackIcon({ color }: { color: string }) {\n  return (\n    <svg width=\"24\" height=\"16\" viewBox=\"0 0 24 16\" fill=\"none\" aria-hidden=\"true\">\n      <rect x=\"1\" y=\"1\" width=\"22\" height=\"14\" rx=\"2.5\" stroke={color} strokeWidth=\"1.4\" />\n      <rect x=\"1\" y=\"3.5\" width=\"22\" height=\"3\" fill={color} />\n      <rect x=\"14.5\" y=\"9\" width=\"6\" height=\"3.5\" rx=\"1\" stroke={color} strokeWidth=\"1.2\" />\n    </svg>\n  );\n}\n\ntype Field = \"name\" | \"number\" | \"expiry\" | \"cvc\";\n\nexport function CreditCardInput({\n  value,\n  defaultValue,\n  onValueChange,\n  showName = false,\n  label,\n  helperText,\n  size = \"md\",\n  theme = \"dark\",\n  width = 360,\n  disabled = false,\n  className,\n}: CreditCardInputProps) {\n  const p = PALETTES[theme];\n  const s = SIZES[size];\n  const uid = React.useId();\n  // Fields are found by id when focus has to move, so no refs are read while rendering.\n  const fieldEl = (f: Field) => document.getElementById(`${uid}-${f}`) as HTMLInputElement | null;\n  const [internal, setInternal] = React.useState({\n    number: digitsIn(defaultValue?.number ?? \"\"),\n    expiry: normaliseExpiry(defaultValue?.expiry ?? \"\"),\n    cvc: digitsIn(defaultValue?.cvc ?? \"\"),\n    name: defaultValue?.name ?? \"\",\n  });\n  const isControlled = value !== undefined;\n  const cur = isControlled\n    ? { number: digitsIn(value.number ?? \"\"), expiry: normaliseExpiry(value.expiry ?? \"\"), cvc: digitsIn(value.cvc ?? \"\"), name: value.name ?? \"\" }\n    : internal;\n\n  const [focused, setFocused] = React.useState<Field | null>(null);\n  const [touched, setTouched] = React.useState<Partial<Record<Field, boolean>>>({});\n  const [hovered, setHovered] = React.useState(false);\n\n  const info = brandInfo(cur.number);\n  const maxLen = Math.max(...info.lengths);\n  const numberOk = info.lengths.includes(cur.number.length) && luhn(cur.number);\n  const exp = expiryState(cur.expiry);\n  const cvcOk = cur.cvc.length === info.cvc;\n  const nameOk = !showName || cur.name.trim().length > 1;\n\n  const errors: Partial<Record<Field, string>> = {};\n  if (touched.name && focused !== \"name\" && showName && cur.name && !nameOk) errors.name = \"Enter the name on the card\";\n  if (touched.number && focused !== \"number\" && cur.number && !numberOk) errors.number = info.lengths.includes(cur.number.length) || cur.number.length >= maxLen ? \"Card number is invalid\" : \"Card number is incomplete\";\n  if (touched.expiry && focused !== \"expiry\" && exp === \"partial\") errors.expiry = \"Expiry date is incomplete\";\n  if (exp === \"past\") errors.expiry = \"Expiry date is in the past\";\n  if (touched.cvc && focused !== \"cvc\" && cur.cvc && !cvcOk) errors.cvc = \"Security code is incomplete\";\n  const firstError = ([\"name\", \"number\", \"expiry\", \"cvc\"] as Field[]).map((f) => errors[f]).find(Boolean);\n\n  const update = (patch: Partial<typeof cur>) => {\n    const next = { ...cur, ...patch };\n    if (!isControlled) setInternal(next);\n    const b = brandInfo(next.number);\n    const complete = b.lengths.includes(next.number.length) && luhn(next.number) && expiryState(next.expiry) === \"ok\" && next.cvc.length === b.cvc && (!showName || next.name.trim().length > 1);\n    onValueChange?.({ ...next, expiry: next.expiry.length > 2 ? `${next.expiry.slice(0, 2)}/${next.expiry.slice(2)}` : next.expiry, brand: b.brand, isComplete: complete });\n  };\n\n  const focusField = (f: Field) => fieldEl(f)?.focus();\n\n  const onNumber = (raw: string) => {\n    const digits = digitsIn(raw);\n    const b = brandInfo(digits);\n    const next = digits.slice(0, Math.max(...b.lengths));\n    update({ number: next, cvc: cur.cvc.slice(0, b.cvc) });\n    if (next.length === typicalLength(b.lengths) && luhn(next)) focusField(\"expiry\");\n  };\n\n  const onExpiry = (raw: string) => {\n    const next = normaliseExpiry(raw);\n    update({ expiry: next });\n    if (next.length === 4 && expiryState(next) === \"ok\") focusField(\"cvc\");\n  };\n\n  const onCvc = (raw: string) => update({ cvc: digitsIn(raw).slice(0, info.cvc) });\n\n  // Backspace in an empty field goes back to the end of the previous one (named in data-prev).\n  const onBackspace = (e: React.KeyboardEvent<HTMLInputElement>) => {\n    const prev = e.currentTarget.dataset.prev as Field | undefined;\n    if (e.key !== \"Backspace\" || e.currentTarget.value !== \"\" || !prev) return;\n    const el = fieldEl(prev);\n    if (!el) return;\n    e.preventDefault();\n    el.focus();\n    requestAnimationFrame(() => el.setSelectionRange(el.value.length, el.value.length));\n  };\n\n  const blur = (f: Field) => () => {\n    setFocused((cur) => (cur === f ? null : cur));\n    setTouched((t) => ({ ...t, [f]: true }));\n  };\n\n  const active = focused !== null;\n  const hasError = Boolean(firstError);\n  const borderColor = hasError ? p.error : active ? p.focus : hovered ? p.borderHover : p.border;\n  const ring = hasError ? p.error : p.focus;\n\n  const inputBase = \"h-full min-w-0 flex-1 border-none bg-transparent outline-none placeholder:text-[color:var(--cc-placeholder)]\";\n  const inputStyle = (field: Field): React.CSSProperties => ({ color: errors[field] ? p.error : p.text, fontSize: s.font, fontWeight: 500, fontVariantNumeric: \"tabular-nums\", letterSpacing: field === \"number\" ? \"0.04em\" : \"0.01em\", [\"--cc-placeholder\" as string]: p.faint });\n\n  const iconKey = focused === \"cvc\" ? \"cvc\" : info.brand;\n\n  return (\n    <div className={cn(\"relative inline-flex flex-col gap-2\", className)} style={{ width, maxWidth: \"100%\", fontFamily: \"Inter, sans-serif\", opacity: disabled ? 0.5 : 1 }}>\n      {label && (\n        <label htmlFor={`${uid}-number`} className=\"font-semibold tracking-[-0.01em]\" style={{ color: p.text, fontSize: s.font }}>\n          {label}\n        </label>\n      )}\n\n      <div\n        role=\"group\"\n        aria-label={label ?? \"Card details\"}\n        onMouseEnter={() => setHovered(true)}\n        onMouseLeave={() => setHovered(false)}\n        className=\"overflow-hidden\"\n        style={{ borderRadius: s.radius, background: p.bg, border: `1px solid ${borderColor}`, boxShadow: active || hasError ? `0 0 0 3px color-mix(in srgb, ${ring} 14%, transparent)` : \"0 0 0 0 transparent\", transition: \"border-color 0.18s ease, box-shadow 0.18s ease\" }}\n      >\n        {showName && (\n          <div className=\"flex items-center\" style={{ height: s.row, padding: `0 ${s.padX}px`, borderBottom: `1px solid ${p.divider}` }}>\n            <input\n              id={`${uid}-name`}\n              type=\"text\"\n              autoComplete=\"cc-name\"\n              aria-label=\"Name on card\"\n              aria-invalid={Boolean(errors.name) || undefined}\n              disabled={disabled}\n              value={cur.name}\n              placeholder=\"Name on card\"\n              onChange={(e) => update({ name: e.target.value })}\n              onFocus={() => setFocused(\"name\")}\n              onBlur={blur(\"name\")}\n              className={inputBase}\n              style={{ ...inputStyle(\"name\"), letterSpacing: 0, fontVariantNumeric: \"normal\" }}\n            />\n          </div>\n        )}\n\n        <div className=\"flex items-center\" style={{ height: s.row, padding: `0 ${s.padX}px`, gap: 12, borderBottom: `1px solid ${p.divider}` }}>\n          <span className=\"relative flex shrink-0 items-center justify-center\" style={{ width: 38, height: 24, borderRadius: 5, background: p.chip }}>\n            <AnimatePresence mode=\"popLayout\" initial={false}>\n              <motion.span key={iconKey} className=\"flex\" initial={{ opacity: 0, y: 6, rotateX: -60 }} animate={{ opacity: 1, y: 0, rotateX: 0 }} exit={{ opacity: 0, y: -6, rotateX: 60 }} transition={{ duration: 0.2, ease: [0.16, 1, 0.3, 1] }}>\n                {iconKey === \"cvc\" ? <CardBackIcon color={p.text} /> : <BrandMark brand={info.brand} color={info.brand === \"unknown\" ? p.muted : p.text} />}\n              </motion.span>\n            </AnimatePresence>\n          </span>\n          <input\n            id={`${uid}-number`}\n            type=\"text\"\n            inputMode=\"numeric\"\n            autoComplete=\"cc-number\"\n            aria-label={label ? undefined : \"Card number\"}\n            aria-invalid={Boolean(errors.number) || undefined}\n            aria-describedby={firstError ? `${uid}-msg` : undefined}\n            disabled={disabled}\n            value={formatNumber(cur.number, info.gaps)}\n            placeholder=\"1234 1234 1234 1234\"\n            onChange={(e) => onNumber(e.target.value)}\n            data-prev={showName ? \"name\" : undefined}\n            onKeyDown={onBackspace}\n            onFocus={() => setFocused(\"number\")}\n            onBlur={blur(\"number\")}\n            className={inputBase}\n            style={inputStyle(\"number\")}\n          />\n          <span className=\"sr-only\" aria-live=\"polite\">\n            {info.brand !== \"unknown\" ? `${info.brand} card` : \"\"}\n          </span>\n        </div>\n\n        <div className=\"flex\" style={{ height: s.row }}>\n          <div className=\"flex flex-1 items-center\" style={{ padding: `0 ${s.padX}px`, borderRight: `1px solid ${p.divider}` }}>\n            <input\n              id={`${uid}-expiry`}\n              type=\"text\"\n              inputMode=\"numeric\"\n              autoComplete=\"cc-exp\"\n              aria-label=\"Expiry date, month and year\"\n              aria-invalid={Boolean(errors.expiry) || undefined}\n              disabled={disabled}\n              value={showExpiry(cur.expiry)}\n              placeholder=\"MM / YY\"\n              onChange={(e) => onExpiry(e.target.value)}\n              data-prev=\"number\"\n              onKeyDown={onBackspace}\n              onFocus={() => setFocused(\"expiry\")}\n              onBlur={blur(\"expiry\")}\n              className={inputBase}\n              style={inputStyle(\"expiry\")}\n            />\n          </div>\n          <div className=\"flex flex-1 items-center\" style={{ padding: `0 ${s.padX}px`, gap: 8 }}>\n            <input\n              id={`${uid}-cvc`}\n              type=\"text\"\n              inputMode=\"numeric\"\n              autoComplete=\"cc-csc\"\n              aria-label={`Security code, ${info.cvc} digits`}\n              aria-invalid={Boolean(errors.cvc) || undefined}\n              disabled={disabled}\n              value={cur.cvc}\n              placeholder={info.cvc === 4 ? \"CVC (4)\" : \"CVC\"}\n              onChange={(e) => onCvc(e.target.value)}\n              data-prev=\"expiry\"\n              onKeyDown={onBackspace}\n              onFocus={() => setFocused(\"cvc\")}\n              onBlur={blur(\"cvc\")}\n              className={inputBase}\n              style={inputStyle(\"cvc\")}\n            />\n          </div>\n        </div>\n      </div>\n\n      <AnimatePresence initial={false} mode=\"wait\">\n        {(firstError || helperText) && (\n          <motion.span key={firstError ?? \"helper\"} id={`${uid}-msg`} role={firstError ? \"alert\" : undefined} initial={{ opacity: 0, y: -3 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -3 }} transition={{ duration: 0.16 }} style={{ color: firstError ? p.error : p.muted, fontSize: s.font - 1.5, lineHeight: 1.4 }}>\n            {firstError ?? helperText}\n          </motion.span>\n        )}\n      </AnimatePresence>\n    </div>\n  );\n}\n",
      "type": "registry:component"
    }
  ],
  "type": "registry:component"
}