"use strict";
function initializePhoneInput(selector, outputSelector) {
    const phoneInput = document.querySelector(selector);
    const systemDefaultCountryCode = $('.system-default-country-code');
    const phoneNumber = phoneInput.value;
    const countryCodeMatch = phoneNumber.replace(/[^0-9]/g, '');
    const initialCountry = countryCodeMatch ? `+${countryCodeMatch}` : systemDefaultCountryCode.data('value').toLowerCase();

    let phoneInputInit = window.intlTelInput(phoneInput, {
        initialCountry: initialCountry.toLowerCase(),
        showSelectedDialCode: true,
    });

    if (!phoneInputInit.s.dialCode ){
        phoneInputInit.destroy();
        phoneInputInit = window.intlTelInput(phoneInput, {
            initialCountry: systemDefaultCountryCode.data('value').toLowerCase(),
            showSelectedDialCode: true,
        })

    }
    $(outputSelector).val('+' + phoneInputInit.s.dialCode + phoneInput.value.replace(/[^0-9]/g, ''));
    $(selector).closest('.iti--allow-dropdown').find('.iti__country').on("click", function() {
        $(outputSelector).val('+' + $(this).data('dial-code') + phoneInput.value.replace(/[^0-9]/g, ''));
    });

    $(selector).on("keyup keypress change", function() {
        $(outputSelector).val('+' + phoneInputInit.s.dialCode + phoneInput.value.replace(/[^0-9]/g, ''));
        $(selector).val(phoneInput.value.replace(/[^0-9]/g, ''));
    });
}
