"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { CreditCard } from "lucide-react";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { cn } from "@open-mercato/shared/lib/utils";
import { inputWrapperVariants, inputElementVariants } from "./input.js";
const CARD_BRANDS = [
  { id: "amex", label: "AMEX", regex: /^3[47]/, format: [4, 6, 5], maxLength: 15, bg: "#006FCF" },
  { id: "visa", label: "VISA", regex: /^4/, format: [4, 4, 4, 4], maxLength: 16, bg: "#1A1F71" },
  { id: "mastercard", label: "MC", regex: /^(5[1-5]|2[2-7])/, format: [4, 4, 4, 4], maxLength: 16, bg: "#EB001B" },
  { id: "discover", label: "DISC", regex: /^(6011|64[4-9]|65|622)/, format: [4, 4, 4, 4], maxLength: 16, bg: "#FF6000" },
  { id: "diners", label: "DC", regex: /^(36|30[0-5]|309)/, format: [4, 6, 4], maxLength: 14, bg: "#0079BE" },
  { id: "jcb", label: "JCB", regex: /^35(2[89]|[3-8])/, format: [4, 4, 4, 4], maxLength: 16, bg: "#0E4C96" },
  { id: "unionpay", label: "UP", regex: /^62/, format: [4, 4, 4, 4], maxLength: 16, bg: "#E21836" }
];
const DEFAULT_FORMAT = [4, 4, 4, 4];
const DEFAULT_MAX_LENGTH = 16;
function detectBrand(digits, brands) {
  if (!digits) return null;
  for (const brand of brands) {
    if (brand.regex.test(digits)) return brand;
  }
  return null;
}
function formatDigits(digits, format) {
  if (!digits) return "";
  const groups = [];
  let cursor = 0;
  for (const groupSize of format) {
    if (cursor >= digits.length) break;
    groups.push(digits.slice(cursor, cursor + groupSize));
    cursor += groupSize;
  }
  if (cursor < digits.length) groups.push(digits.slice(cursor));
  return groups.join(" ");
}
function sanitize(input, maxLength) {
  return input.replace(/\D+/g, "").slice(0, maxLength);
}
const CardInput = React.forwardRef(
  ({
    className,
    inputClassName,
    size,
    value,
    onChange,
    onBrandChange,
    brands: brandsProp,
    showLeadingIcon = true,
    showBrandBadge = true,
    placeholder,
    disabled,
    ...props
  }, ref) => {
    const t = useT();
    const brands = brandsProp ?? CARD_BRANDS;
    const sanitizedValue = sanitize(value ?? "", DEFAULT_MAX_LENGTH);
    const detected = detectBrand(sanitizedValue, brands);
    const format = detected?.format ?? DEFAULT_FORMAT;
    const maxLength = detected?.maxLength ?? DEFAULT_MAX_LENGTH;
    const truncated = sanitizedValue.slice(0, maxLength);
    const displayed = formatDigits(truncated, format);
    const resolvedPlaceholder = placeholder ?? t("ui.inputs.cardInput.placeholder", "0000 0000 0000 0000");
    const lastBrandRef = React.useRef(null);
    React.useEffect(() => {
      const next = detected?.id ?? null;
      if (next !== lastBrandRef.current) {
        lastBrandRef.current = next;
        onBrandChange?.(detected);
      }
    }, [detected, onBrandChange]);
    const handleChange = React.useCallback(
      (event) => {
        const nextBrand = detectBrand(sanitize(event.target.value, DEFAULT_MAX_LENGTH), brands);
        const nextMax = nextBrand?.maxLength ?? DEFAULT_MAX_LENGTH;
        const digits = sanitize(event.target.value, nextMax);
        onChange(digits);
      },
      [brands, onChange]
    );
    return /* @__PURE__ */ jsxs(
      "div",
      {
        className: cn(inputWrapperVariants({ size }), className),
        "data-slot": "card-input-wrapper",
        "data-card-brand": detected?.id ?? "unknown",
        children: [
          showLeadingIcon ? /* @__PURE__ */ jsx(CreditCard, { className: "size-4 shrink-0 text-muted-foreground", "aria-hidden": "true" }) : null,
          /* @__PURE__ */ jsx(
            "input",
            {
              ref,
              type: "text",
              inputMode: "numeric",
              autoComplete: "cc-number",
              value: displayed,
              onChange: handleChange,
              placeholder: resolvedPlaceholder,
              disabled,
              className: cn(
                inputElementVariants({ size }),
                "tracking-[0.02em] tabular-nums",
                inputClassName
              ),
              ...props
            }
          ),
          showBrandBadge && detected ? /* @__PURE__ */ jsx(
            "span",
            {
              className: "flex shrink-0 items-center justify-center rounded-sm px-1.5 text-overline font-semibold uppercase tracking-wider tabular-nums leading-none select-none",
              style: {
                backgroundColor: detected.bg,
                color: detected.fg ?? "#ffffff",
                height: "24px",
                minWidth: "32px"
              },
              "aria-hidden": "true",
              children: detected.label
            }
          ) : null
        ]
      }
    );
  }
);
CardInput.displayName = "CardInput";
export {
  CARD_BRANDS,
  CardInput
};
//# sourceMappingURL=card-input.js.map
