document.addEventListener('DOMContentLoaded', function () {
    
    document.addEventListener('click', function (event) {
        const target = event.target;
        var $ = jQuery;
        // Handling the click on the deactivate link
        if (target.matches('[data-plugin="' + multicollabPluginDeactivation.plugin_path + '"] span.deactivate a')) {
            const snooze_free_deactivate_popup = getCookieName("snooze_free_deactivate_popup");
            if ('yes' !== snooze_free_deactivate_popup) {
                const radioButtons = document.querySelectorAll('.cf-plugin-deacmodal__body-form input[type="radio"]');
                // Loop through each radio button and uncheck it
                radioButtons.forEach(radio => {
                    radio.checked = false;
                });

                document.getElementById('cf-plugin-deacmodal')?.classList.add('cf-plugin-deacmodal', 'cf_visible');
                document.querySelector('.cf-plugin-deacmodal__inner .cf-plugin-deacmodal__footer').style.display = 'block';
                const freeFooter = document.querySelector('.cf-plugin-deacmodal__inner .cf-plugin-deacmodal__footer.cf_free')
                if(freeFooter){
                    freeFooter.style.display = 'none';
                }
                event.preventDefault();
            }
        }

        // Handling radio button changes in step 1
        if (target.matches('#step-1 input[type=radio][name=fs_deactive_free_plugin_step1]')) {
            const value = target.value;
            if (value === 'yes') {
                document.querySelector('.cf-plugin-deacmodal__inner #step-1').style.display = 'none';
                document.querySelector('.cf-plugin-deacmodal__inner #step-3').style.display = 'block';

                document.querySelector('.cf-plugin-deacmodal__inner .cf-plugin-deacmodal__footer').style.display = 'none';
                document.querySelector('.cf-plugin-deacmodal__inner .cf-plugin-deacmodal__header .modal-title').innerHTML = 'How would you rate your overall experience with Multicollab?';
            } else if (value === 'no') {
                document.querySelector('.cf-plugin-deacmodal__inner #step-1').style.display = 'none';
                document.querySelector('.cf-plugin-deacmodal__inner #step-2').style.display = 'block';
                document.querySelector('.cf-plugin-deacmodal__inner .cf-plugin-deacmodal__footer').style.display = 'block';
                document.querySelector('.cf-plugin-deacmodal__inner .cf-plugin-deacmodal__header .modal-title').innerHTML = 'What was the primary reason for deactivating Multicollab?';
            }
        }

        // Handling cancel button click
        if (target.matches('.cf-plugin-deacmodal__footer .btn-cancel')) {
            document.getElementById('cf-plugin-deacmodal').classList.remove('cf_visible');
            document.querySelectorAll('input[name="fs_deactive_free_plugin"]:checked').forEach(input => input.checked = false);
            const snoozeCheckbox = document.getElementById('snooze_option_checkbox');
            if (snoozeCheckbox) snoozeCheckbox.checked = false;
            let cfSnoozeOption = document.querySelector('.cf-plugin-deacmodal__footer-snooze-option');
            let cfSnoozePeriod = document.querySelector('.cf-plugin-deacmodal__footer-snooze-period');
            if (cfSnoozeOption) {
                cfSnoozeOption.style.display = 'none';
            }
            if (cfSnoozePeriod) {
                cfSnoozePeriod.style.display = 'none';
            }
            const primaryButton = document.querySelector('.cf-plugin-deacmodal__footer .btn-primary');
            primaryButton.classList.remove('btn-active');
            primaryButton.innerText = 'Submit & Deactivate';

            let cfDeacmodal1 = document.querySelector('.cf-plugin-deacmodal__inner #step-1');
            let cfDeacmodal2 = document.querySelector('.cf-plugin-deacmodal__inner #step-2');
            let cfDeacmodal3 = document.querySelector('.cf-plugin-deacmodal__inner #step-3');
            let cfDeacmodalFooter = document.querySelector('.cf-plugin-deacmodal__inner .cf-plugin-deacmodal__footer');
            if (cfDeacmodal1) {
                cfDeacmodal1.style.display = 'block';
            }
            if (cfDeacmodal2) {
                cfDeacmodal2.style.display = 'none';
            }
            if (cfDeacmodal3) {
                cfDeacmodal3.style.display = 'none';
            }
            if (cfDeacmodalFooter) {
                cfDeacmodalFooter.style.display = 'none';
            }

            const radioButtons = document.querySelectorAll('.cf-plugin-deacmodal__inner input[type="radio"]');
            // Loop through each radio button and uncheck it
            radioButtons.forEach(radio => {
                radio.checked = false;
            });

            hideTextboxs( '.fs_feedback_message_1, .fs_feedback_message_2, .fs_feedback_message_3, .cf-deact-required-indicator' );
            
        }

        // Handling snooze option checkbox change
        if (target.matches('#snooze_option_checkbox')) {
            const snoozePeriod = document.querySelector('.cf-plugin-deacmodal__footer-snooze-period');
            const primaryButton = document.querySelector('.cf-plugin-deacmodal__footer .btn-primary');
            if (target.checked) {
                snoozePeriod.style.display = 'block';
                primaryButton.innerText = 'Snooze & Deactivate';
            } else {
                snoozePeriod.style.display = 'none';
                primaryButton.innerText = 'Submit & Deactivate';
            }
        }

        // Handling reason for deactivation change
        if (target.matches('input[name=fs_deactive_free_plugin]')) {

            const subscriptionOption = document.querySelector('input[name="fs_deactive_free_plugin"]:checked').value;

            // Clear and disable the feedback message input
            const feedbackMessage = document.querySelector('.feedback_message');
            feedbackMessage.value = '';
            feedbackMessage.disabled = true;

            // Show and hide feedback messages based on the selected option
            const fsFeedbackMessage1 = document.querySelector('.fs_feedback_message_1');
            const fsFeedbackMessage2 = document.querySelector('.fs_feedback_message_2');
            const fsFeedbackMessage3 = document.querySelector('.fs_feedback_message_3');

            if (subscriptionOption === 'Lack of essential features') {
                fsFeedbackMessage3.disabled = true;
                fsFeedbackMessage2.disabled = true;
                fsFeedbackMessage1.disabled = false;
                fsFeedbackMessage1.style.display = 'inline-block';
                fsFeedbackMessage2.style.display = 'none';
                fsFeedbackMessage3.style.display = 'none';
            } else if (subscriptionOption === 'Found a better plugin') {
                fsFeedbackMessage1.disabled = true;
                fsFeedbackMessage3.disabled = true;
                fsFeedbackMessage2.disabled = false;
                fsFeedbackMessage2.style.display = 'inline-block';
                fsFeedbackMessage1.style.display = 'none';
                fsFeedbackMessage3.style.display = 'none';
            } else if (subscriptionOption === 'Something else') {
                fsFeedbackMessage1.disabled = true;
                fsFeedbackMessage2.disabled = true;
                fsFeedbackMessage3.disabled = false;
                fsFeedbackMessage3.style.display = 'inline-block';
                fsFeedbackMessage1.style.display = 'none';
                fsFeedbackMessage2.style.display = 'none';
            } else {
                // Hide all feedback messages if no valid option is selected
                fsFeedbackMessage1.style.display = 'none';
                fsFeedbackMessage2.style.display = 'none';
                fsFeedbackMessage3.style.display = 'none';
                fsFeedbackMessage3.disabled = true;
                fsFeedbackMessage2.disabled = true;
                fsFeedbackMessage1.disabled = true;
                

                // Enable the button
                const primaryButton = document.querySelector('.cf-plugin-deacmodal__footer .btn-primary');
                primaryButton.classList.add('btn-active');
            }

            // Remove active class from the button for specific options
            if (['Lack of essential features', 'Found a better plugin', 'Something else'].includes(subscriptionOption)) {
                const primaryButton = document.querySelector('.cf-plugin-deacmodal__footer .btn-primary');
                primaryButton.classList.remove('btn-active');
            }


            if (subscriptionOption === "It's temporary deactivation - troubleshooting an issue") {
                document.querySelector('.cf-plugin-deacmodal__footer-snooze-option').style.display = 'block';
            } else {
                document.querySelector('.cf-plugin-deacmodal__footer-snooze-option').style.display = 'none';
            }
        }

        // Handling final step button click
        if (target.matches('.free_plugin_deactivate_step3')) {
            // Remove the 'active' class from all the spans
            document.querySelectorAll('.free_plugin_deactivate_step3').forEach((el) => {
                el.classList.remove('active');
            });
            // Add the 'active' class to the clicked span
            target.classList.add('active');

            const free_plugin_deactivate_step3 = target.getAttribute('data-value');
            if (free_plugin_deactivate_step3) {
                const settingsData = new FormData();
                const fs_deactive_free_plugin_step1 = document.querySelector('input[name="fs_deactive_free_plugin_step1"]:checked').value;
                
                if('no' === fs_deactive_free_plugin_step1){
                    const subscriptionOption = document.querySelector('input[name="fs_deactive_free_plugin"]:checked').value;
                    let fs_feedback_message = '';
                    if( 'Lack of essential features' === subscriptionOption ) {
                        fs_feedback_message = $('.fs_feedback_message_1').val();
                    } else if( "Found a better plugin" === subscriptionOption ) {
                        fs_feedback_message = $('.fs_feedback_message_2').val();
                    } else if( 'Something else' === subscriptionOption ) {
                        fs_feedback_message = $('.fs_feedback_message_3').val();
                    }

                    const snoozeCheckbox = document.getElementById('snooze_option_checkbox');
                    if (snoozeCheckbox && snoozeCheckbox.checked) {
                        const cookieTime = document.querySelector('.cf-plugin-deacmodal__footer-snooze-period').value;
                        setCookieName('snooze_free_deactivate_popup', "yes", parseInt(cookieTime));
                    }
                    const settingsData = new FormData();
                    settingsData.append('action', 'multicollab_deactive_plugin_free');
                    if (typeof multicollabPluginDeactivation !== 'undefined') {
                        settingsData.append('nonce', multicollabPluginDeactivation.nonce);
                    }
                    settingsData.append('subscription_option', subscriptionOption);
                    settingsData.append('fs_feedback_message', fs_feedback_message);

                    settingsData.append('free_plugin_deactivate_step3', free_plugin_deactivate_step3);

                    const settingsmodalInner = document.querySelector('.cf-plugin-deacmodal__inner');
                    settingsmodalInner?.classList.add('cf-active-loader');

                    fetch(ajaxurl, {
                        method: 'POST',
                        body: settingsData
                    })
                    .then(response => response.text())
                    .then(success => {
                        if (success === 'success') {
                            location.reload();
                        }
                    })
                    .finally(() => {
                        settingsmodalInner?.classList.remove('cf-active-loader');
                    });
                    
                }else{

                    const settingsData = new FormData();
                    settingsData.append('action', 'multicollab_deactive_plugin_free');
                    if (typeof multicollabPluginDeactivation !== 'undefined') {
                        settingsData.append('nonce', multicollabPluginDeactivation.nonce);
                    }

                    settingsData.append('first_option_value', 'yes');
                    settingsData.append('free_plugin_deactivate_step3', free_plugin_deactivate_step3);

                    const settingsmodalInner = document.querySelector('.cf-plugin-deacmodal__inner');
                    settingsmodalInner?.classList.add('cf-active-loader');

                    fetch(ajaxurl, {
                        method: 'POST',
                        body: settingsData
                    })
                    .then(response => response.text())
                    .then(success => {
                        if (success === 'success') {
                            location.reload();
                        }
                    })
                    .finally(() => {
                        settingsmodalInner?.classList.remove('cf-active-loader');
                    });
                }
            }
        }

        // Handling active button click
        if (target.matches('.cf-plugin-deacmodal__footer .btn-active')) {
            event.preventDefault();
            let cfDeacmodal1 = document.querySelector('.cf-plugin-deacmodal__inner #step-1');
            let cfDeacmodal2 = document.querySelector('.cf-plugin-deacmodal__inner #step-2');
            let cfDeacmodal3 = document.querySelector('.cf-plugin-deacmodal__inner #step-3');
            let cfDeacmodalFooter = document.querySelector('.cf-plugin-deacmodal__inner .cf-plugin-deacmodal__footer');
            if (cfDeacmodal1) {
                cfDeacmodal1.style.display = 'none';
            }
            if (cfDeacmodal2) {
                cfDeacmodal2.style.display = 'none';
            }
            if (cfDeacmodal3) {
                cfDeacmodal3.style.display = 'block';
            }
            if (cfDeacmodalFooter) {
                cfDeacmodalFooter.style.display = 'none';
            }
            let cfModelTitle = document.querySelector('.cf-plugin-deacmodal__inner .cf-plugin-deacmodal__header .modal-title');
            if(cfModelTitle){
                cfModelTitle.innerHTML = 'How would you rate your overall experience with Multicollab?';
            }
        }
    });

    document.querySelectorAll('.feedback_message').forEach(function(element) {
        element.addEventListener('keyup', cfFoggleButtonState);
        element.addEventListener('keypress', cfFoggleButtonState);
    });


});

function cfFoggleButtonState() {
    const button = document.querySelector('.cf-plugin-deacmodal__footer .btn-primary');
    if (this.value.length > 0) {
        button.classList.add('btn-active');
    } else {
        button.classList.remove('btn-active');
    }
}

function hideTextboxs( selectors ) {

    document.querySelectorAll( selectors ).forEach(msg => {
        msg.style.display = 'none';
    });

}

function getCookieName(name) {
    const nameEQ = name + "=";
    const ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i].trim();
        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function setCookieName(name, value, minutes) {
    let expires = "";
    if (minutes) {
        const date = new Date();
        date.setTime(date.getTime() + (minutes * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "") + expires + "; path=/";
}