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

    /**
     * Retrieves the default DATE_SETTINGS field functionality.
     * @returns {Object} An object containing DATE_SETTINGSor configurations.
     */
    getDefaultSettings() {
        return {
            selectors: {
                monthElement: '.is-field-type-monthWeek .elementor-month',
                weekElement: '.is-field-type-monthWeek .elementor-week',
            },
        };
    }  

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

    /**
     * Binds events to the elements. This method is intended to be overridden by subclasses to add specific event handlers.
     */
    bindEvents() {
        this.initialise();
    }
    /**
     * Retrieves and stores unique DATE_SETTINGS input IDs from the Elementor div element.
     */
    initialise(){
        const divWrapper = this.elements.$monthElement;
        const divWrapperWeek = this.elements.$weekElement;
        const divEditorObject = jQuery(divWrapper);
        const divEditorObjectWeek = jQuery(divWrapperWeek);

        divEditorObject.each((index, element) => { 
            let minDate = jQuery(element).attr('data-min');
            let maxDate = jQuery(element).attr('data-max');
            let defaultVal = jQuery(element).attr('data-default');
            this.addFlatpickerMonth(element, minDate, maxDate);
        });

        divEditorObjectWeek.each((index, element) => { 
            let minDate = jQuery(element).attr('data-min');
            let maxDate = jQuery(element).attr('data-max');
            let defaultVal = jQuery(element).attr('data-default');
            this.addFlatpickerWeek(element, minDate, maxDate)
        });
    }

    addFlatpickerMonth(element, minDate, maxDate){
        flatpickr(element, {
            enableTime: false,
            minDate: minDate || null,
            maxDate: maxDate || null,
            dateFormat: "F Y", // Format for Year-Month
            plugins: [
                new monthSelectPlugin({
                    shorthand: true, // Display short month names (e.g., "Jan", "Feb")
                    dateFormat: "F Y", // Format for the input value
                    altFormat: "F Y" // Displayed format (e.g., "January 2025")
                })
            ],
            onChange: (selectedDates, dateStr, instance) => {
                // this.formatMonth(element); 
            },
            disableMobile: true, // Ensures the custom UI is used on mobile
        });
    }

    addFlatpickerWeek(element, minDate, maxDate) {        
        flatpickr(element, {
            enableTime: false,
            minDate: minDate || null,
            maxDate: maxDate || null,
            dateFormat: "Week W, Y", // Internal value format (Year-Week)
            // altInput: true, // Enables alternative display
            altFormat: "Week W, Y", // Displayed format (e.g., "Week 4, 2025")
            weekNumbers: true,
            plugins: [
                new weekSelectPlugin({
                    dateFormat: "Week W, Y", // Format for the input value (Year-Week)
                    altFormat: "Week W, Y" // Displayed format (e.g., "Week 4, 2025")
                })
            ],
                onChange: (selectedDates, dateStr, instance) => {
                    this.formatWeek(instance);
            },
                onReady: (selectedDates, dateStr, instance) => {
                    this.formatWeek(instance);
            },
            disableMobile: true // Ensures the custom UI is used on mobile
        });
    }

    formatWeek(instance) {
        // Correct the altInput (visible value)
        const altInputValue = instance.altInput?.value || ""; // Get altInput value
        if (altInputValue.includes("eek")) { // Check if there's an error
            const correctedAltValue = altInputValue.replace(/^\d+eek/, 'Week'); // Correct "4eek" to "Week"
            instance.altInput.value = correctedAltValue;
        }
        // Correct the value (hidden/internal value)
        const inputValue = instance.input?.value || ""; // Get internal value
        if (inputValue.includes("eek")) {
            const correctedValue = inputValue.replace(/^\d+eek/, 'Week'); // Correct "4eek" to "Week"
            instance.input.value = correctedValue; // Update the input value
        }
    }

}   

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

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

