class CoolFormCal extends elementorModules.frontend.handlers.Base {

    getDefaultSettings() {
        return {
            selectors: {
                calInput: '.coolform-calculator',
                calDiv: '.is-field-type-calculator',
                form: '.cool-form'
            },
        };
    }

    getDefaultElements() {
        const selectors = this.getSettings('selectors');
        return {
            $calInput: this.$element.find(selectors.calInput),
            $calDiv: this.$element.find(selectors.calDiv),
            $form: this.$element.find(selectors.form),
        };
    }

    bindEvents() {
        this.handleFieldLabel()
        this.onInputChange();
        this.updateCalculator(this.elements.$form)
   
    }

    updateCalculator($form) {
        $form.find('.coolform-calculator').each((index, element) => { 
            const $calculator = jQuery(element);
            const $calculatorWrapper = $calculator.closest('.is-field-type-calculator').find('.cfkef-calculator-wrapper')
            const wrapperOutputBox = $calculatorWrapper.find('.cfkef-calculator-outputbox')
            const formula = $calculatorWrapper.data('calculation-formula');
            const beforeText = $calculatorWrapper.data('before-text');
            const afterText = $calculatorWrapper.data('after-text');
            const decimalSeperator = $calculatorWrapper.data('decimal-seperator');
            const thousandSeperator = $calculatorWrapper.data('thousand-seperator');
            const decimalCount = $calculatorWrapper.data('decimal-count');

            // Call calculateResult using the correct `this` context
            let result = this.calculateResult($form, formula, decimalSeperator);
            if (result === Infinity || result === -Infinity || isNaN(result) ) {
                result = " ";
            }else{
                let formattedResult = parseFloat(result).toFixed(decimalCount);
                formattedResult = parseFloat(formattedResult).toString();
                // Split the formatted result into integer and decimal parts
                let [integerPart, decimalPart] = formattedResult.split(".");
                integerPart = parseInt(integerPart).toLocaleString().replace(/,/g, thousandSeperator);
        
                // Join the integer and decimal parts with the specified decimal separator
                formattedResult = decimalPart ? `${integerPart}${decimalSeperator}${decimalPart}` : integerPart;
                const finalResult = beforeText + formattedResult + afterText;
        
                wrapperOutputBox.html('')
                $calculator.val(finalResult);
                let outputHTML = '';
                if (beforeText.trim() !== '') {
                    outputHTML += `<span class="before-text">${beforeText}</span>`;
                }
                outputHTML += `<span class="main-text">${formattedResult}</span>`;
                if (afterText.trim() !== '') {
                    outputHTML += `<span class="after-text">${afterText}</span>`;
                }
                wrapperOutputBox.append(outputHTML);
            }

        });
    }


    calculateResult(form, formula, decimalSeperator) {
        let result = formula;
        const self = this;
        let totalValue = 0;
        // Handle radio buttons
        form.find('input[type="radio"]:checked, select').each(function() {
            const fieldName = jQuery(this).attr('name');
            let fieldVal;
            if (fieldName) {                
                const fieldIdMatch = fieldName.match(/\[([^\]]+)\]/);
                if (fieldIdMatch) {
                    const fieldId = fieldIdMatch[1];
                    fieldVal = jQuery(this).val()
                    fieldVal = self.normalizeValueBasedOnLocale(fieldVal, decimalSeperator);  
                    const fieldValue = parseFloat(fieldVal) || 0;
                    result = result.replace(new RegExp('\\b' + fieldId + '\\b', 'g'), fieldValue);
                }
            }
        });

        // Handle checkbox 
        const checkboxNames = new Set();
        form.find('input[type="checkbox"]').each(function() {
            const fieldName = jQuery(this).attr('name');
            if (fieldName) {
                const fieldIdMatch = fieldName.match(/\[([^\]]+)\]/);
                if (fieldIdMatch) {
                    checkboxNames.add(fieldIdMatch[1]);
                }
            }
        });

        checkboxNames.forEach((fieldId) => {
            let totalValue = 0;
            form.find(`input[type="checkbox"][name*="[${fieldId}]"]:checked`).each(function() {
                let fieldVal = jQuery(this).val();
                fieldVal = self.normalizeValueBasedOnLocale(fieldVal, decimalSeperator);
                totalValue += parseFloat(fieldVal) || 0;
            });

            result = result.replace(new RegExp('\\b' + fieldId + '\\b', 'g'), totalValue);
        });
        
        // Handle other fields
        form.find('.cool-form__field,.coolform-rating-input').each(function() {
            if(jQuery(this).closest('.is-field-type-image_radio').length > 0){
                return
            }
            const fieldName = jQuery(this).attr('name');
            let fieldVal;
            if(jQuery(this).closest('.cool-form__field-group').hasClass('is-field-type-slider')){
                fieldVal = jQuery(this).val() === "" ? jQuery(this).data('from') : jQuery(this).val();
            }else{
                fieldVal = jQuery(this).val()
            }

            if (fieldName) {
                const fieldIdMatch = fieldName.match(/\[([^\]]+)\]/);
                if (fieldIdMatch) {
                    const fieldId = fieldIdMatch[1];
                    if (jQuery(this).hasClass('elementor-currency')) {
                        fieldVal = self.normalizeCurrencyValue(fieldVal);
                    } else {
                        fieldVal = self.normalizeNumericValue(fieldVal, decimalSeperator);
                    }
                    let fieldValue = parseFloat(fieldVal) || 0;
                    result = result.replace(new RegExp('\\b' + fieldId + '\\b', 'g'), fieldValue);
                }
            }
        });

        try {
            return eval(result);
        } catch (e) {
            return 0;
        }
    }

    normalizeCurrencyValue(value) {
        let v = String(value).trim();
        if (!v) return '';
        // Remove all cuxrrency symbols, letters, and spaces
        v = v.replace(/[^0-9.,\-]/g, '');
    
        // Count how many dots and commas
        const dotCount = (v.match(/\./g) || []).length;
        const commaCount = (v.match(/,/g) || []).length;
        // Case 1: Format like 100.000.000 => treat dots as thousand separators
        if (dotCount > 1 && commaCount === 0) {
            v = v.replace(/\./g, '');
        }
        // Case 2: Format like 100,000,000 => commas as thousand separators
        else if (commaCount > 1 && dotCount === 0) {
            v = v.replace(/,/g, '');
        }
        // Case 3: Format like 100,000.00 or 100.000,00 — decide based on last separator
        else if (dotCount === 1 && commaCount === 1) {
            const lastDot = v.lastIndexOf('.');
            const lastComma = v.lastIndexOf(',');
            if (lastComma > lastDot) {
                // Likely format: 100.000,00 → European style
                v = v.replace(/\./g, '');
                v = v.replace(/,/, '.');
            } else {
                // Likely format: 100,000.00 → US style
                v = v.replace(/,/g, '');
            }
        } else {
            // Default fallback: just remove group separators
            v = v.replace(/,/g, '').replace(/\./g, '.');
        }
    
        return v;
    }    

    normalizeValueBasedOnLocale(value, decimalSeperator) {
        value = String(value);
        if(decimalSeperator === ','){
            value = value.replace(/,/g, '.')
        }else{
            value = value.replace(/,/g, '');        
        }
        return value;
    }

    /**
     * Turn any formatted number (with currency symbol, thousands-grouping,
     * varied separators) into a JS-friendly numeric string.
     */
    normalizeNumericValue(value) {
        let v = String(value).trim();
        if (!v) return '';
    
        // 1. Remove spaces
        v = v.replace(/\s+/g, '');

        // 2. Find last dot & comma
        const lastDot   = v.lastIndexOf('.');
        const lastComma = v.lastIndexOf(',');
            // 3. Decide decimal separator
        const decSep = lastComma > lastDot ? ',' : '.';
        const grpSep = decSep === '.' ? ',' : '.';
    
        // 4. Strip out everything except digits, grpSep, decSep, minus
        const reAllowed = new RegExp(`[^0-9\\${decSep}\\${grpSep}\\-]`, 'g');
        v = v.replace(reAllowed, '');
    
        // 5. Remove all grouping separators
        const reGrp = new RegExp(`\\${grpSep}`, 'g');
        v = v.replace(reGrp, '');
    
        // 6. Replace decimal separator with dot
        if (decSep !== '.') {
        const reDec = new RegExp(`\\${decSep}`, 'g');
        v = v.replace(reDec, '.');
        }

        return v;
    }  


    onInputChange(){
        const self = this;
        // Input event
        jQuery(this.elements.$form).on('cfkef:styled_rc_change',function(e){
            let $this = e.detail.sourceElement
            const $form = jQuery($this).closest('.cool-form');
            setTimeout(()=>{
                self.updateCalculator($form);    
                const customEvent = new CustomEvent('cfkef:calculator_field_input', {
                    detail: {
                        form: $form.get(0), 
                        sourceElement: $this  
                    }
                });
                window.dispatchEvent(customEvent);
            },100) 
        })
        jQuery(this.elements.$form).on('input', '.cool-form__field, .coolform-rating-input ,input[type="radio"], input[type="checkbox"], select', function() {
            const $form = jQuery(this).closest('.cool-form');            
            setTimeout(()=>{
                self.updateCalculator($form);    
                
                const customEvent = new CustomEvent('cfkef:calculator_field_input', {
                    detail: {
                        form: $form.get(0), 
                        sourceElement: this  
                    }
                });
                window.dispatchEvent(customEvent);

            },100)
        });
    }

    handleFieldLabel(){
        jQuery(this.elements.$calDiv).each((index, calDiv) => {
            const $parent = jQuery(calDiv);
            const $label = $parent.find('label.cool-form__field-label');
            const $wrapper = $parent.find('.cfkef-calculator-wrapper');
            const $outputBox = $wrapper.find('.cfkef-calculator-outputbox');

            if ($label.length && $wrapper.length && $outputBox.length) {
                $label.detach().insertBefore($outputBox);
            }
        });
    }
}

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



