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

    /**
     * Retrieves the default select field functionality.
     * @returns {Object} An object containing selector configurations.
     */
    getDefaultSettings() {
        return {
            selectors: {
                selectElement: '.is-field-type-select',
                divWrapper: '.select_data_js',
                submitDiv:'.cool-form__submit-group button',
                form:'form',
            },
        };
    }

    /**
     * Retrieves the default elements based on the settings defined.
     * @returns {Object} An object containing jQuery elements for the select field.
     */
    getDefaultElements() {
        const selectors = this.getSettings('selectors');
        return {
            $selectElement: this.$element.find(selectors.selectElement),
            $divWrapper: this.$element.find(selectors.divWrapper),
            $submitDiv: this.$element.find(selectors.submitDiv),
        };
    }  

    /**
     * Binds events to the elements. This method is intended to be overridden by subclasses to add specific event handlers.
     */
    bindEvents() {
        
        this.fieldIds = []; // to store unique Ids
        this.select2Controls = {}; // to store data in object format respective unique id
        this.getUserData(); // retrieve user-data from the element
        this.appendSelect2();  // function to append select2
        this.onSubmit(this.elements.$submitDiv, this.elements.$divWrapper); // reset the default option after submit
        this.borderColor = ""; 
        this.borderWidth = ""; 
        this.borderUnit = ""; 
    }

    /**
     * Retrieves and stores unique select input IDs from the Elementor div element.
     */
    getUserData(){
        const divWrapperElement = this.elements.$divWrapper;
        const divEditorObject = jQuery(divWrapperElement);
        divEditorObject.each((index, element) => { 
            const $element = jQuery(element);
            const classes = $element.attr('class').split(' ');
            const cfefClasses = classes.filter(cls => cls.startsWith('cfef'));
            let uniqueId;
            const select2Controls = {};   
            cfefClasses.forEach(cls => {
                const [key, value] = cls.replace('cfef', '').split('_', 2);
                if (key === 'uniqueId') {
                    uniqueId = value;

                    $element.closest('.cool-form__field-group').addClass(`cool-form__field-group-${uniqueId}`);
                    this.fieldIds.push(uniqueId);
                    if (!this.select2Controls[uniqueId]) {
                        this.select2Controls[uniqueId] = {};
                    }
                } else {           
                    this.select2Controls[uniqueId][key] = value;
                }
            });  
        });
    }

        /**
         * Appends a handler to each select input field to manage functionality.
         */
        appendSelect2() {
            this.fieldIds.forEach(uniqueId => {
                const select2Controls = this.select2Controls[uniqueId];

                // Locate the field group by customId or fallback to uniqueId
                let fieldtarget = this.$element.find(`.cool-form__field-group-${select2Controls.customId}`);
                if (fieldtarget.length === 0) {
                    fieldtarget = this.$element.find(`.cool-form__field-group-${uniqueId}`);
                }
                fieldtarget.addClass(`elementor-repeater-item-${uniqueId}`);

                const mdcContainer = fieldtarget.find('.mdc-select');
                if (!mdcContainer.length) return;

                if (mdcContainer.hasClass('select2-replaced')) return;

                const placehldr = select2Controls.placeholder ? select2Controls.placeholder.replace(/-/g, ' ') : '';
                const selectFieldControl = select2Controls.selectFieldControl;
                const multiSelect = (select2Controls.multiSelect === 'true');
                const multiSelectLimit = parseInt(select2Controls.multiSelectLimit) || 0;
                const customClass = multiSelect ? "multipleClass" : "singleClass";

                if (selectFieldControl !== "yes") return;

                // Get all MDC options from .mdc-list-item
                const mdcOptions = mdcContainer.find('.mdc-list-item');
                if (mdcOptions.length < 0) return;

                // Create a clean <select>
                const builtSelect = jQuery('<select>', {
                    name: mdcContainer.data('name') || `form_fields[${select2Controls.customId}]`,
                    id: `form-field-${select2Controls.customId}`,
                });

                // Populate <select> with real <option> elements
                mdcOptions.each(function () {
                    const $item = jQuery(this);
                    const value = $item.data('value') || '';
                    const label = $item.text().trim();
                    const isSelected = $item.attr('aria-selected') === 'true';

                    const $option = jQuery('<option>', {
                        value: value,
                        text: label,
                        selected: isSelected,
                    });

                    builtSelect.append($option);
                });

                // Mark MDC container so it's not re-initialized
                mdcContainer.addClass('select2-replaced');

                // Hide MDC container and append real <select>
                mdcContainer.hide();
                mdcContainer.after(builtSelect);

                // Destroy MDC instance if already attached
                try {
                    const mdcInstance = mdc.select.MDCSelect?.instances?.get?.(mdcContainer[0]);
                    if (mdcInstance) {
                        mdcInstance.destroy();
                    }
                } catch (e) {
                    console.warn('MDC destroy failed or skipped:', e);
                }

                // Initialize Select2 on the new <select>
                builtSelect.select2({
                    width: 'resolve',
                    multiple: multiSelect,
                    maximumSelectionLength: multiSelectLimit,
                    placeholder: placehldr,
                    allowClear: true,
                    selectOnClose: false,
                    tokenSeparators: [',', ' '],
                    dropdownCssClass: customClass,
                    dropdownParent: fieldtarget,
                    dropdownAutoWidth: true,
                });

                // Optional custom border styling
                const borderColor = select2Controls.borderColor || '';
                const borderWidth = select2Controls.borderWidth || '';
                const borderUnit = select2Controls.borderUnit || '';
                const select2Input = fieldtarget.find('.select2-selection');

                if (borderColor && borderWidth && borderUnit) {
                    select2Input.css("border", `${borderWidth}${borderUnit} solid ${borderColor}`);
                }
            });
        }


        /**
         * After submit, reset the default option values in each select2 field.
         */
        onSubmit(submit, select2) {
            if (submit[0]) {
                const form = submit.closest('form'); 
                if (form.length > 0) {
                    form.on('submit', (e) => {
                        // Delay the reset to happen AFTER the form is submitted
                        setTimeout(() => {
                            this.resetSelect2Fields(select2);
                        }, 0); // Executes right after the form submission process
                    });
                } else {
                    console.error('Form element not found.');
                }
            } else {
                console.error('submit[0] is undefined or not an element');
            }
        }
    
        /**
         * Function to reset Select2 fields
         */
        resetSelect2Fields(select2) {
            // Reset single select fields
            select2.find('.select2-container--default .selection .select2-selection--single .select2-selection__rendered').each(function () {
                const select2Container = jQuery(this);
                const parentContainer = select2Container.closest('.select2-container--default');
                const selectDropdown = parentContainer.prev('select');
                if (selectDropdown.length > 0) {
                    const defaultOption = selectDropdown.find('option[selected="selected"]');
                    const optionText = defaultOption.length > 0 ? defaultOption[0].innerHTML : selectDropdown.find('option').first()[0].innerHTML;
                    select2Container[0].innerHTML = optionText;
                }
            });
        
            // Reset multiple select fields
            select2.find('.select2-container--default .selection .select2-selection--multiple .select2-selection__rendered').each(function () {
                const select2ContainerMulti = jQuery(this);
                const parentContainer = select2ContainerMulti.closest('.select2-container--default');
                const selectDropdown = parentContainer.prev('select');
                if (selectDropdown.length > 0) {
                    const defaultOptions = selectDropdown.find('option[selected="selected"]');
                    if (defaultOptions.length > 0) {
                        const values = defaultOptions.map(function () {
                            return this.value;
                        }).get();
                        selectDropdown.val(values).trigger('change'); 
                    } else {
                        select2ContainerMulti.empty();
                    }
                }
            });
        } 
    }

jQuery(window).on('elementor/frontend/init', () => {
    const addHandler = ($element) => {
        elementorFrontend.elementsHandler.addHandler(CoolForm_SELECT2, {
            $element,
        });
    };

    elementorFrontend.hooks.addAction('frontend/element_ready/cool-form.default', addHandler);
});
