/**
 * Sifency Feedback & Deactivation Modal
 * 
 * - Intercepts plugin deactivation/deletion
 * - Collects user feedback
 * - Handles data retention/deletion choices
 */
(function ($) {
    'use strict';

    if (typeof sifencyDeactivation === 'undefined') return;

    const SifencyFeedback = {
        actionUrl: '',
        actionType: '',

        /**
         * Initialize the module
         */
        init: function () {
            this.cacheDOM();
            this.bindEvents();
        },

        /**
         * Cache DOM elements for better performance
         */
        cacheDOM: function () {
            this.$modal = $('.sifency-feedback-modal');
            this.$overlay = $('.sifency-feedback-modal-overlay');
            this.$submitBtn = this.$modal.find('.sifency-feedback-submit');
            this.$skipBtn = this.$modal.find('.sifency-feedback-skip');
            this.$cancelBtn = this.$modal.find('.sifency-feedback-cancel');
            this.$warningChoice = this.$modal.find('.sifency-data-choice-warning');
            this.$otherTextarea = this.$modal.find('.sifency-feedback-other');
        },

        /**
         * Bind all event listeners
         */
        bindEvents: function () {
            const pluginSlug = sifencyDeactivation.plugin_basename.split('/')[0];
            const targetSelector = `[data-slug="${pluginSlug}"] .deactivate a, [data-slug="${pluginSlug}"] .delete a`;

            $('#the-list').on('click', targetSelector, (e) => {
                e.preventDefault();
                
                const $target = $(e.currentTarget);
                this.actionUrl = $target.attr('href');
                this.actionType = $target.closest('.delete').length > 0 ? 'delete' : 'deactivate';

                this.setupModalUI();
                
                this.$overlay.fadeIn(200);
                this.$modal.fadeIn(200);
            });

            this.$modal.on('click', '.sifency-feedback-submit, .sifency-feedback-skip', (e) => {
                e.preventDefault();
                this.processAction($(e.currentTarget));
            });

            this.$modal.on('change', 'input[name="sifency_feedback_reason"]', (e) => {
                if ($(e.currentTarget).val() === 'other') {
                    this.$otherTextarea.slideDown(250);
                } else {
                    this.$otherTextarea.slideUp(250);
                }
            });

            this.$modal.on('click', '.sifency-feedback-cancel', (e) => {
                e.preventDefault();
                this.closeModal();
            });

            this.$overlay.on('click', () => this.closeModal());
        },

        /**
         * Update modal text and UI state depending on action type
         */
        setupModalUI: function () {
            if (this.actionType === 'delete') {
                this.$submitBtn.text(sifencyDeactivation.i18n.submit_delete);
                this.$skipBtn.text(sifencyDeactivation.i18n.skip_delete);
                this.$warningChoice.show();
            } else {
                this.$submitBtn.text(sifencyDeactivation.i18n.submit_deactivate);
                this.$skipBtn.text(sifencyDeactivation.i18n.skip_deactivate);
                this.$warningChoice.hide();
            }
        },

        /**
         * Process the AJAX requests and redirect
         * @param {jQuery} $button The clicked button
         */
        processAction: function ($button) {

            const $allButtons = this.$submitBtn.add(this.$skipBtn).add(this.$cancelBtn);
            $allButtons.prop('disabled', true);
            $button.text('Processing...');

            const promises =[];
            const dataChoice = this.$modal.find('input[name="sifency_data_choice"]:checked').val();
            const reason = this.$modal.find('input[name="sifency_feedback_reason"]:checked').val();
            const otherInfo = this.$otherTextarea.val();
            const isSubmittingFeedback = $button.hasClass('sifency-feedback-submit');


            if (dataChoice === 'delete') {
                promises.push($.post(sifencyDeactivation.ajax_url, {
                    action: 'sifency_set_uninstall_flag',
                    nonce: sifencyDeactivation.nonce
                }));
            }

            if (isSubmittingFeedback) {
                promises.push($.post(sifencyDeactivation.ajax_url, {
                    action: 'sifency_submit_deactivation_feedback',
                    nonce: sifencyDeactivation.nonce,
                    reason: reason,
                    other_info: otherInfo
                }));
            }


            $.when(...promises).always(() => {
                window.location.href = this.actionUrl;
            });
        },

        /**
         * Close the modal and reset states
         */
        closeModal: function () {
            this.$modal.fadeOut(200);
            this.$overlay.fadeOut(200);
        }
    };

    // Initialize on Document Ready
    $(document).ready(() => {
        SifencyFeedback.init();
    });

})(jQuery);