jQuery(document).ready(function ($) {

    /**
     * HTML-escape a value before string-concatenation into the DOM.
     *
     * All server responses and scanned-HTML strings (loc.location, item.url,
     * item.recommendation, etc.) MUST flow through this helper to prevent
     * stored / reflected XSS in the wp-admin context. Use `escUrl` for
     * anything destined for an `href`.
     */
    function escHtml(value) {
        if (value === null || value === undefined) return '';
        return String(value)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
    }

    /**
     * Render analysis results into the UI.
     */
    function renderAnalysis(data) {
        var results = $('#speeinch-analysis-results');
        results.show();

        var summary = data && data.summary ? data.summary : {};
        var summaryHtml = '';
        summaryHtml += '<div class="speeinch-summary-card score"><span class="number">' + escHtml(summary.score) + '/100</span><span class="label">China Score</span></div>';
        summaryHtml += '<div class="speeinch-summary-card critical"><span class="number">' + escHtml(summary.critical) + '</span><span class="label">Critical</span></div>';
        summaryHtml += '<div class="speeinch-summary-card warning"><span class="number">' + escHtml(summary.warnings) + '</span><span class="label">Warnings</span></div>';
        summaryHtml += '<div class="speeinch-summary-card info"><span class="number">' + escHtml(summary.passed || 0) + '</span><span class="label">Passed</span></div>';
        $('#speeinch-analysis-summary').html(summaryHtml);

        if (data && data.timestamp) {
            $('#speeinch-analysis-timestamp')
                .html('<small style="color:#6b7280;">🕐 Last scanned: ' + escHtml(data.timestamp) + ' UTC</small>')
                .show();
        }

        var issuesHtml = '';
        var severities = ['critical', 'warning', 'info'];
        var labels = { critical: '🔴 Critical Issues', warning: '🟡 Warnings', info: '🟢 Informational' };

        var issues = (data && data.issues) ? data.issues : {};

        severities.forEach(function (severity) {
            var items = issues[severity] || [];
            if (items.length === 0) return;

            issuesHtml += '<div class="speeinch-issue-group"><h3>' + escHtml(labels[severity]) + '</h3>';
            items.forEach(function (item) {
                issuesHtml += '<div class="speeinch-issue ' + escHtml(severity) + '">';
                issuesHtml += '<div class="speeinch-issue-detail">';
                issuesHtml += '<span class="speeinch-issue-service">' + escHtml(item.service) + '</span>';
                issuesHtml += '<span class="speeinch-issue-type">' + escHtml(item.type) + ': ' + escHtml(item.handle) + '</span>';
                issuesHtml += '<div class="speeinch-issue-rec">' + escHtml(item.recommendation) + '</div>';
                if (item.url) issuesHtml += '<div class="speeinch-issue-url">' + escHtml(item.url) + '</div>';
                issuesHtml += '</div></div>';
            });
            issuesHtml += '</div>';
        });

        if (data && data.passed && data.passed.length > 0) {
            issuesHtml += '<div class="speeinch-issue-group"><h3>✅ Passed Checks</h3>';
            data.passed.forEach(function (item) {
                issuesHtml += '<div class="speeinch-issue info">';
                issuesHtml += '<div class="speeinch-issue-detail">';
                issuesHtml += '<span class="speeinch-issue-service">✅ ' + escHtml(item.service) + '</span>';
                issuesHtml += '<span class="speeinch-issue-type">' + escHtml(item.handle) + '</span>';
                issuesHtml += '<div class="speeinch-issue-rec" style="color:#16a34a;">' + escHtml(item.recommendation) + '</div>';
                issuesHtml += '</div></div>';
            });
            issuesHtml += '</div>';
        }

        if (summary.total === 0 && (!data.passed || data.passed.length === 0)) {
            issuesHtml = '<div class="speeinch-issue info"><div class="speeinch-issue-detail"><span class="speeinch-issue-service">✅ No China-blocking issues detected!</span></div></div>';
        }

        $('#speeinch-analysis-issues').html(issuesHtml);
    }

    // Load persisted results on page load.
    if (typeof speeinchOptimizations !== 'undefined' && speeinchOptimizations.savedAnalysis) {
        renderAnalysis(speeinchOptimizations.savedAnalysis);
    }

    // Run Analysis.
    $('#speeinch-run-analysis').on('click', function () {
        var btn = $(this);
        var spinner = $('#speeinch-analysis-spinner');
        var results = $('#speeinch-analysis-results');

        btn.attr('disabled', true);
        spinner.addClass('is-active');

        $.ajax({
            type: 'POST',
            url: speeinch.ajaxurl,
            data: {
                action: 'speeinch_run_analysis',
                security: speeinch.ajax_nonce
            },
            success: function (response) {
                spinner.removeClass('is-active');
                btn.attr('disabled', false);

                if (!response.success) {
                    $('#speeinch-analysis-issues').html('<div class="speeinch-issue critical"><div class="speeinch-issue-detail"><span class="speeinch-issue-service">Analysis failed: ' + escHtml(response.data || 'Unknown error') + '</span></div></div>');
                    results.show();
                    return;
                }

                renderAnalysis(response.data);
            },
            error: function (xhr) {
                spinner.removeClass('is-active');
                btn.attr('disabled', false);
                $('#speeinch-analysis-issues').html('<div class="speeinch-issue critical"><div class="speeinch-issue-detail"><span class="speeinch-issue-service">Request failed (HTTP ' + escHtml(xhr && xhr.status) + ')</span></div></div>');
                results.show();
            }
        });
    });

    // Toggle Google Fonts.
    $('#speeinch-google-fonts-toggle').on('change', function () {
        var enabled = $(this).is(':checked') ? '1' : '0';
        var status = $('#speeinch-font-status');

        status.html('<span class="spinner is-active" style="float:none;"></span> ' + (enabled === '1' ? 'Enabling and caching fonts...' : 'Disabling...'));

        $.ajax({
            type: 'POST',
            url: speeinch.ajaxurl,
            data: {
                action: 'speeinch_toggle_google_fonts',
                enabled: enabled,
                security: speeinch.ajax_nonce
            },
            success: function (response) {
                if (response.success) {
                    var msg = (response.data && response.data.message) ? response.data.message : '';
                    status.html('<span style="color: #22c55e;">✓</span> ' + escHtml(msg));
                } else {
                    status.html('<span style="color: #ef4444;">✗</span> ' + escHtml(response.data || 'Failed'));
                }
            },
            error: function (xhr) {
                status.html('<span style="color: #ef4444;">✗</span> Request failed (HTTP ' + escHtml(xhr && xhr.status) + ')');
            }
        });
    });

    // Clear Font Cache.
    $('#speeinch-clear-font-cache').on('click', function () {
        var status = $('#speeinch-font-status');
        status.html('<span class="spinner is-active" style="float:none;"></span> Clearing cache...');

        $.ajax({
            type: 'POST',
            url: speeinch.ajaxurl,
            data: {
                action: 'speeinch_clear_font_cache',
                security: speeinch.ajax_nonce
            },
            success: function (response) {
                if (response.success) {
                    var msg = (response.data && response.data.message) ? response.data.message : '';
                    status.html('<span style="color: #22c55e;">✓</span> ' + escHtml(msg));
                } else {
                    status.html('<span style="color: #ef4444;">✗</span> ' + escHtml(response.data || 'Failed'));
                }
            },
            error: function (xhr) {
                status.html('<span style="color: #ef4444;">✗</span> Request failed (HTTP ' + escHtml(xhr && xhr.status) + ')');
            }
        });
    });
});
