(function ($) {

    // GLOBAL STATE
    window.SS_UI_LOCKED = false; // prevents table + progress refresh

    // ---------------------------------------------------------------------
    // 🚫 INTERCEPT AUTOMATIC REFRESH CALLS WHEN UI IS LOCKED
    // ---------------------------------------------------------------------
    const _originalPost = $.post;
    $.post = function (url, data, callback, type) {
        const blockedActions = ['ss_scanner_table', 'ss_scanner_status'];

        if (window.SS_UI_LOCKED && data?.action && blockedActions.includes(data.action)) {
            return; // block auto refresh
        }
        return _originalPost.apply(this, arguments);
    };

    // ---------------------------------------------------------------------
    // PROGRESS BAR
    // ---------------------------------------------------------------------
    function refreshProgress() {
        if (window.SS_UI_LOCKED) return;

        $.post(SS_Scanner_Ajax.ajax_url, {
            action: 'ss_scanner_status',
            nonce: SS_Scanner_Ajax.nonce
        }, function (res) {

            if (!res) return;

            // Update progress bar
            $('#ss-scan-progress-bar').css('width', res.percent + '%');
            $('#ss-scan-progress-text').text(
                `Scanned ${res.done} of ${res.total} pages (${res.percent}%)`
            );

            // Auto refresh table when everything is done
            if (res.total > 0 && res.done === res.total) {
                refreshTable(true);
            }
        });
    }

    // ---------------------------------------------------------------------
    // REFRESH TABLE
    // ---------------------------------------------------------------------
    function refreshTable(force) {
        if (window.SS_UI_LOCKED) return;

        $.post(SS_Scanner_Ajax.ajax_url, {
            action: 'ss_scanner_table',
            nonce: SS_Scanner_Ajax.nonce
        }, function (res) {
            if (res.success && res.data.html) {
                $('table.widefat tbody').html(res.data.html);
            }
        });
    }

    // ---------------------------------------------------------------------
    // INIT + AUTO UPDATE LOOP
    // ---------------------------------------------------------------------
    $(document).ready(function () {
        refreshProgress();
        refreshTable();

        // update every 5 seconds
        setInterval(refreshProgress, 5000);
    });

    // **********************************************************************
    // VIEW RECOMMENDATIONS
    // **********************************************************************
    $(document).on('click', '.view-recommendations', function () {

        const btn = $(this);
        const scanId = btn.data('scan-id');
        const row = $('#recommendations-' + scanId);
        const content = row.find('.recommendation-content');

        // If already visible → close it
        if (row.is(':visible')) {
            row.hide();
            window.SS_UI_LOCKED = false; // allow auto refresh again
            return;
        }

        // OPEN recommendations → freeze refresh
        window.SS_UI_LOCKED = true;

        row.show();
        content.html('<em>Loading recommendations...</em>');

        $.post(SS_Scanner_Ajax.ajax_url, {
            action: 'ss_get_recommendations',
            scan_id: scanId,
            nonce: SS_Scanner_Ajax.nonce
        }, function (response) {

            if (response.success) {
                content.html(response.data.html);

                // If fully optimized change the button
                if (response.data.html.includes("✅ All Good")) {
                    btn.replaceWith('<span class="button" style="background:#4CAF50;color:#fff;">✅ Optimized</span>');
                }
            } else {
                content.html('<p style="color:red;">Failed to load recommendations.</p>');
            }
        });
    });
    $(document).on("click", ".ss-close-recommendations", function () {
        const row = $(this).closest("tr.recommendation-row");
        row.hide();

        // 🔓 Re-enable auto-refresh
        window.SS_UI_LOCKED = false;
    });

    // **********************************************************************
    // APPLY FIX
    // **********************************************************************
    $(document).on('click', '.ss-apply-rec', function () {

        const btn = $(this);
        const scanId = btn.data('scan');
        const action = btn.data('action');

        btn.prop('disabled', true).text('Applying...');

        $.post(SS_Scanner_Ajax.ajax_url, {
            action: 'ss_apply_recommendation',
            scan_id: scanId,
            fix_action: action,
            nonce: SS_Scanner_Ajax.nonce
        }, function (response) {

            if (!response.success) {
                btn.text('❌ Failed');
                alert(response.data?.message || 'Fix failed.');
                return;
            }

            btn.text('✅ Applied');

            // Reload recommendation list after 1 sec
            setTimeout(() => {
                $.post(SS_Scanner_Ajax.ajax_url, {
                    action: 'ss_get_recommendations',
                    scan_id: scanId,
                    nonce: SS_Scanner_Ajax.nonce
                }, function (res) {
                    if (res.success) {
                        $('#recommendations-' + scanId)
                            .find('.recommendation-content')
                            .html(res.data.html);
                    }
                });
            }, 1000);

            // Refresh table after 1.5 sec
            setTimeout(() => refreshTable(true), 1500);
        });
    });

    // **********************************************************************
    // VIEW DIFF (MODAL)
    // **********************************************************************
    $(document).on('click', '.ss-view-diff', function () {

        const btn = $(this);
        const scanId = btn.data('scan-id');

        btn.prop('disabled', true).text('Loading...');

        $.post(SS_Scanner_Ajax.ajax_url, {
            action: 'ss_get_diff',
            scan_id: scanId,
            nonce: SS_Scanner_Ajax.nonce
        }, function (res) {

            btn.prop('disabled', false).text('🧾 View Diff');

            if (!res.success) {
                alert(res.data?.message || 'Failed to load diff');
                return;
            }

            $('#ss-modal-root').find('.ss-modal').remove();

            const modal = $(`
                <div class="ss-modal" style="
                    position:fixed;top:0;left:0;width:100%;height:100%;
                    background:rgba(0,0,0,0.6);z-index:9999999;
                    display:flex;align-items:center;justify-content:center;">
                    <div style="
                        background:#fff;padding:20px;width:90%;max-width:850px;
                        border-radius:8px;max-height:85vh;overflow:auto;position:relative;">
                        <button class="ss-close-modal" style="
                            position:absolute;top:10px;right:10px;
                            background:#e74c3c;color:#fff;padding:6px 10px;">
                            ✕ Close
                        </button>
                        ${res.data.html}
                    </div>
                </div>
            `);

            $('#ss-modal-root').append(modal);

            // Modal open → freeze auto refresh
            window.SS_UI_LOCKED = true;

            modal.on('click', '.ss-close-modal', function () {
                modal.remove();
                window.SS_UI_LOCKED = false; // resume refresh
            });
        });
    });

    // **********************************************************************
    // RE-OPTIMIZE BUTTON
    // **********************************************************************
    $(document).on('click', '.ss-reoptimize', function () {

        const btn = $(this);
        const scanId = btn.data('scan-id');

        btn.prop('disabled', true).text('Re-optimizing...');

        $.post(SS_Scanner_Ajax.ajax_url, {
            action: 'ss_reoptimize_scan',
            scan_id: scanId,
            nonce: SS_Scanner_Ajax.nonce
        }, function (res) {

            btn.prop('disabled', false).text('♻️ Re-optimize');

            alert(res.data?.message || 'Re-optimization complete.');

            refreshTable(true);
        });
    });

})(jQuery);
