import { checkProbablyEmail } from '@astral/utils/email/checkProbablyEmail';
import { checkPhone } from '@astral/utils/phone/checkPhone';
import { formatPhoneToView } from '@astral/utils/phone/formatPhoneToView';
import { normalizePhone } from '@astral/utils/phone/normalizePhone';
export const useLogic = (props) => {
    const { onBlur, onChange, value, inputProps, isHidePersonalData, ...restProps } = props;
    const getFieldType = (targetValue) => {
        if (checkProbablyEmail(targetValue)) {
            return 'email';
        }
        const normalizedValue = normalizePhone(targetValue);
        if (checkPhone(normalizedValue)) {
            return 'phone';
        }
        return 'unknown';
    };
    const handleChange = (event) => {
        const targetValue = event.target.value;
        const type = getFieldType(targetValue);
        onChange?.({
            value: targetValue,
            normalizedValue: type === 'phone' ? normalizePhone(targetValue) : targetValue,
            type,
        });
    };
    const handleBlur = (event) => {
        const targetValue = event.target.value;
        const type = getFieldType(targetValue);
        if (type === 'phone') {
            const normalizedValue = normalizePhone(targetValue);
            const formattedValue = formatPhoneToView(normalizedValue) || '';
            onChange?.({
                value: formattedValue,
                normalizedValue,
                type,
            });
        }
        onBlur?.(event);
    };
    return {
        onBlur: handleBlur,
        restProps,
        inputValue: value?.value,
        onChange: handleChange,
        inputProps,
        isHidePersonalData,
    };
};
