
class Cfkef_Currency extends elementorModules.frontend.handlers.Base {

    getDefaultSettings() {
        return {
            selectors: {
                editorSpan: 'span.cfkef-editor-currency',
                form: '.elementor-form'
            },
        };
    }

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

    bindEvents() {
        this.addRepeaterClass()
        this.onInputChange();
        this.updateCurrency(this.elements.$form)
    }

    updateCurrency($form) { 
        $form.find('.elementor-currency').each((index, element) => { 
            const $currencyObject = jQuery(element);
             // currencies with period as thousand seperator and comma as decimal seperator
            const euroFormat = ["$", "R$", "Kč", "kr", "kn", "Ft", "ƒ1", "₪", "zł", "CHF", "₫" ,"$9" ,"$10", "₡", "₱ 1", "RD$" ,"Rp", "C$" , "₦" ,"kr2", "﷼5", "Gs", "S/.", "₱", "﷼0", "lei", "﷼1", "$22", "₺" , "$U", "Bs", "3﷼",  ];
            const indiaFormat = ["₨"];
            // currencies with space ( ) as thousand seperator and comma(,) as decimal seperator
            const currencySet1 = ["₼", "Br", "лв6", "₽", "kr3", "₴", "лв3"];
            // currencies with space ( ) as thousand seperator and period(.) as decimal seperator
            const currencySet2 = ["лв1", "₩" ];

            let currencySelectedRaw;
            let currencySelected;
            let decimalCount;     
            if($currencyObject.data('currency-selected') !== undefined){
                currencySelectedRaw = $currencyObject.data('currency-selected');
                currencySelected = currencySelectedRaw.replace(/[0-9]/g, '');
                decimalCount = $currencyObject.data('deci-upto');
                decimalCount = parseFloat(decimalCount);
            }else{
                let spanObject =  this.elements.$editorSpan;
                currencySelectedRaw = spanObject.attr('data-currency-selected');
                currencySelected = currencySelectedRaw.replace(/[0-9]/g, '');
                decimalCount = spanObject.attr('data-deci-upto');
                decimalCount = parseFloat(decimalCount);
            }
            
            let value = $currencyObject.val();
            value = value.replace(/^[^0-9-]+/g, ''); 
            if (value.startsWith('-')) {
                    // Remove all other minus signs from the string
                value = '-' + value.replace(/-/g, ''); // Keep the leading minus and remove others
            } else {
                // If there's no leading minus, just remove all minus signs
                value = value.replace(/-/g, '');
            }

            if(value.startsWith("-")){  
                if (euroFormat.includes(currencySelectedRaw) || currencySet1.includes(currencySelectedRaw)) {
                value = value.replace(/[^0-9,.]/g, ''); // Allow only digits, comma, and minus/decimal points
                value = value.replace(/\./g, ''); // Remove all dots
                let finalValue = this.applyDecimalSeperator(value,currencySelected,decimalCount,currencySet1,currencySelectedRaw)

                if(finalValue === currencySelected){
                    $currencyObject.val(`${currencySelected}`);
                }else{
                    $currencyObject.val(`-${finalValue}`);
                }
               }else{
                value = value.replace(/[^0-9.-]/g, ''); // Allow digits and decimal point
                value = value.substring(1);           
                if(value !== ""){
                 let numericValue = parseFloat(value);
                 let finalValue = this.applyCommaSeperator(value,currencySelected,decimalCount,indiaFormat,currencySet2,currencySelectedRaw);
                 $currencyObject.val(`-${finalValue}`);
               }else{
                $currencyObject.val(`-${currencySelected}`);
                }
               }
            }else{
                if (euroFormat.includes(currencySelectedRaw) || currencySet1.includes(currencySelectedRaw)) { 
                    // Remove the currency symbol
                    value = value.replace(/[^0-9,.-]/g, ''); // Allow only digits, comma, and minus/decimal points
                    value = value.replace(/\./g, ''); // Remove all dots
                    let finalValue = this.applyDecimalSeperator(value,currencySelected,decimalCount,currencySet1,currencySelectedRaw)
                    $currencyObject.val(finalValue);  
                }else{
                    value = value.replace(/[^0-9.-]/g, ''); // Allow digits and decimal point
                    let finalValue = this.applyCommaSeperator(value,currencySelected,decimalCount,indiaFormat,currencySet2,currencySelectedRaw)
                    $currencyObject.val(finalValue);  
                }
            }
        });
    }

    applyDecimalSeperator(value,currencySelected,decimalCount,currencySet1,currencySelectedRaw){
        let match = value.match(/^(-?\d+)([.,]\d*)?$/);
            // Extract the integer and decimal parts
            let formattedInteger; 
            let integerPart = match ? match[1] : value; 
            let decimalPart = match && match[2] ? match[2] : '';
            if (decimalPart) {
                decimalPart = ',' + decimalPart.slice(1, (decimalCount + 1));
            }
            // Example Formatting
             if(currencySet1.includes(currencySelectedRaw)){
                    formattedInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
                }else{
                    formattedInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, "."); 
                }

            let formattedNumber = formattedInteger + decimalPart;
            formattedNumber = `${currencySelected} ${formattedNumber}`;
            return formattedNumber;
    }

    // apply comma(,) as thousand seperator 
    applyCommaSeperator(value,currencySelected,decimalCount,indiaFormat,currencySet2,currencySelectedRaw){
            let match = value.match(/^(-?\d+)(\.\d*)?$/);
            // Extract the integer and decimal parts
            let integerPart = match ? match[1] : value; 
            let decimalPart = match && match[2] ? match[2] : '';
            if (decimalPart) {
                    decimalPart = '.' + decimalPart.slice(1, (decimalCount + 1));
                }
            if (indiaFormat.includes(currencySelected)) {
                let formattedInteger = integerPart.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
                let parts = formattedInteger.split(',');
                // Part 1: Everything before the last comma
                let part1 = parts.slice(0, parts.length - 1).join(',');
                part1 = part1.replace(/\,/g, ''); // Remove all commas
                part1 = part1.replace(/\B(?=(\d{2})+(?!\d))/g, ",");
                part1 = part1.replace(/\B(?=(\d{2})+(?!\d))/g, ",");   
                if(part1){
                    part1 = part1 + "," ;
                }
                // Part 2: The last portion after the last comma
                let part2 = parts[parts.length - 1];
                let formattedNumber = part1 + part2 +decimalPart;
                formattedNumber = `${currencySelected} ${formattedNumber}`;
                return formattedNumber;
             }else{
                let formattedInteger;
                if(currencySet2.includes(currencySelectedRaw)){
                    formattedInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
                }else{
                    formattedInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ",");  
                }
    
                let formattedNumber = formattedInteger + decimalPart;
                // Add dollar sign to the formatted number
                formattedNumber = `${currencySelected} ${formattedNumber}`;
                return formattedNumber;
             }

           
    }

    onInputChange(){
        const self = this;
         // Input event
        jQuery(this.elements.$form).on('input', function(e) {
            const $form = jQuery(this).closest('.elementor-form');
            self.updateCurrency($form);    
        }); 

        // remove the (-) minus sign from the start when there is not input value
        jQuery(this.elements.$form).on('keydown', function(e) {
            const $form = jQuery(this).closest('.elementor-form');
               // Check if the Backspace key is pressed
                if (e.key === "Backspace") {
                    setTimeout(() => {
                        let value = jQuery(e.target).val()
                        if (!/[0-9]/.test(value)) {
                            value = value.replace(/-/g, ''); 
                            jQuery(e.target).val(value)
                        }
                    }, 0);                    
                }
            self.updateCurrency($form);    
        }); 
    }

    addRepeaterClass(){
        jQuery(this.elements.$calInput).each((index, input) => { 
        const repeaterId = input.className.match(/elementor-repeater-item-([\w-]+)/);

        if (repeaterId) {
            const parent = input.closest('.elementor-field-type-currency'); 
            if (parent) {
                parent.classList.add('elementor-repeater-item-' + repeaterId[1]);
            }
        }
    })
}
}
      
jQuery(window).on('elementor/frontend/init', () => {
    const currencyHandler = ($element) => {
        elementorFrontend.elementsHandler.addHandler(Cfkef_Currency, {
            $element,
        });
    };
  
    elementorFrontend.hooks.addAction('frontend/element_ready/form.default', currencyHandler);
  }); 



