(function($) {
    "use strict";

    $(document).ready(function() {

        // Function to compare conditional values
        function checkFieldLogic(compareFieldValue, conditionOperation, compareValue) {

            conditionOperation = decodeHTMLEntities(conditionOperation);
            compareValue = decodeHTMLEntities(compareValue).trim();
            compareFieldValue = compareFieldValue.trim();

            var values = compareFieldValue.split(',');

            var matchFound = values.some(function(value) {
                return value.trim() === compareValue;
            });


            switch (conditionOperation) {
                case "==":
                    return matchFound && '' !== compareFieldValue;
                case "!=":
                    return !matchFound && compareFieldValue !== "";
                case "e":
                    return compareFieldValue == "";
                case "!e":
                    return compareFieldValue != "";
                case "c":
                    return compareFieldValue.includes(compareValue);
                case "!c":
                    return compareFieldValue != "" && !compareFieldValue.includes(compareValue);
                case "^":
                    return compareFieldValue.startsWith(compareValue);
                case "~":
                    return compareFieldValue.endsWith(compareValue);
                case ">":
                    return parseInt(compareFieldValue) > parseInt(compareValue);
                case "<":
                    return parseInt(compareFieldValue) < parseInt(compareValue);
                case ">=":
                    return parseInt(compareFieldValue) >= parseInt(compareValue);
                case "<=":
                    return parseInt(compareFieldValue) <= parseInt(compareValue);
                default:
                    return false;
            }
        }

        function decodeHTMLEntities(text) {
            var textArea = document.createElement('textarea');
            textArea.innerHTML = text;
            return textArea.value;
        }

        // Function to apply conditions to the submit button

        function applySubmitButtonConditions(logicData, form) {            
            $.each(logicData, function(logic_key, logic_value){

                var field = getFieldMainDivById(logic_key);
                
                var displayMode = logic_value.display_mode;
                var fireAction = logic_value.fire_action;
                var logicConditions = logic_value.logic_data;
                var conditionPassFail = [];

                $.each(logicConditions, function(index, condition) {

                    var dependent_fi = $(".is-field-group-" + condition.cfef_logic_field_id, form);
                    var hiddenDiv = dependent_fi[0];
                    var	is_field_hidden = hiddenDiv ? hiddenDiv.classList.contains('cfef-hidden') : hiddenDiv;

                    if(condition.cfef_logic_field_id)
                            {
                                    if(form.find(`#form-field-${condition.cfef_logic_field_id}`).attr('type') === 'slider'){
                                        setTimeout(()=>{
                                            handleFieldValueDetection();
                                            handleMainLogic();
                                        },100)
                                    }else{
                                        handleFieldValueDetection();
                                        handleMainLogic();
                                    }

                                    function handleFieldValueDetection(){
                                        var value_id = getFieldEnteredValue(condition.cfef_logic_field_id, form);
                                        
                                        var value = is_field_hidden ? false : checkFieldLogic(value_id, condition.cfef_logic_field_is, condition.cfef_logic_compare_value);
                                        conditionPassFail.push(value);
                                    }

                            }

                });

                function handleMainLogic(){
                    var conditionResult = fireAction == "All" ? conditionPassFail.every(function(fvalue) { return fvalue === true; }) : conditionPassFail.some(function(fvalue) { return fvalue === true; });

                    if(field !== undefined && field.length > 0){
                        if (displayMode== "show") {
                            if (conditionResult) {
                                field.removeClass("cfef-hidden");
                            } else {
                                field.addClass("cfef-hidden");
                            }
                        } else if (displayMode == "hide") {
                            if (conditionResult) {
                                field.addClass("cfef-hidden");
                            } else {
                                field.removeClass("cfef-hidden");
                            }
                        } else if (displayMode== "enable") {
                            if (conditionResult) {
                                field.find('button').attr('disabled',false).css({"pointer-events": "unset", "opacity": "1.0"})
                                field[0].onclick = ()=>{
                                    field.find('button').attr('disabled',false).css({"pointer-events": "unset", "opacity": "1.0"})
                                }
                            } else {
    
                                field.find('button').attr('disabled','disabled').css({"pointer-events": "none", "opacity": "0.3"})
                                field[0].onclick = ()=>{
                                    field.find('button').attr('disabled','disabled').css({"pointer-events": "none", "opacity": "0.3"})
                                }
                            }
                        } else if(displayMode== "disable") {
                            if (conditionResult) {
                                    field.find('button').attr('disabled','disabled').css({"pointer-events": "none", "opacity": "0.3"})
                                    field[0].onclick = ()=>{
                                        field.find('button').attr('disabled','disabled').css({"pointer-events": "none", "opacity": "0.3"})
                                    }
                                } else {
                                    field.find('button').attr('disabled',false).css({"pointer-events": "unset", "opacity": "1.0"})
                                    field[0].onclick = ()=>{
                                        field.find('button').attr('disabled',false).css({"pointer-events": "unset", "opacity": "1.0"})
                                    }
        
                                }                  
                        }
                    }
                }
            })
        }
        
        
        function getFieldEnteredValue(id = "", form = "body") {
            var inputValue = "";
            if ($(".is-field-group-" + id).hasClass("is-field-type-radio")) {
                inputValue = $(".is-field-group-" + id + " input:checked", form).val();
            } else if ($(".is-field-group-" + id).hasClass("is-field-type-checkbox")) {
                if ($(".is-field-group-" + id).hasClass("is-field-type-checkbox")) {
                    var data = [];
                    
                    // Check if any checkbox is checked
                    if ($(".is-field-group-" + id + " input[type='checkbox']:checked").length > 0) {
                        // Collect values of checked checkboxes
                        $(".is-field-group-" + id + " input[type='checkbox']:checked").each(function() {
                            data.push($(this).val());
                        });
                        inputValue = data.join(", ");
                    } else {
                        // No checkbox is checked
                        inputValue = "";
                    }
                }
                
            } else if ($(".is-field-group-" + id).hasClass("is-field-type-select")) {
                inputValue = $(".is-field-group-" + id + " select", form).val();
                if(Array.isArray(inputValue)){
                    inputValue= inputValue.join(',');
                }
            } else if ($(".is-field-group-" + id).hasClass("is-field-type-textarea")) {
                inputValue = $(".is-field-group-" + id + " textarea", form).val();
            } else if($(".is-field-group-" + id).hasClass("is-field-type-tel")) {
                inputValue = $(".is-field-group-" + id).find(`#form-field-${id}`).val()
            } else if($(".is-field-group-" + id).hasClass("is-field-type-slider")){
                inputValue = $(".is-field-group-" + id).find('input').val()
            } else if($(".is-field-group-" + id).hasClass("is-field-type-acceptance")){
                let checkStatus = $(".is-field-group-" + id).find('input').is(':checked')
                inputValue = checkStatus ? 'on' : '';
            } else if($(".is-field-group-" + id).hasClass("is-field-type-toggle")){
                inputValue = $(".is-field-group-" + id).find('input.cfkef-switch-Input').val()
            }else {
                inputValue = $(".is-field-group-" + id + " input", form).val();
            }
            if (inputValue === undefined) {
                return '';
            } else {
                return inputValue;
            }
        }

        function getFieldMainDivById(id = "") {
            if(id !== ""){
                return $("button#" + id).closest(".cool-form__submit-group")
            }
        }

        // Call the function to apply conditions to the submit button when the document is ready
        $(document).ready(function() {
            $(".cool-form").each(function() {
                var form = $(this).closest(".elementor-widget-cool-form");
                var logicData = $(".cfef_logic_data_submit_button_js", form).text();
                if (logicData && logicData !== "undefined") {
                    try {
                        logicData = jQuery.parseJSON(logicData);
                        applySubmitButtonConditions(logicData, form);
                    } catch (e) {
                        console.error("Error parsing JSON:", e);    
                    }
                } else {
                    // console.warn("JSON data is empty or undefined");
                }
            });
        });

        $("body").on("MDCSelect:change", ".cool-form .mdc-select", function (e) {
            var form = $(this).closest(".elementor-widget-cool-form");
            var logicData = $(".cfef_logic_data_submit_button_js", form).text();

            if (logicData && logicData !== "undefined") {
                try {
                    logicData = jQuery.parseJSON(logicData);
                    applySubmitButtonConditions(logicData, form);
                } catch (e) {
                    console.error("Error parsing JSON:", e);
                }
            }
        });

        // Event listener for changes in the form
        $("body").on("input change", ".cool-form", function(e) {
            var form = $(this).closest(".elementor-widget-cool-form");
            var logicData = $(".cfef_logic_data_submit_button_js", form).text();

            if (logicData && logicData !== "undefined") {
                try {
                    logicData = jQuery.parseJSON(logicData);
                    applySubmitButtonConditions(logicData, form);
                } catch (e) {
                    console.error("Error parsing JSON:", e);
                }
            } else {
                // console.warn("JSON data is empty or undefined");
            }
        });

        // Prevent Elementor form submission when hitting Enter if the submit button is hidden
        jQuery(document).on("keydown", ".cool-form input, .cool-form textarea", function (e) {
            if (e.key === "Enter" || e.keyCode === 13) {
                var $form = jQuery(this).closest(".cool-form");                
                if ($form.find(".elementor-field-type-submit").hasClass("cfef-hidden")) {
                    e.preventDefault(); 
                    e.stopImmediatePropagation(); 
                    return false;
                }
            }
        });

        jQuery(document).on('submit_success', function(e, data) {
            setTimeout(()=>{
                $(".cool-form").each(function() {
                    var form = $(this).closest(".elementor-widget-cool-form");
                    var logicData = $(".cfef_logic_data_submit_button_js", form).text();
                    if (logicData && logicData !== "undefined") {
                        try {
                            logicData = jQuery.parseJSON(logicData);
                            applySubmitButtonConditions(logicData, form);
                        } catch (e) {
                            console.error("Error parsing JSON:", e);
                        }
                    } else {
                        // console.warn("JSON data is empty or undefined");
                    }
                });
            },200)
        });

    });

})(jQuery);
