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

    // Escape user-controlled values before injecting into HTML / attributes.
    // 404 URLs, referrers and user-agents come straight from request headers
    // of (possibly anonymous) visitors, so unescaped output is a stored-XSS
    // vector that fires in the admin's browser when they open this screen.
    function escapeHtml(str) {
        return String(str)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    if ($('#log-404-table').length) {
        load404Logs();
    }

    function load404Logs() {
        $.ajax({
            url: seo404Monitor.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_load_404_log',
                nonce: seo404Monitor.nonce
            },
            beforeSend: function() {
                $('#log-404-table tbody').html('<tr><td colspan="7" style="text-align: center;">' + seo404Monitor.i18n.loading + '</td></tr>');
            },
            success: function(response) {
                if (response.success) {
                    updateStats(response.data.stats);
                    renderLogs(response.data.logs);
                } else {
                    $('#log-404-table tbody').html('<tr><td colspan="7" style="text-align: center; color: #d63638;">' + seo404Monitor.i18n.loadError + '</td></tr>');
                }
            },
            error: function() {
                $('#log-404-table tbody').html('<tr><td colspan="7" style="text-align: center; color: #d63638;">' + seo404Monitor.i18n.serverError + '</td></tr>');
            }
        });
    }

    function updateStats(stats) {
        $('#stat-total').text(stats.total || 0);
        $('#stat-active').text(stats.active || 0);
        $('#stat-resolved').text(stats.resolved || 0);
        $('#stat-hits').text(stats.total_hits || 0);
    }

    function renderLogs(logs) {
        var html = '';

        if (logs.length === 0) {
            html = '<tr><td colspan="7" style="text-align: center;">' + seo404Monitor.i18n.no404Found + '</td></tr>';
        } else {
            $.each(logs, function(index, log) {
                var statusBadge = log.resolved == 1
                    ? '<span style="color: #00a32a;">✓ ' + seo404Monitor.i18n.resolved + '</span>'
                    : '<span style="color: #d63638;">✗ ' + seo404Monitor.i18n.active + '</span>';

                var logId = parseInt(log.id, 10);
                var urlAttr = escapeHtml(log.url);

                var actions = '';
                if (log.resolved == 0) {
                    actions += '<button class="button button-small sf-icon-btn find-similar" data-id="' + logId + '" data-url="' + urlAttr + '" title="' + escapeHtml(seo404Monitor.i18n.find) + '" aria-label="' + escapeHtml(seo404Monitor.i18n.find) + '">\ud83d\udd0d</button> ';
                    actions += '<button class="button button-small sf-icon-btn create-redirect-btn" data-id="' + logId + '" data-url="' + urlAttr + '" title="' + escapeHtml(seo404Monitor.i18n.redirect) + '" aria-label="' + escapeHtml(seo404Monitor.i18n.redirect) + '">\u279c</button> ';
                    actions += '<button class="button button-small sf-icon-btn mark-resolved" data-id="' + logId + '" title="' + escapeHtml(seo404Monitor.i18n.resolve) + '" aria-label="' + escapeHtml(seo404Monitor.i18n.resolve) + '">\u2713</button> ';
                }
                actions += '<button class="button button-small sf-icon-btn delete-404" data-id="' + logId + '" style="color: #d63638;" title="' + escapeHtml(seo404Monitor.i18n.delete) + '" aria-label="' + escapeHtml(seo404Monitor.i18n.delete) + '">\ud83d\uddd1</button>';

                var decodedUrl;
                try {
                    decodedUrl = decodeURIComponent(log.url);
                } catch (e) {
                    decodedUrl = log.url;
                }

                html += '<tr>';
                html += '<td>' + logId + '</td>';
                html += '<td><code style="word-break: break-all;">' + escapeHtml(decodedUrl) + '</code></td>';
                html += '<td><strong>' + escapeHtml(log.hits) + '</strong></td>';
                html += '<td>' + escapeHtml(log.first_seen) + '</td>';
                html += '<td>' + escapeHtml(log.last_seen) + '</td>';
                html += '<td>' + statusBadge + '</td>';
                html += '<td class="error-404-actions">' + actions + '</td>';
                html += '</tr>';
            });
        }

        $('#log-404-table tbody').html(html);
    }

    $('#refresh-404-log').on('click', function() {
        load404Logs();
    });

    $('#clear-404-log').on('click', function() {
        if (!confirm(seo404Monitor.i18n.confirmClearAll)) {
            return;
        }

        $.ajax({
            url: seo404Monitor.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_clear_404_log',
                nonce: seo404Monitor.nonce
            },
            success: function(response) {
                if (response.success) {
                    alert('\u2705 ' + seo404Monitor.i18n.logsCleared);
                    load404Logs();
                } else {
                    alert('❌ Error: ' + response.data);
                }
            }
        });
    });

    $(document).on('click', '.find-similar', function() {
        var id = $(this).data('id');
        var url = $(this).data('url');

        $('#similar-404-id').val(id);
        $('#similar-source-url').val(url);
        $('#similar-url-display').text(url);

        $('#find-similar-modal').fadeIn();

        $.ajax({
            url: seo404Monitor.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_find_similar_pages',
                nonce: seo404Monitor.nonce,
                url: url
            },
            beforeSend: function() {
                $('#similar-pages-results').html('<p>' + seo404Monitor.i18n.searchingSimilar + '</p>');
            },
            success: function(response) {
                if (response.success && response.data.pages.length > 0) {
                    var html = '<p><strong>' + seo404Monitor.i18n.foundSimilar.replace('%d', response.data.pages.length) + '</strong></p>';
                    html += '<div style="max-height: 400px; overflow-y: auto;">';

                    $.each(response.data.pages, function(index, page) {
                        html += '<div style="padding: 10px; margin-bottom: 10px; background: var(--sf-gray-50, #f6f7f7); border: 1px solid var(--sf-gray-200, #e5e7eb); border-radius: 4px;">';
                        html += '<div style="margin-bottom: 5px;"><strong>' + escapeHtml(page.title) + '</strong></div>';
                        html += '<div style="margin-bottom: 10px;"><code>' + escapeHtml(page.url) + '</code></div>';
                        html += '<button class="button button-small use-this-url" data-url="' + escapeHtml(page.url) + '">' + seo404Monitor.i18n.useThisUrl + '</button>';
                        html += '</div>';
                    });

                    html += '</div>';
                    $('#similar-pages-results').html(html);
                } else {
                    $('#similar-pages-results').html('<p style="color: #d63638;">\u274c ' + seo404Monitor.i18n.noSimilarFound + '</p>');
                }
            }
        });
    });

    $(document).on('click', '.use-this-url', function() {
        var targetUrl = $(this).data('url');
        var sourceUrl = $('#similar-source-url').val();
        var logId = $('#similar-404-id').val();

        var decodedSource = decodeURIComponent(sourceUrl);

        $('#find-similar-modal').fadeOut();

        $('#redirect-404-id').val(logId);
        $('#error-404-redirect-source').val(decodedSource);
        $('#error-404-redirect-target').val(targetUrl);
        $('#create-redirect-modal').fadeIn();
    });

    $(document).on('click', '.create-redirect-btn', function() {
        var id = $(this).data('id');
        var url = $(this).data('url');

        var decodedUrl = decodeURIComponent(url);

        $('#redirect-404-id').val(id);
        $('#error-404-redirect-source').val(decodedUrl);
        $('#error-404-redirect-target').val('');
        $('#create-redirect-modal').fadeIn();
    });

    $('#save-redirect-btn').on('click', function() {
        var logId = $('#redirect-404-id').val();
        var source = $('#error-404-redirect-source').val();
        var target = $('#error-404-redirect-target').val().trim();
        var type = $('#redirect-type-modal').val();

        if (!target) {
            alert(seo404Monitor.i18n.provideTargetUrl);
            return;
        }

        var btn = $(this);
        var originalText = btn.text();
        btn.prop('disabled', true).text(seo404Monitor.i18n.creating);

        $.ajax({
            url: seo404Monitor.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_create_redirect_from_404',
                nonce: seo404Monitor.nonce,
                log_id: logId,
                source_url: source,
                target_url: target,
                redirect_type: type
            },
            success: function(response) {
                if (response.success) {
                    var message = typeof response.data === 'string' ? response.data : (response.data.message || seo404Monitor.i18n.redirectCreated);
                    alert('\u2705 ' + message);
                    $('#create-redirect-modal').fadeOut();
                    load404Logs();
                } else {
                    var errorMsg = typeof response.data === 'string' ? response.data : (response.data.message || seo404Monitor.i18n.errorCreatingRedirect);
                    alert('\u274C ' + errorMsg);
                }
            },
            error: function() {
                alert('\u274c ' + seo404Monitor.i18n.serverError);
            },
            complete: function() {
                btn.prop('disabled', false).text(originalText);
            }
        });
    });

    $(document).on('click', '.mark-resolved', function() {
        var id = $(this).data('id');

        $.ajax({
            url: seo404Monitor.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_mark_404_resolved',
                nonce: seo404Monitor.nonce,
                id: id
            },
            success: function(response) {
                if (response.success) {
                    load404Logs();
                } else {
                    alert('❌ ' + response.data);
                }
            }
        });
    });

    $(document).on('click', '.delete-404', function() {
        if (!confirm(seo404Monitor.i18n.confirmDeleteEntry)) {
            return;
        }

        var id = $(this).data('id');

        $.ajax({
            url: seo404Monitor.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_delete_404_entry',
                nonce: seo404Monitor.nonce,
                id: id
            },
            success: function(response) {
                if (response.success) {
                    load404Logs();
                } else {
                    alert('❌ ' + response.data);
                }
            }
        });
    });

    $('#seo-export-404-logs').on('click', function() {
        window.location.href = seo404Monitor.ajax_url + '?action=seo_export_404_logs_csv&nonce=' + encodeURIComponent(seo404Monitor.nonce);
    });

    $('.seo-modal-close, .seo-modal').on('click', function(e) {
        if (e.target === this) {
            $('.seo-modal').fadeOut();
        }
    });

});
