/**
 * Class for handling country field functionality in Elementor forms.
 */
class CoolFormCYFEF extends elementorModules.frontend.handlers.Base {

    /**
     * Retrieves the default settings for the country code functionality.
     * @returns {Object} An object containing selector configurations.
     */
    getDefaultSettings() {
        return {
            selectors: {
                spanerror: '.country_error',
                intlSpanElement: '.cfef-editor-intl-input',
                submitButton: 'div.cool-form__submit-group button'
            },
        };
    }
  
    /**
     * Retrieves the default elements based on the settings defined.
     * @returns {Object} An object containing jQuery elements for the input area and error span and editor span.
     */
    getDefaultElements() {
        const selectors = this.getSettings('selectors');
        return {
            $spanerror: this.$element.find(selectors.spanerror),
            $intlSpanElement: this.$element.find(selectors.intlSpanElement),
            $submitButton: this.$element.find(selectors.submitButton)
        };
    }
  
    /**
     * Binds events to the elements. This method is intended to be overridden by subclasses to add specific event handlers.
     */
    bindEvents() {
  
        // Global variable to store the shared geo IP promise.
        if (!window._ccfefGeoIpPromises) {
            window._ccfefGeoIpPromises = {};
        }
  
        this.initializeITISettings();
        this.setupInternationalCountryInput();
        this.customFlags();
        this.handleHideFlag();
        this.validateCountryInputs();
        this.setCountryFieldsLabelTyprography();
    }
  
    handleTelWithMdcFields(iti) {
        const input = iti.telInput;
        const parentFieldGroup = input.closest('.cool-form__field-group');
        const $parent = jQuery(parentFieldGroup);
    
        // Cache common elements
        const $floatingLabel = $parent.find('.mdc-floating-label');
        const $inputs = $parent.find('input');
        const $notchedOutlineNotch = $parent.find('.mdc-notched-outline__notch');
        const $notchedOutlineLeading = $parent.find('.mdc-notched-outline__leading');
    
        if ($parent.nextAll().length > 0) {
            const $nextAll = $parent.nextAll();
            if ($nextAll.length > 0) {
                const first = $nextAll[0];
                const second = $nextAll[1];

                const isSubmitGroup = (el) => el && el.classList && el.classList.contains('cool-form__submit-group');

                const conditionMatched = !$parent.hasClass('has-width-100')
                    ? (isSubmitGroup(first) || isSubmitGroup(second))
                    : isSubmitGroup(first);

                if (conditionMatched) {
                    $parent.css({ 'margin-bottom': '20px' });
                    $parent.find('.iti__country-list').css({ 'max-height': '100px' });
                }
            }
        }

        // Set initial floating label style
        $floatingLabel.css('left', '50px');
    
        // Input focus event for the second input element
        $inputs.eq(1).on('focus', () => {
            $floatingLabel.css({
                "left": "50px",
                "background-color": "white"
            });
            const borderTop = getComputedStyle($notchedOutlineNotch[0]).getPropertyValue('border-bottom');
            $notchedOutlineNotch.css({ 'border-top': borderTop });
        });
    
        // Bind a click event on the parent container
        $parent.on('click', (e) => {
            handleMainLogic();
        });
    
        // input on the first input element
        $inputs.eq(0).on('input', () => {
            handleMainLogic();
        });
    
        // Mouseover on the first input element
        $inputs.eq(0).on('mouseover', () => {
            const borderWidth = getComputedStyle($notchedOutlineLeading[0]).getPropertyValue('border-bottom-width');
            $notchedOutlineNotch.css({ 'border-top-width': borderWidth, 'border-top-color': 'black' });
        });
    
        // Parent mouseover event
        $parent.on('mouseover', (e) => {
            const borderWidth = getComputedStyle($notchedOutlineLeading[0]).getPropertyValue('border-bottom-width');
            $notchedOutlineNotch.css({ 'border-top-width': borderWidth, 'border-top-color': 'black' });
            handleMainLogic();
        });
    
        // Mouse leave event on the parent container
        $parent.on('mouseleave', (e) => {
            const borderWidth = getComputedStyle($notchedOutlineLeading[0]).getPropertyValue('border-bottom-width');
            const borderColor = getComputedStyle($notchedOutlineLeading[0]).getPropertyValue('border-right-color');
            $notchedOutlineNotch.css({ 'border-top-width': borderWidth, 'border-top-color': borderColor });
            handleMainLogic();
        });
    
        // Inner function to handle the main logic
        function handleMainLogic() {
            const $dropdown = $parent.find('.iti__dropdown-content');
            $parent.nextAll('.cool-form__field-group').each(function() {
                if (!$dropdown.hasClass('iti__hide')) {
                    this.style.zIndex = '-1';
                } else {
                    this.style.zIndex = 'initial';
                }
            });
        
        }
    } 
    
    handleHideFlag(){
        this.itiSettingData.Id.forEach(data => {
            let uniqueId = `${data.formId}${data.fieldId}`;
            let showFlags = this.itiSettingData.showFlags[uniqueId] || [] 
            showFlags = (showFlags.length > 0) ? showFlags[0] : '';

            if(showFlags !== 'yes'){
                let telInput = jQuery(`[data-uniqueid="${uniqueId}"]`)
                let selectedCountry = telInput.parent().find('.iti__country-container .iti__selected-country .iti__flag') 
                setTimeout(()=>{
                    selectedCountry.addClass('iti__globe')
                    selectedCountry.css('background-image','')
                },100)
            }    
        });
    }

    setCountryFieldsLabelTyprography() {
        setTimeout(() => {
            // Get typography values from a normal field label (direct child of .elementor-field-group)
            let fieldLabel = jQuery('.elementor-field-group > label');
            if (fieldLabel.length > 0) {
                let styleData = getComputedStyle(fieldLabel[0]);
                let fieldFontFamily = styleData.getPropertyValue('font-family');
                let fieldFontSize = styleData.getPropertyValue('font-size');
                let fieldFontStyle = styleData.getPropertyValue('font-style');
                let fieldFontWeight = styleData.getPropertyValue('font-weight');
                let fieldLineHeight = styleData.getPropertyValue('line-height');
                let fieldLetterSpacing = styleData.getPropertyValue('letter-spacing');
                let fieldTextTransform = styleData.getPropertyValue('text-transform');
                let fieldTextDecoration = styleData.getPropertyValue('text-decoration');
                let fieldTextColor = styleData.getPropertyValue('color');
  
                // Apply the typography values to the custom country code field labels.
                // Adjust the selector '.iti .elementor-field-label' if your markup differs.
                jQuery('.elementor-field-group .iti .elementor-field-label').css({
                    'font-family': fieldFontFamily,
                    'font-size': fieldFontSize,
                    'font-style': fieldFontStyle,
                    'font-weight': fieldFontWeight,
                    'line-height': fieldLineHeight,
                    'letter-spacing': fieldLetterSpacing,
                    'text-transform': fieldTextTransform,
                    'text-decoration': fieldTextDecoration,
                    'color': fieldTextColor,
                });
            }
        }, 100);
    }
    /**
    * Initializes settings for International Telephone Input.
    */
    initializeITISettings() {
        this.provider = CYFEFCustomData.geo_lookup_provider;
        if ( this.provider === 'ipapi' ) {
            this.apiKey = CYFEFCustomData.geo_lookup_key;
        } else {
            this.apiKey = CYFEFCustomData.geo_lookup_api_key;
        }

        this.itiSettingData = {
            Id: [], // Array to store telephone IDs
            defaultCountry: {}, // Object to store default country settings
            includeCountries: {}, // Object to store included countries
            excludeCountries: {}, // Object to store excluded countries
            preferredCountries: {}, // Object to store preferred countries
            autoDetectCountry: {}, // Object to store auto-detect country settings
            Internationalisation: {}, // Object to store auto-detect country settings
            showFlags: {}, // Object to store auto-detect country settings
        };
  
        this.translatedStrings = window.CCFEFCountryTranslations

        this.itiObj = {}; // Object to store ITI instances
  
        this.getIntlUserData(); // Retrieves ITI data from the DOM
    }
  
    /**
     * Sets up the international telephone input functionality.
     */
    setupInternationalCountryInput() {
        this.appendCountryCodeHandler(); // Manages country code functionality
        this.countryCodeEventsHandler(); // Initializes ITI functionality
    }
  
    /**
     * Method to handle appending country code.
     */
    appendCountryCodeHandler() {
        this.itiSettingData.Id.forEach(data => {
            this.addCountryCodeIconHandler(data.formId, data.fieldId, data.customId);
        });
    }
  
    /**
     * Method to handle adding country code icon.
     * @param {string} formId - The ID of the form.
     * @param {string} widgetId - The widget ID.
     * @param {string} inputId - The input ID.
     */
    addCountryCodeIconHandler(formId, widgetId, inputId) {
        const utilsPath = `${CYFEFCustomData.pluginDir}assets/js/utils.js`;
        const telField = jQuery(`.elementor-widget.elementor-widget-cool-form[data-id="${formId}"] .is-field-type-country.cool-form__field-group input[type="country"]#${inputId}`).get(0);

        const settingsData = this.itiSettingData;
  
  
        if (telField) {
            const uniqueId = `${formId}${widgetId}`;
            const includeCountries = settingsData.includeCountries[uniqueId] || [];
            const excludeCountries = settingsData.excludeCountries[uniqueId] || [];
            const preferredCountries = settingsData.preferredCountries[uniqueId] || [];
            const Internationalisation = settingsData.Internationalisation[uniqueId] || [];
            let showFlags = settingsData.showFlags[uniqueId] || [];
            showFlags = (showFlags.length > 0) ? showFlags[0] : ''; 
  
            let langCode    = Internationalisation;
            langCode = (langCode.length > 0) ? langCode[0] : '';
            const i18nMap         = this.translatedStrings[langCode] || this.translatedStrings
            ['en'];

            const itiOptions = {
                utilsScript: utilsPath,
                i18n:i18nMap,
                containerClass: 'cfefp-intl-container',
                nationalMode: true,
                searchCountryField: [],
                onlyCountries: includeCountries,
                excludeCountries: excludeCountries,
                autoPlaceholder: "off",
                useFullscreenPopup: false,
                fixDropdownWidth: false,
            };
  
            const iti = window.intlTelInput(telField, itiOptions);
            this.itiObj[uniqueId] = iti;
  
            if(showFlags !== 'yes'){
                jQuery(iti.dropdownContent).find('.iti__flag-box').hide()
            }
            jQuery(telField).attr('data-uniqueid',uniqueId)

            if (preferredCountries.length) {
                this.reorderPreferredCountries(iti, preferredCountries);
            }
  
            this.setInitialCountry(iti, excludeCountries, uniqueId, telField );
            iti.searchInput.remove();
        }
    }
  
    /**
     * Reorders the country list based on preferred countries.
     * @param {Object} itiInstance - The intl-tel-input instance.
     * @param {Array} preferredCountries - List of preferred country codes.
     */
    reorderPreferredCountries(itiInstance, preferredCountries) {
        const countryList = jQuery(itiInstance.countryList);
        preferredCountries.reverse().forEach((countryCode, index) => {
            const countryListItem = countryList.find(`li[data-country-code="${countryCode}"]`);
            if (countryListItem.length) {
                if (index === 0) {
                    countryList.prepend('<hr></hr>');
                }
                countryList.prepend(countryListItem);
            }
        });
    }

    fetchGeoIPData(defaultCountry, uniqueId) {
        // initialize the per-field promise map
        if (!window._ccfefGeoIpPromises) {
            window._ccfefGeoIpPromises = {};
        }
    
        // if we’ve already kicked off a lookup for this field, reuse it
        if (window._ccfefGeoIpPromises[uniqueId]) {
            return window._ccfefGeoIpPromises[uniqueId];
        }
    
        // build provider URL
        const provider = this.provider;
        const key      = this.apiKey.trim();
        let url;
        switch (provider) {
          case 'ipstack':
            url = `http://api.ipstack.com/check?access_key=${key}&format=1`;
            break;
          case 'ipinfo':
            url = `https://ipinfo.io/json${ key ? '?token=' + key : '' }`;
            break;
          case 'geojs':
            url = 'https://get.geojs.io/v1/ip/geo.json';
            break;
          case 'ip-api':
            url = 'http://ip-api.com/json';
            break;
          case 'ipapi':
          default:
            url = key
              ? `https://api.ipapi.com/api/check?access_key=${key}&format=1`
              : 'https://ipapi.co/json';
        }
    
        // start the fetch and normalize to an ISO2 code
        const promise = fetch(url)
          .then(res => {
            if (!res.ok) throw new Error(`HTTP ${res.status}`);
            return res.json();
          })
          .then(data => {
            switch (provider) {
              case 'ipstack': return data.country_code || defaultCountry;
              case 'ipinfo':  return data.country      || defaultCountry;
              case 'geojs':   return data.country_code || defaultCountry;
              case 'ip-api':  return data.countryCode || defaultCountry;
              case 'ipapi':
              default:        return data.country_code || data.country || defaultCountry;
            }
          })
          .catch(() => defaultCountry);
    
        // cache and return
        window._ccfefGeoIpPromises[uniqueId] = promise;
        return promise;
    }    
    /**
     * Sets the initial selected country in the dropdown.
     * @param {Object} itiInstance - The intl-tel-input instance.
     * @param {string} autoDetectCountry - Auto-detect country setting.
     * @param {string} defaultCountry - Default country code.
     * @param {string} apiKey - API key for geo-location services.
     * @param {Array} excludeCountries - List of countries to exclude.
     */
    setInitialCountry(itiInstance, excludeCountries, uniqueId, telField) {       
        const defaultCountry = this.itiSettingData.defaultCountry[uniqueId] || "";
        const autoDetectCountry = this.itiSettingData.autoDetectCountry[uniqueId] || "";
        const defaultCountries = ['in', 'us', 'gb', 'ru', 'fr', 'de', 'br', 'cn', 'jp', 'it'];
        const itiCountriesList = itiInstance.countries.map(data => data.iso2);
        const inputElement = itiInstance.telInput;
  
        if (jQuery(telField).closest('.is-field-type-country').hasClass('elementor-field-required') &&
            jQuery(telField).closest('.is-field-type-country').hasClass('cfef-hidden')) {
            if (defaultCountry === "") {
                itiInstance.setCountry("us");
                jQuery(telField).val("United States");    
                jQuery(telField).focus()  
                jQuery(telField).trigger('change');
            } else {
                itiInstance.setCountry(defaultCountry);
                jQuery(telField).val(defaultCountry);
                jQuery(telField).focus()    
                jQuery(telField).trigger('change');
            }
        } 
     
        const setCountry = (countryCode) => {
            if (itiCountriesList.length <= 0) {
                return;
            }
            const normalizedCountryCode = isNaN(countryCode) && countryCode ? countryCode.toLowerCase() : '';
            if (normalizedCountryCode && itiCountriesList.includes(normalizedCountryCode)) {
                itiInstance.setCountry(normalizedCountryCode);
            } else if (defaultCountry && itiCountriesList.includes(defaultCountry)) {
                itiInstance.setCountry(defaultCountry);
         
            } else {
                const availableCountries = defaultCountries.filter(country =>
                    !excludeCountries.includes(country) && itiCountriesList.includes(country)
                );
              
                const fallbackCountry = availableCountries.length > 0 ? availableCountries[0] : itiCountriesList[0];
                itiInstance.setCountry(fallbackCountry);
            }
  
            const selectedCountry = itiInstance.getSelectedCountryData();

            if (!selectedCountry.hasOwnProperty('iso2')) return;
            
            let langCode    = this.itiSettingData.Internationalisation[uniqueId] || [];
            langCode = (langCode.length > 0) ? langCode[0] : '';
            const map         = this.translatedStrings[langCode] || this.translatedStrings
            ['en'];
            const countryName = map[selectedCountry.iso2] || selectedCountry.name;
            inputElement.value = countryName;
        };
  
        if (autoDetectCountry && autoDetectCountry !== "no") {
            this.fetchGeoIPData(defaultCountry,uniqueId)
                .then(countryCode => {
                    setCountry(countryCode);
                });
        } else if (defaultCountry) {
            setCountry(defaultCountry);
        }
        
    }
  
    /**
     * Adds event handlers for the country code input field.
     */
    countryCodeEventsHandler() {
        const itiArr = this.itiObj;
  
        Object.keys(itiArr).forEach(key => {
            const iti = itiArr[key];
            this.handleTelWithMdcFields(iti);

            let inputEl = iti.telInput
            const dataSetValue = jQuery(iti.telInput).closest('.is-field-type-country')
            .find('.cfef-editor-intl-input')[0].dataset;

            const updateCountryCodeOutside = (iti,countryCode)=>{
                if(countryCode === ""){
                    iti.setCountry(countryCode);
            
                    inputEl.value = ''
                    if(inputEl.value === ''){
                        iti.countryList.style.display = 'none'
                        const input = inputEl
                        const globeBtn = jQuery(input).prev().find('.iti__flag.iti__globe')
                            const globeFlag = CYFEFCustomData.pluginDir + `assets/images/globe.png`;
                            if(globeBtn.length > 0){
                                globeBtn[0].style.backgroundImage = `url('${globeFlag}')`;
                            }
                            inputEl.value = ''
                    }
                }else{
                    const availableCodes = iti.countries.map(data => data.iso2);
                    if (availableCodes.includes(countryCode.toLowerCase())) {      
                        iti.setCountry(countryCode);
                        iti.countryList.style.display = 'block'

                        const selectedData = iti.getSelectedCountryData();
                        if (selectedData && selectedData.name) {
                            inputEl.value = selectedData.name;
                        } 
                    } 
                }
            };


            // Convert the comma‑separated strings to arrays
            const includeArr = dataSetValue.includeCountries
            ? dataSetValue.includeCountries.split(',').map(c => c.trim()).filter(Boolean)
            : [];
            const commonArr = dataSetValue.commonCountries
            ? dataSetValue.commonCountries.split(',').map(c => c.trim()).filter(Boolean)
            : [];
            const excludeArr = dataSetValue.excludeCountries
            ? dataSetValue.excludeCountries.split(',').map(c => c.trim()).filter(Boolean)
            : [];

            // Compute the intersection: countries that are present in both arrays
            const intersection = commonArr.filter(country => excludeArr.includes(country));

            // If all the countries in the include list are in the exclude list, then clear the field.
            
            // let firstCountry = iti.countryList.children[0].dataset.countryCode

            if((dataSetValue.commonCountries === "undefined" && dataSetValue.excludeCountries === "undefined" && dataSetValue.defaultCountry === "") || (dataSetValue.commonCountries === "" && dataSetValue.excludeCountries === "" && dataSetValue.defaultCountry === "")){
                updateCountryCodeOutside(iti,'us');
            }
            if (commonArr.length > 0 && intersection.length === commonArr.length && !commonArr.includes("undefined") &&
            !intersection.includes("undefined")) {
                updateCountryCodeOutside(iti,'');
            }
            if(includeArr.length > 0){
                includeArr.forEach((val)=>{
                    updateCountryCodeOutside(iti,val)
                })
            }

            const inputElement = iti.telInput;
            const parentWrp = jQuery(inputElement.closest('.is-field-type-country'));
            const itiDropdown = parentWrp.find('.iti__dropdown-content')
            const intlContainer = parentWrp.find('.iti__country-container');
            const countryLiItem = parentWrp.find('.iti__country-list .iti__country.iti__standard'); // Get country list for adding mouse hover event.
            const countryLists = Array.from(iti.countryList.querySelectorAll('li.iti__country.iti__standard')); // Get all country list Array.
            const countrylistItems = countryLists.filter(list => list);
            let handleMouseStatus=false;
            let liTrigger = false;
  
            let filteredCountriesArr = countrylistItems;
  
            /**
             * Toggles the class status of an element.
             * @param {Element} element - The element to toggle the class on.
             * @param {boolean} status - The status to set for the class.
             */
            const toggleClassStatus = (element, status) => {
                element.toggleClass('custom-iti-show', status);
            }
  
            /**
             * Handles the document click event.
             * @param {Event} event - The event object.
             */
            const handleDocumentClick = (event) => {
                const triggerElement = event.target.closest('.is-field-type-country');
                if (!triggerElement) {
                    if (filteredCountriesArr.length <= 0) {
                        updateCountryCode('');
                    }
                    intlContainer.trigger('click');
                }
            };
  
            /**
             * Handles the highlighting of the country list.
             * @param {Event} event - The event object.
             */
            const liHighlightedHandler = (event) => {
                if (['ArrowUp', 'ArrowDown'].includes(event.key)) {
                    handleMouseStatus = true;
                    setTimeout(() => {
                        handleMouseStatus = false;
                    }, 1000);
                }
                countryLiItem.removeClass('iti__highlight');
                if (filteredCountriesArr.length <= 0) {
                    return;
                }
                let listItemIndex = -1;
                if (event.key === 'ArrowUp') {
                    listItemIndex = filteredCountriesArr.findIndex((list, index) => index !== 0 && list.classList.contains('ccfef_iti__highlight'));
                    intlContainer.find('.iti__country-list .ccfef_iti__highlight').removeClass('ccfef_iti__highlight');
                    listItemIndex = listItemIndex !== -1 ? listItemIndex - 1 : filteredCountriesArr.length - 1;
                } else if (event.key === 'ArrowDown') {
                    listItemIndex = filteredCountriesArr.findIndex((list, index) => {
                        return index < filteredCountriesArr.length && list.classList.contains('ccfef_iti__highlight');
                    });
                    intlContainer.find('.iti__country-list .ccfef_iti__highlight').removeClass('ccfef_iti__highlight');
                    listItemIndex = listItemIndex === -1 || listItemIndex === (filteredCountriesArr.length - 1) ? 0 : listItemIndex + 1;
                }
  
                const highlightedLi = filteredCountriesArr[listItemIndex];
  
                if (highlightedLi) {
                    const ulListWrp = intlContainer.find('.iti__country-list');
                    const ulContainerOffsetTop = ulListWrp[0].offsetTop + ulListWrp[0].offsetHeight;
                    const highlightedLiOffsettop = highlightedLi.offsetTop;
  
                    if (highlightedLiOffsettop > ulContainerOffsetTop) {
                        ulListWrp[0].scrollTop = highlightedLiOffsettop - ulListWrp[0].offsetHeight + 23;
                    }
  
                    highlightedLi.classList.add('ccfef_iti__highlight');
                }
            }
  
            /**
             * Updates the country code in the input field.
             * @param {string} countryCode - The country code to set.
             */
            const updateCountryCode = (countryCode) => {
                this.handleTelWithMdcFields(iti)
                iti.setCountry(countryCode);
  
                let telinput = iti.telInput
                if(telinput.value === 'undefined'){
                const input = telinput
                const globeBtn = jQuery(input).prev().find('.iti__flag.iti__globe')
                    const globeFlag = CYFEFCustomData.pluginDir + `assets/images/globe.png`;
                    if(globeBtn.length > 0){
                        globeBtn[0].style.backgroundImage = `url('${globeFlag}')`;
                    }
                    telinput.value = ''
                }
            };
  
            /**
             * Handles the click event on the international container.
             */
            intlContainer.on('click', () => {
                const isHidden = parentWrp.hasClass('custom-iti-show');
                countryLiItem.removeClass('iti__highlight')
                toggleClassStatus(parentWrp, !isHidden);
  
                document.removeEventListener('click', handleDocumentClick);
                document.removeEventListener('keydown', liHighlightedHandler);
                document.removeEventListener('keydown', inputKeyDownEvent);

                setTimeout(()=>{
                    let parentWrpWidth = getComputedStyle(parentWrp[0]).getPropertyValue('width')
                    itiDropdown.css({'width':`calc(${parentWrpWidth} - 65%)`})
                    if(!parentWrp.hasClass('custom-iti-show')){                        
                        parentWrp.find('.iti__dropdown-content').addClass('iti__hide')
                    }else{
                        parentWrp.find('.iti__dropdown-content').removeClass('iti__hide')
                    }
                },100)

                if (!iti.countryList.querySelector('li.iti__country.iti__standard.ccfef_iti__highlight') && filteredCountriesArr.length > 0) {
                    filteredCountriesArr[0].classList.add('ccfef_iti__highlight');
                }
  
                if (!isHidden) {
                    document.addEventListener('keydown', inputKeyDownEvent);
                    document.addEventListener('keydown', liHighlightedHandler);
                    document.addEventListener('click', handleDocumentClick);
                }
            });

            // Listen for backspace key press
            jQuery(inputElement).on('keydown', (e) => {
                if (e.key === 'Backspace' && !parentWrp.hasClass('custom-iti-show')) {
                    // Open the dropdown list
                    toggleClassStatus(parentWrp, true);
                    jQuery(document).on('keydown', inputKeyDownEvent);
                    jQuery(document).on('keydown', liHighlightedHandler);
                    jQuery(document).on('click', handleDocumentClick);
                }
            });

            /**
             * Handles the click event on the input element.
             */
            jQuery(inputElement).on('click', () => {
                const isHidden = parentWrp.hasClass('custom-iti-show');
                if (!isHidden) {
                    intlContainer.trigger('click');
                }
            });
  
            /**
             * Handles the input event on the input element.
             */
            jQuery(inputElement).on('input', (event) => {
                this.handleTelWithMdcFields(iti);
                countryLiItem.removeClass('iti__highlight');
                countryLiItem.removeClass('ccfef_iti__highlight');
                const inputValue = event.currentTarget.value.trim().toUpperCase();
                const preferredCountryHrLine = parentWrp.find('.iti__country-list hr');

                if(itiDropdown.hasClass('iti__hide')){
                    itiDropdown.removeClass('iti__hide')
                }
  
                const updatedList = countrylistItems.filter(list => {
                    if (list.querySelector('.iti__country-name').innerText.toUpperCase().includes(inputValue)) {
                        list.style.display = "block";
                        return true;
                    } else {
                        list.style.display = "none";
                        return false;
                    }
                });
  
                if ('' !== inputValue && updatedList.length <= 0) {
                    countryLiItem.removeClass('ccfef_iti__highlight');
                    filteredCountriesArr = updatedList;
                }
  
                if (updatedList.length > 0) {
                    filteredCountriesArr = updatedList;
                    updatedList[0].classList.add('ccfef_iti__highlight');
                }
  
                if (updatedList.length > 1) {
                    filteredCountriesArr = updatedList;
                }
  
                if (preferredCountryHrLine) {
                    const hrLineVisibility = preferredCountryHrLine.prevAll('.iti__country.iti__standard').filter((_, e) => {
                        return jQuery(e).css('display') === 'block';
                    });
                    if (hrLineVisibility.length > 0) {
                        preferredCountryHrLine.show();
                    } else {
                        preferredCountryHrLine.hide();
                    }
                }
            });
  
            /**
             * Handles keyup event on the input element.
             * @param {Event} event - The event object.
             */
            const inputKeyDownEvent = (event) => {
                if (parentWrp.hasClass('custom-iti-show')) {
                    if (['Enter', 'ArrowUp', 'ArrowDown', 'Escape'].includes(event.key)) {
                        event.preventDefault();
                        if (['Enter', 'Escape'].includes(event.key)){
                            const selectedCountry = parentWrp.find('.iti__country-list .iti__country.iti__standard.ccfef_iti__highlight .iti__country-name').text() || inputElement.value;
                            const countryCode = parentWrp.find('.iti__country-list .iti__country.iti__standard.ccfef_iti__highlight').data('countryCode');
                            if (countryCode === undefined) {
                                updateCountryCode('');
                            } else {
                                updateCountryCode(countryCode);
                            }
                            inputElement.value = selectedCountry;
                            intlContainer.trigger('click');
                        }
                    }
                }
            }

            /**
             * Handles keydown event on the input element and intl container.
             */
            intlContainer[0].addEventListener('keydown', inputKeyDownEvent);
            jQuery(inputElement).on('keydown', (e) => {
                intlContainer[0].removeEventListener('keydown', inputKeyDownEvent);
                inputKeyDownEvent(e);
            });
  
            /**
             * Handles the blur event on the input element.
             */
            jQuery(inputElement).on('blur', (e) => {
                this.customFlags(e) 
                this.handleHideFlag();
                this.handleTelWithMdcFields(iti)

                if(!itiDropdown.hasClass('iti__hide')){
                    itiDropdown.addClass('iti__hide')
                }
                const userInput = inputElement.value.toUpperCase();
                const filteredCountry = filteredCountriesArr.find((country) => {
                    const listCountryName = country.querySelector('span.iti__country-name').innerText.toUpperCase();
                    return userInput === listCountryName;
                });
  
                if (filteredCountry) {
                    const countryCode = filteredCountry.getAttribute('data-country-code');
                    updateCountryCode(countryCode);
                } else {
                    updateCountryCode('');
                }
            });
  
            countryLiItem.on('mouseover', async (e) => {
                if(!handleMouseStatus){
                    countryLiItem.removeClass('iti__highlight');
                    countryLiItem.removeClass('ccfef_iti__highlight');
                    e.currentTarget.classList.add('ccfef_iti__highlight');
                }
            });
  
            /**
             * Handles the click event on the country list item.
             */
            countryLiItem.on('click', (e) => {
                liTrigger = true;
                const countryCode = e.currentTarget.getAttribute('data-country-code');
                updateCountryCode(countryCode);
            });

            /**
             * Handles the country change event on the input element.
             */
            inputElement.addEventListener('countrychange', (e) => {
                let uniqueId = inputElement.getAttribute('data-uniqueid')
                
                liTrigger = true;   
                if (liTrigger) {
                    // 1. Get the ISO2 code
                    const countryData = iti.getSelectedCountryData();
                    const iso2 = countryData.iso2;
                    const langList = this.itiSettingData.Internationalisation[uniqueId] || [];
                    const lang     = langList[0] || 'en';
                    // 3. Grab the right map from your single global
                    const map      = this.translatedStrings[lang] || this.translatedStrings['en'];
                    // 4. Pull the name from your map, fallback to the library’s .name
                    const countryName = (map[iso2] || countryData.name || '').trim();
                    // 5. Write it into the input
                    inputElement.value = countryName;
                    // 6. Re-apply your custom flag logic
                    this.customFlags(e);
                    this.handleHideFlag();
                }
            });
        });
    }


    customFlags(e) {

        const selectedCountries = this.$element.find('.is-field-type-country .cfefp-intl-container .iti__country-container .iti__flag:not(.iti__globe)');
    
        // Loop through each flag element
        selectedCountries.each(function() {
            const selectedCountry = this;  // 'this' refers to the current element in the loop
            const classList = selectedCountry.className.split(' '); 
            if (classList[1]) {
                const selectedCountryFlag = classList[1].split('__')[1]; 
                const svgFlagPath = CYFEFCustomData.pluginDir + `assets/flags/${selectedCountryFlag}.svg`;
                // Apply the styles dynamically to the current flag
                selectedCountry.style.backgroundImage = `url('${svgFlagPath}')`;
            } 
        });
    }
  
    validateCountryInputs() {
        this.elements.$submitButton.on('click', (e) => {
            const itiArr = this.itiObj;
  
            if (Object.keys(itiArr).length > 0) {
                Object.keys(itiArr).forEach(data => {
                    const iti = itiArr[data];
                    const inputTelElement = iti.telInput;
  
                    const parentWrp = inputTelElement.closest('.cool-form__field-group');
                    const telContainer = parentWrp.querySelector('.cfefp-intl-container');
  
                    if (telContainer && inputTelElement.offsetHeight) {
                        telContainer.style.setProperty('--cfefp-intl-tel-button-height', `${inputTelElement.offsetHeight}px`);
                    }
  
                    const errorContainer = jQuery(inputTelElement).parent();
                    errorContainer.find('span.elementor-message').remove();
  
                    let errorMsgHtml = '<span class="elementor-message elementor-message-danger elementor-help-inline elementor-form-help-inline" role="alert">';
                    if (inputTelElement.value.trim() === '') {
                        return;
                    }
  
                    const countryExists = iti.getSelectedCountryData().hasOwnProperty('iso2');
  
                    if (!countryExists) {
                        errorMsgHtml += `The country name "${inputTelElement.value}" does not exist.</span>`;
                        jQuery(inputTelElement).closest('.cfefp-intl-container').addClass('elementor-error');
                        jQuery(inputTelElement).after(errorMsgHtml);
                        e.preventDefault();
                    }
                });
            }
        });
    }
  
    /**
    * Retrieves and stores unique telephone input IDs from the Elementor editor span elements.
    */
    getIntlUserData() {
        const intelInputElement = this.elements.$intlSpanElement;
        const previousIds = [];
  
        intelInputElement.each((_, ele) => {
            const element = jQuery(ele);
            const dataAttributes = {
                defaultCountry: element.data('defaultCountry'),
                includeCountries: element.data('includeCountries'),
                excludeCountries: element.data('excludeCountries'),
                preferredCountries: element.data('preferredCountries'),
                autoDetectCountry: element.data('autoDetectCountry'),
                Internationalisation: element.data('internationalisation'),
                showFlags: element.data('showFlags'),
                inputId: element.data('id'),
                fieldId: element.data('field-id'),
                formId: element.closest('.elementor-element.elementor-widget-cool-form').data('id')
            };

            const currentId = `${dataAttributes.formId}${dataAttributes.fieldId}`;
  
            Object.keys(dataAttributes).forEach(attr => {
                if (dataAttributes[attr] && attr !== 'inputId' && attr !== 'fieldId' && attr !== 'formId') {
                    if (dataAttributes[attr] !== '' && isNaN(dataAttributes[attr])) {
                        const splitData = ['defaultCountry', 'autoDetectCountry'].includes(attr) ? dataAttributes[attr] : dataAttributes[attr].split(',');
                        this.itiSettingData[attr][currentId] = splitData;
                    }
                }
            });
  
            if (!previousIds.includes(currentId)) {
                this.itiSettingData.Id.push({ formId: dataAttributes.formId, fieldId: dataAttributes.fieldId, customId: dataAttributes.inputId });
                previousIds.push(currentId);
            }
        });
    }
  }
  
  jQuery(window).on('elementor/frontend/init', () => {
    const addHandler = ($element) => {
  
        elementorFrontend.elementsHandler.addHandler(CoolFormCYFEF, {
            $element,
        });
    };
  
    elementorFrontend.hooks.addAction('frontend/element_ready/cool-form.default', addHandler);
  });
  
  