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

    if (typeof seoIndexNow === 'undefined' && typeof seoRedirects === 'undefined') {
        console.warn('SEO Plugin: IndexNow scripts not loaded properly');
        return;
    }

    const ajaxConfig = typeof seoIndexNow !== 'undefined' ? seoIndexNow : (typeof seoRedirects !== 'undefined' ? seoRedirects : {
        ajax_url: ajaxurl,
        nonce: ''
    });

    // Escape user-controlled values before injecting into the history table.
    // Submitted URLs are stored from the manual-submit textarea and rendered
    // back as HTML, 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;');
    }

    $('#submit-indexnow-btn').on('click', function(e) {
        e.preventDefault();

        const urls = $('#indexnow-urls').val().trim();
        if (!urls) {
            alert(seoIndexNow.i18n.enterUrl);
            return;
        }

        let urlList = urls.split('\n')
            .map(url => url.trim())
            .filter(url => url.length > 0);

        if (urlList.length === 0) {
            alert(seoIndexNow.i18n.noValidUrls);
            return;
        }

        if (urlList.length > 10000) {
            alert(seoIndexNow.i18n.maxUrls + ' ' + urlList.length);
            return;
        }

        const useBatching = $('#indexnow-batch-mode').is(':checked');
        const batchSize = parseInt($('#indexnow-batch-size').val()) || 100;

        if (useBatching && urlList.length > batchSize) {
            submitInBatches(urlList, batchSize);
        } else {
            submitSingleBatch(urlList);
        }
    });

    // Submit every published sitemap URL to IndexNow (loaded server-side, then
    // submitted in batches via the existing flow).
    $('#submit-indexnow-sitemap-btn').on('click', function(e) {
        e.preventDefault();
        var btn = $(this);
        var orig = btn.text();
        btn.prop('disabled', true).text(seoIndexNow.i18n.loadingSitemap || 'Loading sitemap URLs…');
        $('#indexnow-submit-result').hide();

        $.ajax({
            url: ajaxConfig.ajax_url,
            type: 'POST',
            data: { action: 'seo_fury_indexnow_sitemap_urls', nonce: ajaxConfig.nonce },
            success: function(response) {
                if (response.success && response.data && response.data.urls && response.data.urls.length) {
                    var urlList = response.data.urls;
                    var batchSize = parseInt($('#indexnow-batch-size').val(), 10) || 100;
                    if (urlList.length > batchSize) {
                        submitInBatches(urlList, batchSize);
                    } else {
                        submitSingleBatch(urlList);
                    }
                } else {
                    $('#indexnow-submit-result').removeClass('success').addClass('error').show()
                        .html('<strong>❌ ' + (seoIndexNow.i18n.noSitemapUrls || 'No URLs found in the sitemap.') + '</strong>');
                }
            },
            error: function() {
                $('#indexnow-submit-result').removeClass('success').addClass('error').show()
                    .html('<strong>❌ ' + seoIndexNow.i18n.serverError + '</strong>');
            },
            complete: function() {
                btn.prop('disabled', false).text(orig);
            }
        });
    });

    function submitSingleBatch(urls) {
        const btn = $('#submit-indexnow-btn');
        const originalText = btn.text();
        btn.prop('disabled', true).text(seoIndexNow.i18n.sending);

        $.ajax({
            url: ajaxConfig.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_submit_indexnow',
                nonce: ajaxConfig.nonce,
                urls: urls.join('\n')
            },
            success: function(response) {
                if (response.success) {
                    $('#indexnow-submit-result')
                        .removeClass('error')
                        .addClass('success')
                        .html('<strong>✅ ' + seoIndexNow.i18n.success + '</strong><br>' + seoIndexNow.i18n.urlsSent + ' ' + urls.length);
                    $('#indexnow-urls').val('');

                    if (typeof loadIndexNowHistory === 'function') {
                        loadIndexNowHistory();
                    }
                } else {
                    $('#indexnow-submit-result')
                        .removeClass('success')
                        .addClass('error')
                        .html('<strong>❌ ' + seoIndexNow.i18n.error + '</strong><br>').append($('<span>').text(response.data || seoIndexNow.i18n.unknownError));
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error:', error);
                $('#indexnow-submit-result')
                    .removeClass('success')
                    .addClass('error')
                    .html('<strong>❌ ' + seoIndexNow.i18n.serverError + '</strong>');
            },
            complete: function() {
                btn.prop('disabled', false).text(originalText);
            }
        });
    }

    function submitInBatches(urls, batchSize) {
        const totalBatches = Math.ceil(urls.length / batchSize);
        let currentBatch = 0;
        let successCount = 0;
        let errorCount = 0;

        const btn = $('#submit-indexnow-btn');
        const originalText = btn.text();
        btn.prop('disabled', true).text(seoIndexNow.i18n.sendingBatches);

        $('#indexnow-progress').show();
        $('#indexnow-submit-result').hide();

        function sendNextBatch() {
            if (currentBatch >= totalBatches) {
                finishBatching();
                return;
            }

            const start = currentBatch * batchSize;
            const end = Math.min(start + batchSize, urls.length);
            const batchUrls = urls.slice(start, end);

            const progress = Math.round(((currentBatch + 1) / totalBatches) * 100);
            $('#indexnow-progress-bar').css('width', progress + '%');
            $('#indexnow-progress-text').text(progress + '%');
            $('#indexnow-progress-status').text(
                seoIndexNow.i18n.sendingBatch + ' ' + (currentBatch + 1) + ' ' + seoIndexNow.i18n.of + ' ' + totalBatches +
                ' (' + batchUrls.length + ' URL)...'
            );

            $.ajax({
                url: ajaxConfig.ajax_url,
                type: 'POST',
                data: {
                    action: 'seo_submit_indexnow',
                    nonce: ajaxConfig.nonce,
                    urls: batchUrls.join('\n')
                },
                success: function(response) {
                    if (response.success) {
                        successCount += batchUrls.length;
                    } else {
                        errorCount += batchUrls.length;
                    }
                },
                error: function() {
                    errorCount += batchUrls.length;
                },
                complete: function() {
                    currentBatch++;
                    if (currentBatch < totalBatches) {
                        setTimeout(sendNextBatch, 2000);
                    } else {
                        finishBatching();
                    }
                }
            });
        }

        function finishBatching() {
            $('#indexnow-progress').hide();
            $('#indexnow-submit-result').show();

            if (errorCount === 0) {
                $('#indexnow-submit-result')
                    .removeClass('error')
                    .addClass('success')
                    .html(
                        '<strong>✅ ' + seoIndexNow.i18n.allBatchesSent + '</strong><br>' +
                        seoIndexNow.i18n.totalUrls + ' ' + urls.length + '<br>' +
                        seoIndexNow.i18n.batches + ' ' + totalBatches + '<br>' +
                        seoIndexNow.i18n.success + ': ' + successCount
                    );
                $('#indexnow-urls').val('');

                if (typeof loadIndexNowHistory === 'function') {
                    loadIndexNowHistory();
                }
            } else {
                $('#indexnow-submit-result')
                    .removeClass('success')
                    .addClass('error')
                    .html(
                        '<strong>⚠️ ' + seoIndexNow.i18n.completedWithErrors + '</strong><br>' +
                        seoIndexNow.i18n.success + ': ' + successCount + '<br>' +
                        seoIndexNow.i18n.errors + ' ' + errorCount
                    );
            }

            btn.prop('disabled', false).text(originalText);
        }

        sendNextBatch();
    }

    $('#save-settings-btn').on('click', function(e) {
        e.preventDefault();
        const autoSubmit = $('#indexnow-auto-submit').is(':checked') ? 1 : 0;
        const postTypes = [];
        $('input[name="indexnow_post_types[]"]:checked').each(function() {
            postTypes.push($(this).val());
        });

        const btn = $(this);
        const originalText = btn.text();
        btn.prop('disabled', true).text(seoIndexNow.i18n.saving);

        $.ajax({
            url: ajaxConfig.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_save_indexnow_settings',
                nonce: ajaxConfig.nonce,
                auto_submit: autoSubmit,
                post_types: postTypes
            },
            success: function(response) {
                if (response.success) {
                    alert('✅ ' + seoIndexNow.i18n.settingsSaved);
                } else {
                    alert('❌ ' + (response.data || seoIndexNow.i18n.saveError));
                }
            },
            error: function() {
                alert('❌ ' + seoIndexNow.i18n.serverError);
            },
            complete: function() {
                btn.prop('disabled', false).text(originalText);
            }
        });
    });

    $('#generate-indexnow-key').on('click', function(e) {
        e.preventDefault();
        const btn = $(this);
        const originalText = btn.text();
        btn.prop('disabled', true).text(seoIndexNow.i18n.generating);

        $.ajax({
            url: ajaxConfig.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_generate_indexnow_key',
                nonce: ajaxConfig.nonce
            },
            success: function(response) {
                if (response.success) {
                    $('input[name="seo_fury_indexnow_api_key"]').val(response.data.key);

                    if ($('#verify-indexnow-key').length === 0) {
                        btn.after(' <button type="button" class="button" id="verify-indexnow-key">' + seoIndexNow.i18n.verifyKey + '</button>');
                    }

                    $('#indexnow-key-status')
                        .removeClass('error')
                        .addClass('success')
                        .html('<strong>✅ ' + seoIndexNow.i18n.keyGenerated + '</strong><br>File: ').append($('<code>').text(response.data.file)).append('<br>URL: ').append($('<a>').attr({href: response.data.url, target: '_blank'}).text(response.data.url));
                } else {
                    $('#indexnow-key-status')
                        .removeClass('success')
                        .addClass('error')
                        .html('<strong>❌ ' + seoIndexNow.i18n.error + ':</strong> ').append($('<span>').text(response.data));
                }
            },
            error: function(xhr, status, error) {
                console.error('Key generation error:', error);
                $('#indexnow-key-status')
                    .removeClass('success')
                    .addClass('error')
                    .html('<strong>❌ ' + seoIndexNow.i18n.serverError + '</strong>');
            },
            complete: function() {
                btn.prop('disabled', false).text(originalText);
            }
        });
    });

    $(document).on('click', '#verify-indexnow-key', function(e) {
        e.preventDefault();
        const btn = $(this);
        const originalText = btn.text();
        btn.prop('disabled', true).text(seoIndexNow.i18n.checking);

        $.ajax({
            url: ajaxConfig.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_verify_indexnow_key',
                nonce: ajaxConfig.nonce
            },
            success: function(response) {
                if (response.success) {
                    $('#indexnow-key-status')
                        .removeClass('error')
                        .addClass('success')
                        .html('<strong>✅ </strong>').append($('<strong>').text(response.data.message)).append('<br>URL: ').append($('<a>').attr({href: response.data.url, target: '_blank'}).text(response.data.url));
                } else {
                    $('#indexnow-key-status')
                        .removeClass('success')
                        .addClass('error')
                        .html('<strong>❌ ' + seoIndexNow.i18n.error + ':</strong> ').append($('<span>').text(response.data));
                }
            },
            error: function() {
                $('#indexnow-key-status')
                    .removeClass('success')
                    .addClass('error')
                    .html('<strong>❌ ' + seoIndexNow.i18n.serverError + '</strong>');
            },
            complete: function() {
                btn.prop('disabled', false).text(originalText);
            }
        });
    });

    function loadIndexNowHistory() {
        $.ajax({
            url: ajaxConfig.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_load_indexnow_history',
                nonce: ajaxConfig.nonce
            },
            success: function(response) {
                if (response.success && response.data) {
                    const history = response.data;
                    const tbody = $('#indexnow-history-table tbody');
                    tbody.empty();

                    if (history.length === 0) {
                        tbody.html('<tr><td colspan="4" style="text-align: center;">' + seoIndexNow.i18n.noHistoryYet + '</td></tr>');
                    } else {
                        history.forEach(function(item) {
                            const statusColor = item.response_code >= 200 && item.response_code < 300 ? 'green' : 'red';
                            const methodBadge = item.method === 'auto_publish' ? '<span style="background: #2271b1; color: white; padding: 2px 6px; border-radius: 3px; font-size: 11px;">' + seoIndexNow.i18n.auto + '</span>' : '<span style="background: var(--sf-gray-200, #ddd); color: var(--sf-gray-700, #333); padding: 2px 6px; border-radius: 3px; font-size: 11px;">' + seoIndexNow.i18n.manual + '</span>';

                            tbody.append(
                                '<tr>' +
                                '<td>' + escapeHtml(item.submitted_at) + '</td>' +
                                '<td style="word-break: break-all;">' + escapeHtml(item.url) + '</td>' +
                                '<td><span style="color: ' + statusColor + '; font-weight: bold;">' + escapeHtml(item.response_code || seoIndexNow.i18n.notAvailable) + '</span></td>' +
                                '<td>' + methodBadge + '</td>' +
                                '</tr>'
                            );
                        });
                    }
                }
            }
        });
    }

    $('#load-indexnow-history-btn').on('click', function() {
        loadIndexNowHistory();
    });

    $('#clear-indexnow-history-btn').on('click', function() {
        if (!confirm(seoIndexNow.i18n.confirmClearHistory)) {
            return;
        }

        $.ajax({
            url: ajaxConfig.ajax_url,
            type: 'POST',
            data: {
                action: 'seo_clear_indexnow_history',
                nonce: ajaxConfig.nonce
            },
            success: function(response) {
                if (response.success) {
                    loadIndexNowHistory();
                    alert('✅ ' + seoIndexNow.i18n.historyCleared);
                } else {
                    alert('❌ ' + seoIndexNow.i18n.clearFailed);
                }
            }
        });
    });

    if ($('#indexnow-history-table').length) {
        loadIndexNowHistory();
    }

});
