"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useLogic = void 0;
const checkProbablyEmail_1 = require("@astral/utils/email/checkProbablyEmail");
const checkPhone_1 = require("@astral/utils/phone/checkPhone");
const formatPhoneToView_1 = require("@astral/utils/phone/formatPhoneToView");
const normalizePhone_1 = require("@astral/utils/phone/normalizePhone");
const useLogic = (props) => {
    const { onBlur, onChange, value, inputProps, isHidePersonalData, ...restProps } = props;
    const getFieldType = (targetValue) => {
        if ((0, checkProbablyEmail_1.checkProbablyEmail)(targetValue)) {
            return 'email';
        }
        const normalizedValue = (0, normalizePhone_1.normalizePhone)(targetValue);
        if ((0, checkPhone_1.checkPhone)(normalizedValue)) {
            return 'phone';
        }
        return 'unknown';
    };
    const handleChange = (event) => {
        const targetValue = event.target.value;
        const type = getFieldType(targetValue);
        onChange?.({
            value: targetValue,
            normalizedValue: type === 'phone' ? (0, normalizePhone_1.normalizePhone)(targetValue) : targetValue,
            type,
        });
    };
    const handleBlur = (event) => {
        const targetValue = event.target.value;
        const type = getFieldType(targetValue);
        if (type === 'phone') {
            const normalizedValue = (0, normalizePhone_1.normalizePhone)(targetValue);
            const formattedValue = (0, formatPhoneToView_1.formatPhoneToView)(normalizedValue) || '';
            onChange?.({
                value: formattedValue,
                normalizedValue,
                type,
            });
        }
        onBlur?.(event);
    };
    return {
        onBlur: handleBlur,
        restProps,
        inputValue: value?.value,
        onChange: handleChange,
        inputProps,
        isHidePersonalData,
    };
};
exports.useLogic = useLogic;
