import { jsx as _jsx } from "react/jsx-runtime";
import { forwardRef } from 'react';
import creditCardType from 'credit-card-type';
import Input from '../Input';
import { useConsolidatedRef, useInputFormatter } from '../../hooks';
import { formatCreditCard, isPossibleCardNumber } from './utils';
export default forwardRef(function CreditCardInput({ value = '', onChange, onBlur, onFocus, ...restProps }, ref) {
    const onInputKeyDown = (e) => {
        if (value && !isPossibleCardNumber(value) && Number.isFinite(Number.parseInt(e.key, 10))) {
            e.target.value = '';
        }
    };
    const onInputChange = (e) => {
        onChange(e.target.value ? e.target.value.replace(/\D+/g, '') : undefined);
    };
    const onInputBlur = (e) => {
        const inputValue = e.target.value;
        onBlur?.(inputValue ? inputValue.replace(/\D+/g, '') : undefined);
    };
    const onInputFocus = (e) => {
        const inputValue = e.target.value;
        onFocus?.(inputValue ? inputValue.replace(/\D+/g, '') : undefined);
    };
    const onPaste = (e) => {
        const text = e.clipboardData.getData('text').replace(/\D+/g, '');
        const [{ lengths: [inferredLength] = [] } = {}] = creditCardType(text);
        if (text.length > inferredLength) {
            onChange(Number(text).toString());
            e.preventDefault();
        }
    };
    const maxLength = value ? Math.max(...(creditCardType(value)[0]?.lengths || [16])) : undefined;
    const obfuscation = /\D/.test(value) ? 'partial' : 'none';
    const inputRef = useConsolidatedRef(ref);
    const formatted = useInputFormatter(inputRef, value, (input) => formatCreditCard(input.replace(/\D+/g, ''), { obfuscation }));
    return (_jsx(Input, { ...restProps, inputMode: 'numeric', ref: inputRef, value: formatted, onChange: onInputChange, onBlur: onInputBlur, onFocus: onInputFocus, onPaste: onPaste, onKeyDown: onInputKeyDown, maxLength: maxLength, autoComplete: 'cc-number' }));
});
//# sourceMappingURL=CreditCardInput.js.map