/**
 * Module Disable Reason Picker
 */

(function($) {
    'use strict';

    const WPSB_DisableReason = {
        init: function() {
            this.createPopover();
            this.bindEvents();
        },

        createPopover: function() {
            if ($('#wpsb-disable-reason-popover').length) {
                return;
            }

            const popoverHTML = `
                <div id="wpsb-disable-reason-popover" class="wpsb-disable-popover" style="display: none;">
                    <div class="wpsb-disable-popover-content">
                        <h4>${wpsbTelemetry.i18n.title}</h4>
                        <div class="wpsb-disable-reasons">
                            <label class="wpsb-reason-option">
                                <input type="radio" name="wpsb_disable_reason" value="not_needed">
                                <span>${wpsbTelemetry.i18n.not_needed}</span>
                            </label>
                            <label class="wpsb-reason-option">
                                <input type="radio" name="wpsb_disable_reason" value="has_issues">
                                <span>${wpsbTelemetry.i18n.has_issues}</span>
                            </label>
                            <label class="wpsb-reason-option">
                                <input type="radio" name="wpsb_disable_reason" value="performance">
                                <span>${wpsbTelemetry.i18n.performance}</span>
                            </label>
                            <label class="wpsb-reason-option">
                                <input type="radio" name="wpsb_disable_reason" value="missing_features">
                                <span>${wpsbTelemetry.i18n.missing_features}</span>
                            </label>
                            <label class="wpsb-reason-option">
                                <input type="radio" name="wpsb_disable_reason" value="just_testing">
                                <span>${wpsbTelemetry.i18n.just_testing}</span>
                            </label>
                        </div>
                        <div class="wpsb-disable-popover-footer">
                            <button type="button" class="button wpsb-skip-reason">${wpsbTelemetry.i18n.skip}</button>
                        </div>
                    </div>
                </div>
            `;

            $('body').append(popoverHTML);
        },

        bindEvents: function() {
            const self = this;

            // Intercept module disable toggle
            $(document).on('change', '.wpsb-module-toggle', function(e) {
                const $toggle = $(this);
                const isEnabled = $toggle.prop('checked');

                // If disabling, show popover
                if (!isEnabled) {
                    e.preventDefault();
                    e.stopPropagation();

                    // Reset toggle (will be disabled after reason is selected)
                    $toggle.prop('checked', true);

                    // Show popover
                    self.showPopover($toggle);
                }
            });

            // Handle reason selection
            $(document).on('change', '#wpsb-disable-reason-popover input[type="radio"]', function() {
                const reason = $(this).val();
                const $toggle = $('#wpsb-disable-reason-popover').data('toggle');

                if ($toggle) {
                    self.disableModule($toggle, reason);
                    self.hidePopover();
                }
            });

            // Handle skip button
            $(document).on('click', '.wpsb-skip-reason', function() {
                const $toggle = $('#wpsb-disable-reason-popover').data('toggle');

                if ($toggle) {
                    self.disableModule($toggle, null);
                    self.hidePopover();
                }
            });

            // Close popover on outside click
            $(document).on('click', function(e) {
                const $popover = $('#wpsb-disable-reason-popover');
                if ($popover.is(':visible') &&
                    !$popover.is(e.target) &&
                    $popover.has(e.target).length === 0 &&
                    !$(e.target).hasClass('wpsb-module-toggle')) {

                    // Reset toggle
                    const $toggle = $popover.data('toggle');
                    if ($toggle) {
                        $toggle.prop('checked', true);
                    }

                    self.hidePopover();
                }
            });
        },

        showPopover: function($toggle) {
            const $popover = $('#wpsb-disable-reason-popover');
            const offset = $toggle.offset();

            // Clear previous selection
            $popover.find('input[type="radio"]').prop('checked', false);

            // Store reference to toggle
            $popover.data('toggle', $toggle);

            // Position popover
            $popover.css({
                top: offset.top + $toggle.outerHeight() + 5,
                left: offset.left,
                display: 'block'
            });

            // Add class to body to prevent interactions
            $('body').addClass('wpsb-popover-active');
        },

        hidePopover: function() {
            const $popover = $('#wpsb-disable-reason-popover');
            $popover.hide().removeData('toggle');
            $('body').removeClass('wpsb-popover-active');
        },

        disableModule: function($toggle, reason) {
            const moduleSlug = $toggle.data('module');

            // Actually disable the toggle
            $toggle.prop('checked', false);

            const ajaxData = {
                action: 'wpsb_disable_module',
                nonce: wpsbTelemetry.nonce,
                module: moduleSlug,
                reason: reason
            };

            // Send AJAX request
            $.ajax({
                url: wpsbTelemetry.ajaxUrl,
                type: 'POST',
                data: ajaxData,
                success: function(response) {
                    if (!response.success) {
                        console.error('WPSB: Failed to disable module:', response);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('WPSB: Error disabling module:', status, error);
                    // Revert toggle on error
                    $toggle.prop('checked', true);
                }
            });
        }
    };

    // Initialize on document ready
    $(document).ready(function() {
        if (typeof wpsbTelemetry !== 'undefined') {
            WPSB_DisableReason.init();
        }
    });

})(jQuery);
