{{-- ================= CSS ================= --}}
@once('css')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/intl-tel-input@19.2.16/build/css/intlTelInput.css" />
<style>
    .iti { width: 100%; direction: ltr; }
    .iti__country-list { background: #fff; width: 100%; }
    input.error { border: 1px solid #dc3545 !important; }
</style>
@endonce

{{-- ================= JS ================= --}}
@once('js')
<script src="https://cdn.jsdelivr.net/npm/intl-tel-input@19.2.16/build/js/intlTelInput.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/intl-tel-input@19.2.16/build/js/utils.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function () {

    const phoneInput = document.querySelector("input[name='phone']");

    // Skip initialization if input has NoIntl class
    if (!phoneInput || phoneInput.classList.contains('NoIntl')) return;

    const countryCodeInput = document.querySelector("input[name='country_code']");
    const phoneCodeInput   = document.querySelector("input[name='phone_code']");

    /* Phone lengths (from DB) */
    const PHONE_LENGTHS = {
        SA: 9,
        AE: 9,
        BH: 8,
        KW: 8,
        QA: 8,
        OM: 8,
        EG: 10
    };

    const iti = window.intlTelInput(phoneInput, {
        initialCountry: 'sa',
        onlyCountries: ['sa','ae','qa','om','eg','bh','kw'],
        autoHideDialCode: true,
        formatOnDisplay: false,
        strictMode: true,
        utilsScript: "https://cdn.jsdelivr.net/npm/intl-tel-input@19.2.16/build/js/utils.js"
    });

    /* ---------------- Core Helpers ---------------- */

    const setMinMax = (countryCode) => {
        const length = PHONE_LENGTHS[countryCode] || 9;
        phoneInput.setAttribute('maxlength', length);
        phoneInput.setAttribute('minlength', length);
    };

    const cleanAndLimit = () => {
        phoneInput.value = phoneInput.value.replace(/\D+/g, '');
        const max = phoneInput.getAttribute('maxlength');
        if (max) phoneInput.value = phoneInput.value.slice(0, max);
    };

    const resetError = () => {
        phoneInput.classList.remove('error');
    };

    const isValid = () => {
        const country = iti.getSelectedCountryData().iso2.toUpperCase();
        const requiredLength = PHONE_LENGTHS[country];
        return (
            phoneInput.value.length === requiredLength &&
            iti.isValidNumber()
        );
    };

    /* ---------------- Events ---------------- */

    phoneInput.addEventListener('input', function () {
        cleanAndLimit();
        resetError();
    });

    phoneInput.addEventListener('blur', function () {
        resetError();
        if (!phoneInput.value) return;
        if (!isValid()) phoneInput.classList.add('error');
    });

    phoneInput.addEventListener('countrychange', function () {
        const countryData = iti.getSelectedCountryData();
        const countryCode = countryData.iso2.toUpperCase();

        countryCodeInput.value = countryCode;
        phoneCodeInput.value   = countryData.dialCode;

        setMinMax(countryCode);
        resetError();
    });

    /* ---------------- Initial Load ---------------- */

    const initialCountry = countryCodeInput.value || 'SA';
    iti.setCountry(initialCountry.toLowerCase());
    setMinMax(initialCountry);

});
</script>
@endonce
