jQuery(document).ready(function($) {
    
    if (typeof seoRedirects === 'undefined') {
        console.warn('SEO Plugin: Redirects scripts not loaded properly');
        return;
    }

    // Escape user-controlled values before injecting into HTML / attributes.
    // Redirect source/target may contain markup (esp. regex rules and values
    // imported from 404 logs), so unescaped output is a stored-XSS vector.
    function escapeHtml(str) {
        return String(str)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    loadRedirects();
    
    function loadRedirects() {
        $.ajax({
            url: seoRedirects.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_load_redirects',
                nonce: seoRedirects.nonce
            },
            beforeSend: function() {
                $('#redirects-table tbody').html('<tr><td colspan="8" style="text-align: center;">' + seoRedirects.i18n.loading + '</td></tr>');
            },
            success: function(response) {
                if (response.success) {
                    var redirects = response.data.redirects;
                    var html = '';
                    
                    if (redirects.length === 0) {
                        html = '<tr><td colspan="8" style="text-align: center;">' + seoRedirects.i18n.noRedirectsFound + '</td></tr>';
                    } else {
                        $.each(redirects, function(index, redirect) {
                            var targetUrl = redirect.target_url || 'N/A';
                            var sourceUrl = redirect.source_url || 'N/A';
                            var redirectType = redirect.redirect_type || '301';
                            var hits = redirect.hits || '0';
                            
                            var isActive = (redirect.active === "1" || redirect.active === 1);
                            
                            var statusBadge = isActive
                                ? '<span style="color: #00a32a; font-weight: 600;">&#10003; ' + seoRedirects.i18n.active + '</span>'
                                : '<span style="color: #d63638; font-weight: 600;">&#10005; ' + seoRedirects.i18n.inactive + '</span>';
                            
                            var createdDate = 'N/A';
                            if (redirect.created && redirect.created !== '0000-00-00 00:00:00') {
                                try {
                                    var date = new Date(redirect.created.replace(' ', 'T'));
                                    createdDate = date.toLocaleString('en-US', {
                                        year: 'numeric',
                                        month: '2-digit',
                                        day: '2-digit',
                                        hour: '2-digit',
                                        minute: '2-digit'
                                    });
                                } catch(e) {
                                    createdDate = redirect.created;
                                }
                            }
                            
                            var isRegex = redirect.is_regex == 1;
                            var regexBadge = isRegex ? ' <span style="background:#7c3aed;color:#fff;font-size:10px;padding:1px 5px;border-radius:3px;font-weight:600;">Regex</span>' : '';

                            var sourceUrlEsc = escapeHtml(sourceUrl);
                            var targetUrlEsc = escapeHtml(targetUrl);

                            html += '<tr>';
                            html += '<td>' + parseInt(redirect.id, 10) + '</td>';
                            html += '<td><code>' + sourceUrlEsc + '</code>' + regexBadge + '</td>';
                            html += '<td><code>' + targetUrlEsc + '</code></td>';
                            html += '<td>' + escapeHtml(redirectType) + '</td>';
                            html += '<td>' + escapeHtml(hits) + '</td>';
                            html += '<td>' + createdDate + '</td>';
                            html += '<td>' + statusBadge + '</td>';
                            html += '<td class="redirect-actions">';
                            html += '<button class="button button-small sf-icon-btn edit-redirect" data-id="' + parseInt(redirect.id, 10) + '" data-source="' + sourceUrlEsc + '" data-target="' + targetUrlEsc + '" data-type="' + escapeHtml(redirectType) + '" data-regex="' + (isRegex ? '1' : '0') + '" title="' + escapeHtml(seoRedirects.i18n.edit) + '" aria-label="' + escapeHtml(seoRedirects.i18n.edit) + '">✏️</button> ';

                            var toggleText = isActive ? seoRedirects.i18n.deactivate : seoRedirects.i18n.activate;
                            var toggleValue = isActive ? 0 : 1;
                            var toggleIcon = isActive ? '⏸️' : '▶️';
                            html += '<button class="button button-small sf-icon-btn toggle-redirect" data-id="' + redirect.id + '" data-active="' + toggleValue + '" title="' + escapeHtml(toggleText) + '" aria-label="' + escapeHtml(toggleText) + '">' + toggleIcon + '</button> ';

                            html += '<button class="button button-small sf-icon-btn delete-redirect" data-id="' + redirect.id + '" style="color: #d63638;" title="' + escapeHtml(seoRedirects.i18n.delete) + '" aria-label="' + escapeHtml(seoRedirects.i18n.delete) + '">🗑️</button>';
                            html += '</td>';
                            html += '</tr>';
                        });
                    }
                    
                    $('#redirects-table tbody').html(html);
                } else {
                    var errorMsg = response.data && response.data.message ? response.data.message : seoRedirects.i18n.errorLoading;
                    $('#redirects-table tbody').html('<tr><td colspan="8" style="text-align: center; color: #d63638;">' + errorMsg + '</td></tr>');
                }
            },
            error: function() {
                $('#redirects-table tbody').html('<tr><td colspan="8" style="text-align: center; color: #d63638;">' + seoRedirects.i18n.errorLoadingData + '</td></tr>');
            }
        });
    }
    
    $('#add-redirect-btn').on('click', function() {
        var source = $('#redirect-source').val().trim();
        var target = $('#redirect-target').val().trim();
        var type = $('#redirect-type').val();
        var is_regex = $('#redirect-is-regex').is(':checked') ? 1 : 0;

        if (!source || !target) {
            alert(seoRedirects.i18n.fillAllFields);
            return;
        }

        var btn = $(this);
        var originalText = btn.text();

        btn.prop('disabled', true).text(seoRedirects.i18n.adding);

        $.ajax({
            url: seoRedirects.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_add_redirect',
                nonce: seoRedirects.nonce,
                source: source,
                target: target,
                type: type,
                is_regex: is_regex
            },
            success: function(response) {
                if (response.success) {
                    var message = response.data && typeof response.data === 'string' ? response.data : seoRedirects.i18n.redirectAdded;
                    alert(message);
                    $('#redirect-source').val('');
                    $('#redirect-target').val('');
                    $('#redirect-type').val('301');
                    loadRedirects();
                } else {
                    var errorMessage = typeof response.data === 'string' ? response.data : (response.data && response.data.message ? response.data.message : seoRedirects.i18n.anErrorOccurred);
                    alert(seoRedirects.i18n.errorPrefix + ' ' + errorMessage);
                }
            },
            error: function() {
                alert(seoRedirects.i18n.errorAdding);
            },
            complete: function() {
                btn.prop('disabled', false).text(originalText);
            }
        });
    });

    $('#seo-export-redirects').on('click', function() {
        var url = seoRedirects.ajax_url + '?action=seo_export_redirects_csv&nonce=' + encodeURIComponent(seoRedirects.nonce);
        window.location.href = url;
    });

    $('#seo-import-redirects').on('click', function() {
        var fileInput = $('#seo-import-redirects-file')[0];
        var resultBox = $('#seo-import-redirects-result');
        if (!fileInput.files.length) {
            alert(seoRedirects.i18n.selectCsvFile);
            return;
        }

        var formData = new FormData();
        formData.append('action', 'seo_import_redirects_csv');
        formData.append('nonce', seoRedirects.nonce);
        formData.append('file', fileInput.files[0]);

        resultBox.html('');
        $.ajax({
            url: seoRedirects.ajax_url,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    var msg = seoRedirects.i18n.imported + ': ' + response.data.imported +
                              ', ' + seoRedirects.i18n.updated + ': ' + response.data.updated +
                              ', ' + seoRedirects.i18n.skipped + ': ' + response.data.skipped;
                    resultBox.html('<div class="seo-alert success"><strong>✅ ' + seoRedirects.i18n.csvImportCompleted + '</strong><br>' + msg + '</div>');
                    loadRedirects();
                } else {
                    resultBox.html('<div class="seo-alert error"><strong>❌ ' + seoRedirects.i18n.error + ':</strong> ' + response.data + '</div>');
                }
            },
            error: function() {
                resultBox.html('<div class="seo-alert error"><strong>❌ ' + seoRedirects.i18n.error + ':</strong> ' + seoRedirects.i18n.uploadFailed + '</div>');
            }
        });
    });
    
    $(document).on('click', '.delete-redirect', function() {
        if (!confirm(seoRedirects.i18n.confirmDelete)) {
            return;
        }
        
        var id = $(this).data('id');
        var btn = $(this);
        
        btn.prop('disabled', true).css('opacity', 0.5);

        $.ajax({
            url: seoRedirects.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_delete_redirect',
                nonce: seoRedirects.nonce,
                id: id
            },
            success: function(response) {
                if (response.success) {
                    alert(seoRedirects.i18n.redirectDeleted);
                    loadRedirects();
                } else {
                    alert(seoRedirects.i18n.errorPrefix + ' ' + response.data);
                    btn.prop('disabled', false).css('opacity', 1);
                }
            },
            error: function() {
                alert(seoRedirects.i18n.errorDeleting);
                btn.prop('disabled', false).css('opacity', 1);
            }
        });
    });
    
    $(document).on('click', '.toggle-redirect', function() {
        var id = $(this).data('id');
        var active = $(this).data('active');
        var btn = $(this);
        
        btn.prop('disabled', true).css('opacity', 0.5);

        $.ajax({
            url: seoRedirects.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_toggle_redirect',
                nonce: seoRedirects.nonce,
                id: id,
                active: active
            },
            success: function(response) {
                if (response.success) {
                    loadRedirects();
                } else {
                    alert(seoRedirects.i18n.errorPrefix + ' ' + response.data);
                    btn.prop('disabled', false);
                }
            },
            error: function() {
                alert(seoRedirects.i18n.errorUpdatingStatus);
                btn.prop('disabled', false);
            }
        });
    });
    
    $(document).on('click', '.edit-redirect', function() {
        var id = $(this).data('id');
        var source = $(this).data('source');
        var target = $(this).data('target');
        var type = $(this).data('type');
        var isRegex = $(this).data('regex') == '1';

        $('#edit-redirect-id').val(id);
        $('#edit-redirect-source').val(source);
        $('#edit-redirect-target').val(target);
        $('#edit-redirect-type').val(type);
        $('#edit-redirect-is-regex').prop('checked', isRegex);

        $('#edit-redirect-modal').fadeIn();
    });
    
    $('.seo-modal-close, .seo-modal').on('click', function(e) {
        if (e.target === this) {
            $('#edit-redirect-modal').fadeOut();
        }
    });
    
    $('#update-redirect-btn').on('click', function() {
        var id = $('#edit-redirect-id').val();
        var source = $('#edit-redirect-source').val().trim();
        var target = $('#edit-redirect-target').val().trim();
        var type = $('#edit-redirect-type').val();
        var is_regex = $('#edit-redirect-is-regex').is(':checked') ? 1 : 0;

        if (!source || !target) {
            alert(seoRedirects.i18n.fillAllFields);
            return;
        }

        var btn = $(this);
        var originalText = btn.text();

        btn.prop('disabled', true).text(seoRedirects.i18n.saving);
        
        $.ajax({
            url: seoRedirects.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_update_redirect',
                nonce: seoRedirects.nonce,
                id: id,
                source: source,
                target: target,
                type: type,
                is_regex: is_regex
            },
            success: function(response) {
                if (response.success) {
                    alert(seoRedirects.i18n.redirectUpdated);
                    $('#edit-redirect-modal').fadeOut();
                    loadRedirects();
                } else {
                    alert(seoRedirects.i18n.errorPrefix + ' ' + response.data);
                }
            },
            error: function() {
                alert(seoRedirects.i18n.errorUpdating);
            },
            complete: function() {
                btn.prop('disabled', false).text(originalText);
            }
        });
    });

    // Redirect tester — dry-run the matcher without redirecting.
    function runRedirectTest() {
        var url = $('#seo-test-redirect-url').val().trim();
        var $result = $('#seo-test-redirect-result');
        if (!url) {
            $result.html('<div class="seo-alert error">' + seoRedirects.i18n.testEnterUrl + '</div>');
            return;
        }
        var btn = $('#seo-test-redirect-btn');
        var orig = btn.text();
        btn.prop('disabled', true).text(seoRedirects.i18n.testing);
        $.ajax({
            url: seoRedirects.ajax_url,
            type: 'POST',
            data: { action: 'seo_test_redirect', nonce: seoRedirects.nonce, url: url },
            success: function(response) {
                if (response.success && response.data && response.data.matched) {
                    var d = response.data;
                    var typeLabel = d.type === 'regex' ? seoRedirects.i18n.testRegexMatch : seoRedirects.i18n.testExactMatch;
                    $result.html(
                        '<div class="seo-alert success">' +
                        '<strong>' + typeLabel + '</strong><br>' +
                        seoRedirects.i18n.testRule + ': <code>' + escapeHtml(d.source) + '</code><br>' +
                        seoRedirects.i18n.testWouldRedirect + ': <code>' + escapeHtml(d.target) + '</code> ' +
                        '(' + seoRedirects.i18n.testStatus + ' ' + escapeHtml(d.status) + ')' +
                        '</div>'
                    );
                } else if (response.success) {
                    $result.html('<div class="seo-alert">' + seoRedirects.i18n.testNoMatch + '</div>');
                } else {
                    var msg = (response.data && response.data.message) ? response.data.message : seoRedirects.i18n.error;
                    $result.html('<div class="seo-alert error">' + escapeHtml(msg) + '</div>');
                }
            },
            error: function() {
                $result.html('<div class="seo-alert error">' + seoRedirects.i18n.error + '</div>');
            },
            complete: function() {
                btn.prop('disabled', false).text(orig);
            }
        });
    }

    $('#seo-test-redirect-btn').on('click', runRedirectTest);
    $('#seo-test-redirect-url').on('keypress', function(e) {
        if (e.which === 13) { e.preventDefault(); runRedirectTest(); }
    });

});
