/**
 * SEO Fury - Uninstall Dialog
 *
 * Intercepts the "Delete" action on the plugins.php page
 * and shows a dialog asking the user whether to keep or remove database data.
 */
(function ($) {
    'use strict';

    if (typeof seoFuryUninstall === 'undefined') {
        return;
    }

    var i18n  = seoFuryUninstall.i18n;
    var nonce = seoFuryUninstall.nonce;
    var slug  = seoFuryUninstall.pluginSlug;

    /**
     * Inject the modal CSS into the page head.
     */
    function injectStyles() {
        var css =
            '#seo-fury-uninstall-overlay {' +
                'position: fixed; top: 0; left: 0; width: 100%; height: 100%;' +
                'background: rgba(0,0,0,0.65); z-index: 999999;' +
                'display: flex; align-items: center; justify-content: center;' +
            '}' +
            '#seo-fury-uninstall-dialog {' +
                'background: #fff; border-radius: 8px; padding: 32px 36px 28px;' +
                'max-width: 520px; width: 90%; box-shadow: 0 8px 32px rgba(0,0,0,0.25);' +
                'font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;' +
                'position: relative;' +
            '}' +
            '#seo-fury-uninstall-dialog h2 {' +
                'margin: 0 0 8px; font-size: 20px; font-weight: 600; color: #1d2327;' +
            '}' +
            '#seo-fury-uninstall-dialog .sfu-subtitle {' +
                'margin: 0 0 24px; font-size: 13px; color: #646970;' +
            '}' +
            '#seo-fury-uninstall-dialog .sfu-option {' +
                'display: flex; align-items: flex-start; gap: 12px;' +
                'padding: 16px; margin-bottom: 12px; border: 2px solid #dcdcde;' +
                'border-radius: 6px; cursor: pointer; transition: border-color 0.15s, background 0.15s;' +
            '}' +
            '#seo-fury-uninstall-dialog .sfu-option:hover {' +
                'border-color: #2271b1; background: #f0f6fc;' +
            '}' +
            '#seo-fury-uninstall-dialog .sfu-option.sfu-selected {' +
                'border-color: #2271b1; background: #f0f6fc;' +
            '}' +
            '#seo-fury-uninstall-dialog .sfu-option input[type="radio"] {' +
                'margin-top: 2px; flex-shrink: 0;' +
            '}' +
            '#seo-fury-uninstall-dialog .sfu-option-text strong {' +
                'display: block; font-size: 14px; color: #1d2327; margin-bottom: 4px;' +
            '}' +
            '#seo-fury-uninstall-dialog .sfu-option-text span {' +
                'font-size: 12.5px; color: #646970; line-height: 1.4;' +
            '}' +
            '#seo-fury-uninstall-dialog .sfu-badge {' +
                'display: inline-block; background: #00a32a; color: #fff;' +
                'font-size: 11px; font-weight: 600; padding: 2px 8px; border-radius: 3px;' +
                'margin-left: 6px; vertical-align: middle;' +
            '}' +
            '#seo-fury-uninstall-dialog .sfu-actions {' +
                'display: flex; gap: 12px; justify-content: flex-end; margin-top: 24px;' +
            '}' +
            '#seo-fury-uninstall-dialog .sfu-btn {' +
                'padding: 8px 20px; border-radius: 4px; font-size: 13px; font-weight: 500;' +
                'cursor: pointer; border: 1px solid; transition: background 0.15s, color 0.15s;' +
                'text-decoration: none; line-height: 1.5;' +
            '}' +
            '#seo-fury-uninstall-dialog .sfu-btn-cancel {' +
                'background: #f0f0f1; border-color: #c3c4c7; color: #1d2327;' +
            '}' +
            '#seo-fury-uninstall-dialog .sfu-btn-cancel:hover {' +
                'background: #e0e0e1;' +
            '}' +
            '#seo-fury-uninstall-dialog .sfu-btn-confirm {' +
                'background: #d63638; border-color: #d63638; color: #fff;' +
            '}' +
            '#seo-fury-uninstall-dialog .sfu-btn-confirm:hover {' +
                'background: #b32d2e; border-color: #b32d2e;' +
            '}' +
            '#seo-fury-uninstall-dialog .sfu-btn-confirm:disabled {' +
                'background: #f0adae; border-color: #f0adae; cursor: not-allowed;' +
            '}' +
            '#seo-fury-uninstall-dialog .sfu-spinner {' +
                'display: inline-block; width: 16px; height: 16px;' +
                'border: 2px solid rgba(255,255,255,0.3); border-top-color: #fff;' +
                'border-radius: 50%; animation: sfu-spin 0.6s linear infinite;' +
                'vertical-align: middle; margin-right: 6px;' +
            '}' +
            '@keyframes sfu-spin {' +
                'to { transform: rotate(360deg); }' +
            '}';

        $('<style>').text(css).appendTo('head');
    }

    /**
     * Build and show the modal dialog.
     *
     * @param {string}   deleteUrl The original WP delete URL
     */
    function showDialog(deleteUrl) {
        // Remove any existing dialog
        $('#seo-fury-uninstall-overlay').remove();

        var html =
            '<div id="seo-fury-uninstall-overlay">' +
                '<div id="seo-fury-uninstall-dialog" role="dialog" aria-modal="true">' +
                    '<h2>' + escHtml(i18n.title) + '</h2>' +
                    '<p class="sfu-subtitle">' + escHtml(i18n.subtitle) + '</p>' +

                    '<label class="sfu-option sfu-selected" data-value="0">' +
                        '<input type="radio" name="sfu_delete_data" value="0" checked>' +
                        '<div class="sfu-option-text">' +
                            '<strong>' + escHtml(i18n.keepTitle) + ' <span class="sfu-badge">' + escHtml(i18n.recommended) + '</span></strong>' +
                            '<span>' + escHtml(i18n.keepDesc) + '</span>' +
                        '</div>' +
                    '</label>' +

                    '<label class="sfu-option" data-value="1">' +
                        '<input type="radio" name="sfu_delete_data" value="1">' +
                        '<div class="sfu-option-text">' +
                            '<strong>' + escHtml(i18n.deleteTitle) + '</strong>' +
                            '<span>' + escHtml(i18n.deleteDesc) + '</span>' +
                        '</div>' +
                    '</label>' +

                    '<div class="sfu-actions">' +
                        '<button type="button" class="sfu-btn sfu-btn-cancel" id="sfu-cancel">' + escHtml(i18n.cancel) + '</button>' +
                        '<button type="button" class="sfu-btn sfu-btn-confirm" id="sfu-confirm">' + escHtml(i18n.confirm) + '</button>' +
                    '</div>' +
                '</div>' +
            '</div>';

        var $overlay = $(html).appendTo('body');

        // Highlight selected option
        $overlay.on('change', 'input[name="sfu_delete_data"]', function () {
            $overlay.find('.sfu-option').removeClass('sfu-selected');
            $(this).closest('.sfu-option').addClass('sfu-selected');
        });

        // Cancel
        $overlay.on('click', '#sfu-cancel', function () {
            $overlay.remove();
        });

        // Click overlay background to cancel
        $overlay.on('click', function (e) {
            if (e.target === $overlay[0]) {
                $overlay.remove();
            }
        });

        // Escape key to cancel
        $(document).on('keydown.sfuDialog', function (e) {
            if (e.key === 'Escape') {
                $overlay.remove();
                $(document).off('keydown.sfuDialog');
            }
        });

        // Confirm
        $overlay.on('click', '#sfu-confirm', function () {
            var $btn      = $(this);
            var deleteVal = $overlay.find('input[name="sfu_delete_data"]:checked').val();

            // Disable button and show spinner
            $btn.prop('disabled', true).html(
                '<span class="sfu-spinner"></span>' + escHtml(i18n.processing)
            );

            // Save preference via AJAX, then redirect to WP delete URL
            $.ajax({
                url: seoFuryUninstall.ajaxUrl,
                method: 'POST',
                data: {
                    action: 'seo_fury_set_delete_preference',
                    nonce: nonce,
                    delete_data: deleteVal
                },
                success: function () {
                    $(document).off('keydown.sfuDialog');
                    window.location.href = deleteUrl;
                },
                error: function () {
                    // Even on AJAX error, proceed with deletion (default is keep data = 0)
                    $(document).off('keydown.sfuDialog');
                    window.location.href = deleteUrl;
                }
            });
        });
    }

    /**
     * Simple HTML escaping to prevent XSS in translated strings.
     */
    function escHtml(str) {
        var div = document.createElement('div');
        div.appendChild(document.createTextNode(str));
        return div.innerHTML;
    }

    /**
     * Find and intercept the Delete link for our plugin.
     */
    function init() {
        injectStyles();

        // Encoded slug for matching in href attributes
        var encodedSlug = encodeURIComponent(slug);

        // Use delegated event to catch all delete link clicks
        $(document).on('click', 'a.delete', function (e) {
            var $link = $(this);
            var href  = $link.attr('href') || '';

            // Check if this delete link is for our plugin
            if (href.indexOf(encodedSlug) === -1 && href.indexOf(slug) === -1) {
                return; // Not our plugin, let it through
            }

            e.preventDefault();
            e.stopImmediatePropagation();

            showDialog(href);
        });
    }

    $(document).ready(init);

})(jQuery);
