(function ($) {
    'use strict';
    $(function () {
        if (typeof window.intlTelInput === 'function') {

            var user_country = localStorage.getItem('eca_socialnotify_user_country') ? localStorage.getItem('eca_socialnotify_user_country') : "auto";
            // Get all phone number fields
            const input_telephones = document.querySelectorAll('input[type="tel"]');
            input_telephones.forEach(telephone => {
                // Initliase intl library.
                const iti = window.intlTelInput(telephone, {
                    initialCountry: user_country,
                    geoIpLookup: callback => {
                        if ("auto" === user_country) {
                            fetch("https://ipapi.co/json")
                                .then(res => res.json())
                                .then(data => {
                                    callback(data?.country_code);
                                    localStorage.setItem('eca_socialnotify_user_country', data?.country_code);
                                })
                                .catch(() => callback("auto"));
                        }
                    },
                    strictMode: true,
                    nationalMode: true,
                    showSelectedDialCode: true,
                });

                const handleChange = (e) => {
                    var $this = e.target;
                    $this.value = iti.getNumber();
                };

                telephone.addEventListener('change', handleChange);
                telephone.addEventListener('keyup', handleChange);
            });
        }

    });
})(jQuery);