/**
 * GeoBot Admin JS — City import, batch trigger, live progress, history reset
 * Works for ALL countries via data-country attribute.
 * @since 2.8.0
 */
(function($) {
    'use strict';

    var pollingIntervals = {};

    /* =================================================================
     *  CITY IMPORT — Paste & parse
     * ================================================================= */

    $(document).on('click', '.dba-geo-import-cities', function(e) {
        e.preventDefault();
        var btn = $(this);
        var countryKey = btn.data('country');
        var $textarea = $('#dba-geo-paste-cities-' + countryKey);
        var $result   = $('.dba-geo-import-result-' + countryKey);
        var mode      = $('input[name="dba_geo_import_mode_' + countryKey + '"]:checked').val() || 'replace';

        var text = $textarea.val().trim();
        if (!text) {
            $result.show().css({'background':'#fff3cd','border':'1px solid #ffc107','color':'#856404'})
                .text('⚠️ Paste your city list first.');
            return;
        }

        if (mode === 'replace') {
            var lineCount = text.split('\n').filter(function(l) { return l.trim() !== ''; }).length;
            if (!confirm('Replace ALL existing cities with ' + lineCount + ' new lines?\n\nThis cannot be undone.')) return;
        }

        btn.prop('disabled', true).text('⏳ Importing…');
        $result.show().css({'background':'#e8f4fd','border':'1px solid #b8d4e3','color':'#1565c0'})
            .text('Processing…');

        $.ajax({
            url: dba_geo.ajaxurl,
            type: 'POST',
            data: {
                action: 'dba_geo_import_cities',
                nonce: dba_geo.nonce,
                country_key: countryKey,
                cities_text: text,
                import_mode: mode
            },
            timeout: 30000,
            success: function(resp) {
                btn.prop('disabled', false).text('📥 Import Cities');
                if (resp.success && resp.data) {
                    $result.css({'background':'#e8f5e9','border':'1px solid #a5d6a7','color':'#2e7d32'})
                        .html('✅ ' + resp.data.message +
                            (resp.data.sample ? '<br><small>Preview: ' + resp.data.sample.join(', ') + (resp.data.count > 10 ? '…' : '') + '</small>' : ''));
                    setTimeout(function() { location.reload(); }, 2500);
                } else {
                    $result.css({'background':'#ffebee','border':'1px solid #ef9a9a','color':'#c62828'})
                        .text('❌ ' + (resp.data || 'Import failed'));
                }
            },
            error: function(xhr, status) {
                btn.prop('disabled', false).text('📥 Import Cities');
                $result.css({'background':'#ffebee','border':'1px solid #ef9a9a','color':'#c62828'})
                    .text('❌ Error: ' + status);
            }
        });
    });

    /* =================================================================
     *  RESET HISTORY — Clear dedupe rotation
     * ================================================================= */

    $(document).on('click', '.dba-geo-reset-history', function(e) {
        e.preventDefault();
        var btn = $(this);
        var countryKey = btn.data('country');

        if (!confirm('Reset dedupe history for ' + countryKey.toUpperCase() + '?\n\nAll communes will become available again. Published posts are NOT deleted.')) return;

        btn.prop('disabled', true);

        $.ajax({
            url: dba_geo.ajaxurl,
            type: 'POST',
            data: {
                action: 'dba_geo_reset_history',
                nonce: dba_geo.nonce,
                country_key: countryKey
            },
            success: function(resp) {
                if (resp.success) {
                    alert('✅ ' + (resp.data.message || 'History cleared.'));
                    location.reload();
                } else {
                    alert('❌ ' + (resp.data || 'Failed'));
                    btn.prop('disabled', false);
                }
            },
            error: function() {
                alert('❌ Network error');
                btn.prop('disabled', false);
            }
        });
    });

    /* =================================================================
     *  HUB PAGE — Create / update pillar page
     * ================================================================= */

    $(document).on('click', '.dba-geo-update-hub', function(e) {
        e.preventDefault();
        var btn = $(this);
        var countryKey = btn.data('country');
        var $result = $('.dba-geo-link-result-' + countryKey);

        btn.prop('disabled', true).text('⏳ Updating hub…');
        $result.text('').show();

        $.ajax({
            url: dba_geo.ajaxurl,
            type: 'POST',
            data: {
                action: 'dba_geo_update_hub',
                nonce: dba_geo.nonce,
                country_key: countryKey
            },
            timeout: 60000,
            success: function(resp) {
                btn.prop('disabled', false).text('📄 Update Hub Page');
                if (resp.success && resp.data) {
                    $result.html('✅ ' + resp.data.message + ' — <a href="' + resp.data.permalink + '" target="_blank">View hub page</a>');
                    setTimeout(function() { location.reload(); }, 2000);
                } else {
                    $result.text('❌ ' + (resp.data || 'Failed'));
                }
            },
            error: function(xhr, status) {
                btn.prop('disabled', false).text('📄 Update Hub Page');
                $result.text('❌ Error: ' + status);
            }
        });
    });

    /* =================================================================
     *  RETROACTIVE LINKING — Fix orphan posts
     * ================================================================= */

    $(document).on('click', '.dba-geo-retroactive-link', function(e) {
        e.preventDefault();
        var btn = $(this);
        var countryKey = btn.data('country');
        var $result = $('.dba-geo-link-result-' + countryKey);

        if (!confirm('This will scan ALL existing ' + countryKey.toUpperCase() + ' GeoBot posts and inject cross-links.\n\nExisting links will be refreshed. Continue?')) return;

        btn.prop('disabled', true).text('⏳ Linking posts…');
        $result.text('Processing — this may take a minute…').show();

        $.ajax({
            url: dba_geo.ajaxurl,
            type: 'POST',
            data: {
                action: 'dba_geo_retroactive_link',
                nonce: dba_geo.nonce,
                country_key: countryKey
            },
            timeout: 300000,
            success: function(resp) {
                btn.prop('disabled', false).text('🔗 Fix All Orphan Posts');
                if (resp.success && resp.data) {
                    var d = resp.data;
                    $result.html('✅ Done! Updated: ' + d.updated + ' | Skipped: ' + d.skipped + ' | Errors: ' + d.errors + ' | Hub: ' + d.hub_page);
                    setTimeout(function() { location.reload(); }, 2500);
                } else {
                    $result.text('❌ ' + (resp.data || 'Failed'));
                }
            },
            error: function(xhr, status) {
                btn.prop('disabled', false).text('🔗 Fix All Orphan Posts');
                $result.text('❌ Error: ' + status);
            }
        });
    });

    /* =================================================================
     *  BATCH TRIGGER — Generate posts
     * ================================================================= */

    $(document).on('click', '.dba-geo-run-batch', function(e) {
        e.preventDefault();
        var btn = $(this);
        var countryKey = btn.data('country');

        if (!countryKey) return;
        if (!confirm('Run the ' + countryKey.toUpperCase() + ' GeoBot batch now?\n\nFull plagiarism detection pipeline is active.')) return;

        var $progress = $('.dba-geo-progress[data-country="' + countryKey + '"]');
        var $bar      = $progress.find('.dba-geo-progress-bar');
        var $label    = $progress.find('.dba-geo-progress-label');
        var $detail   = $progress.find('.dba-geo-progress-detail');

        btn.prop('disabled', true).text('⏳ Running…');
        $progress.slideDown();
        $bar.css({'width': '5%', 'background': '#28a745'});
        $label.text('Starting batch…');

        pollingIntervals[countryKey] = setInterval(function() {
            pollGeoProgress(countryKey);
        }, 3000);

        $.ajax({
            url: dba_geo.ajaxurl,
            type: 'POST',
            data: {
                action: 'dba_geo_generate_batch',
                nonce: dba_geo.nonce,
                country_key: countryKey
            },
            timeout: 900000,
            success: function(resp) {
                clearInterval(pollingIntervals[countryKey]);
                btn.prop('disabled', false).text('🚀 Run Batch Now');
                $bar.css('width', '100%');

                if (resp.success && resp.data) {
                    var d = resp.data;
                    $label.text('✅ Batch complete!');
                    $detail.text(
                        'Created: ' + (d.created || 0) +
                        ' | Failed: ' + (d.failed || 0)
                    );
                } else {
                    $label.text('⚠️ Batch ended with issues');
                }
            },
            error: function(xhr, status) {
                clearInterval(pollingIntervals[countryKey]);
                btn.prop('disabled', false).text('🚀 Run Batch Now');
                $label.text('❌ Error: ' + status);
                $bar.css({'width': '100%', 'background': '#dc3545'});
            }
        });
    });

    function pollGeoProgress(countryKey) {
        var $progress = $('.dba-geo-progress[data-country="' + countryKey + '"]');
        var $bar      = $progress.find('.dba-geo-progress-bar');
        var $label    = $progress.find('.dba-geo-progress-label');
        var $detail   = $progress.find('.dba-geo-progress-detail');

        $.ajax({
            url: dba_geo.ajaxurl,
            type: 'POST',
            data: {
                action: 'dba_geo_get_progress',
                nonce: dba_geo.nonce,
                country_key: countryKey
            },
            success: function(resp) {
                if (!resp.success || !resp.data) return;
                var p = resp.data;
                var total = p.total_posts || 1;
                var done  = (p.completed || 0) + (p.failed || 0);
                var pct   = Math.min(95, Math.round((done / total) * 100));

                $bar.css('width', pct + '%');

                var stepLabel = p.current_step_name || '…';
                if (stepLabel === 'plagiarism') stepLabel = '🛡️ Plagiarism check';
                if (stepLabel === 'validate')   stepLabel = '🔍 Validation gates';

                $label.text(
                    'Post ' + (p.current_post || '?') + '/' + total +
                    ' — ' + stepLabel
                );
                $detail.text(p.current_detail || '');

                if (p.current_status === 'complete') {
                    clearInterval(pollingIntervals[countryKey]);
                    $bar.css('width', '100%');
                }
            }
        });
    }

})(jQuery);
