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

    /**
     * Retrieves the default settings for the country code functionality.
     * @returns {Object} An object containing selector configurations.
     */
    getDefaultSettings() {
        return {
            selectors: {
                intlSpanElement: '.sfef-editor-intl-input',
                countryInput: '.is-field-type-country input',
            },
        };
    }
  
    /**
     * 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 {
            $intlSpanElement: this.$element.find(selectors.intlSpanElement),
            $countryInput: this.$element.find(selectors.countryInput),
        };
    }
  
    /**
     * Binds events to the elements. This method is intended to be overridden by subclasses to add specific event handlers.
     */
    bindEvents() {
         this.onDocumentloaded();
         this.onInputChange();
    }

    /**
    * Retrieves and stores unique telephone input IDs from the Elementor editor span elements.
    */
    getIntlUserData() {
        const intelInputElement = this.elements.$intlSpanElement;
    
        intelInputElement.each((_, ele) => {
            const element = jQuery(ele);
            let countryId = element.data('country-field-id');

            if(countryId){
                let stateInput = element.closest('.cool-form__field-group').find('input');
                let stateLabel = element.siblings('label');

                // Select the element based on the countryId in its class
                let countryFieldText = this.$element.find(`.cool-form__field.iti__tel-input.${countryId}`)
                .siblings('.iti__country-container')
                .find('button .iti__a11y-text')[0];
    
                // let countrySelected = this.$element.find('#form-field-' + countryId).val();
                let countrySelected = countryFieldText ? countryFieldText.innerHTML : this.$element.find('#form-field-' + countryId).val();
        
                countrySelected = countrySelected !== "No country selected" ? countrySelected : "";

                countrySelected = (countrySelected !== '' && countrySelected !== undefined) ? countrySelected.split(" +")[0] : '';

                if (countrySelected) {
                    let selectedCountry = window.sfef_states.find(
                        country => country.name.toLowerCase() === countrySelected.toLowerCase()
                    );

                    if (selectedCountry) {
                        stateInput.val("");
                        stateInput.attr("placeholder", "");
                        stateInput[0].style.pointerEvents = "auto";
                        stateInput.closest('.cool-form__field-group').find('.sfef-custom-dropdown').remove();
                        let states = selectedCountry.states;
                        // Create the custom dropdown structure                        
                        let dropdownHtml = `<ul class="sfef-custom-dropdown">`;
                        states.forEach(state => {
                            dropdownHtml += `<li data-value="${state.name}">${state.name}</li>`;
                        });
                        dropdownHtml += `</ul>`;
        
                        // Append the dropdown options list to the input field
                        if(stateLabel.length > 0){
                            stateLabel.after(dropdownHtml);
                        }else{
                            stateInput.after(dropdownHtml);
                        }
                        
                        const dropdown = stateInput.closest('.cool-form__field-group').find('.sfef-custom-dropdown');
        
                        // Show/hide dropdown on input focus
                        stateInput.on('focus click', function () {
                            dropdown.show();
                        });
        
                        // Insert the selected value into the input field and hide the dropdown
                        dropdown.on('click', 'li', function () {
                            const selectedValue = jQuery(this).data('value');
                            stateInput.val(selectedValue); // Update the input field's value
                            dropdown.hide(); // Hide the dropdown after selection
                        });
        
                        // Close the dropdown if clicked outside
                        jQuery(document).on('click', function (e) {
                            if (!stateInput.is(e.target) && !dropdown.is(e.target) && dropdown.has(e.target).length === 0) {
                                dropdown.hide();
                            }
                        });
                    } else {
                    
                    }
                } else {
                        stateInput.attr("placeholder", "Select a country");
                        stateInput[0].style.pointerEvents = "none";
                }
            }
        });
    }
    
    onInputChange(){
        let body = this.elements.$intlSpanElement.closest('body');
        jQuery(body).on('input change click',".cool-form__field-group.is-field-type-country input, .cool-form__field-group.is-field-type-country ul li", () => {
            this.getIntlUserData();
        });

        body.find('.cool-form__field-group.is-field-type-country input').trigger('change');
        body.find('.cool-form__field-group.is-field-type-country input').trigger('input');
        // Direct binding for the blur event
        jQuery(".cool-form__field-group.is-field-type-country input").on('blur', () => {
            this.getIntlUserData();
        });
    }

    onDocumentloaded(){
        jQuery(document).ready(() => {
            this.getIntlUserData();
        });
    }
}

  jQuery(window).on('elementor/frontend/init', () => {
    const addHandler = ($element) => {
  
        elementorFrontend.elementsHandler.addHandler(CoolFormSTFEF, {
            $element,
        });
    };
  
    elementorFrontend.hooks.addAction('frontend/element_ready/cool-form.default', addHandler);

  });
  
  