/**
 * PE NewsBot Admin JS — Per-post batch trigger + live progress + STOP
 * @since 2.7.0
 */
(function($) {
    'use strict';

    var polling = null;
    var stopped = false;
    var batchState = { created: 0, failed: 0, target: 0 };
    var $runBtn = $('#dba-pe-run-batch');
    var $stopBtn = $('#dba-pe-stop-batch');

    $runBtn.on('click', function(e) {
        e.preventDefault();
        if (!confirm('Run the PE News Batch now? This will generate individual posts + roundup.')) return;

        stopped = false;
        $runBtn.prop('disabled', true).text('⏳ Starting…');
        $stopBtn.prop('disabled', false).css('opacity', '1');

        $('#dba-pe-progress').slideDown();
        $('#dba-pe-progress-bar').css({'width': '2%', 'background': '#28a745'});
        $('#dba-pe-progress-label').text('Initializing batch…');
        $('#dba-pe-progress-detail').text('');

        batchState = { created: 0, failed: 0, target: 0 };

        $.ajax({
            url: dba_pe.ajaxurl,
            type: 'POST',
            data: { action: 'dba_pe_init_batch', nonce: dba_pe.nonce },
            timeout: 30000,
            success: function(resp) {
                if (stopped) { batchStopped(); return; }
                if (!resp.success) {
                    batchError(resp.data ? resp.data.message : 'Init failed');
                    return;
                }
                batchState.target = resp.data.posts_target || 1;
                $('#dba-pe-progress-label').text('Generating ' + batchState.target + ' posts…');
                $('#dba-pe-progress-bar').css('width', '5%');
                generateNextPost(1);
            },
            error: function(xhr, status) {
                batchError('Init request failed: ' + status);
            }
        });
    });

    $stopBtn.on('click', function(e) {
        e.preventDefault();
        stopped = true;
        $(this).prop('disabled', true).text('⛔ Stopping…');
        $('#dba-pe-progress-label').text('⛔ Stopping after current post finishes…');
    });

    function generateNextPost(postIndex) {
        if (stopped) { batchStopped(); return; }

        if (postIndex > batchState.target) {
            finishRoundup();
            return;
        }

        var pct = Math.round(5 + (postIndex / (batchState.target + 1)) * 85);
        $('#dba-pe-progress-bar').css('width', pct + '%');
        $('#dba-pe-progress-label').text('Post ' + postIndex + '/' + batchState.target + ' — generating…');

        if (polling) clearInterval(polling);
        polling = setInterval(pollProgress, 3000);

        $.ajax({
            url: dba_pe.ajaxurl,
            type: 'POST',
            data: {
                action: 'dba_pe_single_post',
                nonce: dba_pe.nonce,
                post_index: postIndex
            },
            timeout: 180000,
            success: function(resp) {
                clearInterval(polling);

                if (!resp.success) {
                    batchState.failed++;
                    $('#dba-pe-progress-detail').text('Post ' + postIndex + ' failed: ' + (resp.data ? resp.data.message : 'unknown'));
                } else if (resp.data && resp.data.status === 'failed') {
                    batchState.failed++;
                    $('#dba-pe-progress-detail').text('Post ' + postIndex + ' failed: ' + (resp.data.error || 'unknown'));
                } else {
                    batchState.created++;
                    var title = resp.data ? (resp.data.title || '') : '';
                    $('#dba-pe-progress-detail').text('✅ Post ' + postIndex + ': ' + title);
                }

                if (stopped) { batchStopped(); return; }

                setTimeout(function() {
                    generateNextPost(postIndex + 1);
                }, 2000);
            },
            error: function(xhr, status) {
                clearInterval(polling);
                batchState.failed++;
                $('#dba-pe-progress-detail').text('⚠️ Post ' + postIndex + ' ' + (status === 'timeout' ? 'timed out' : 'error: ' + status) + '. Continuing…');

                if (stopped) { batchStopped(); return; }

                setTimeout(function() {
                    generateNextPost(postIndex + 1);
                }, 3000);
            }
        });
    }

    function finishRoundup() {
        if (stopped) { batchStopped(); return; }

        $('#dba-pe-progress-bar').css('width', '92%');
        $('#dba-pe-progress-label').text('Creating daily roundup hub…');

        if (batchState.created === 0) {
            batchDone('0 created, ' + batchState.failed + ' failed. No roundup.');
            return;
        }

        $.ajax({
            url: dba_pe.ajaxurl,
            type: 'POST',
            data: { action: 'dba_pe_finish_roundup', nonce: dba_pe.nonce },
            timeout: 60000,
            success: function(resp) {
                var roundup = (resp.success && resp.data) ? ' | Roundup: #' + (resp.data.roundup_id || '?') : '';
                batchDone('Created: ' + batchState.created + ' | Failed: ' + batchState.failed + roundup);
            },
            error: function(xhr, status) {
                batchDone('Created: ' + batchState.created + ' | Failed: ' + batchState.failed + ' | Roundup failed: ' + status);
            }
        });
    }

    function resetButtons() {
        $runBtn.prop('disabled', false).text('🚀 Run PE Batch Now');
        $stopBtn.prop('disabled', true).css('opacity', '0.5').text('⛔ Stop Batch');
    }

    function batchStopped() {
        if (polling) clearInterval(polling);
        resetButtons();
        $('#dba-pe-progress-bar').css({'width': '100%', 'background': '#f0ad4e'});
        $('#dba-pe-progress-label').text('⛔ Batch stopped by user');
        var summary = 'Created: ' + batchState.created + ' | Failed: ' + batchState.failed + ' | Remaining skipped';
        if (batchState.created > 0) {
            summary += ' — run again to generate roundup';
        }
        $('#dba-pe-progress-detail').text(summary);
    }

    function batchDone(summary) {
        if (polling) clearInterval(polling);
        resetButtons();
        $('#dba-pe-progress-bar').css('width', '100%');
        $('#dba-pe-progress-label').text('✅ Batch complete!');
        $('#dba-pe-progress-detail').text(summary);
    }

    function batchError(message) {
        if (polling) clearInterval(polling);
        resetButtons();
        $('#dba-pe-progress-label').text('❌ ' + message);
        $('#dba-pe-progress-bar').css({'width': '100%', 'background': '#dc3545'});
    }

    function pollProgress() {
        $.ajax({
            url: dba_pe.ajaxurl,
            type: 'POST',
            data: { action: 'dba_pe_get_progress', nonce: dba_pe.nonce },
            success: function(resp) {
                if (!resp.success || !resp.data) return;
                var p = resp.data;
                if (p.current_step_name && p.current_detail) {
                    $('#dba-pe-progress-label').text(
                        'Post ' + (p.current_post || '?') + '/' + batchState.target +
                        ' — ' + (p.current_step_name || '…')
                    );
                    $('#dba-pe-progress-detail').text(p.current_detail || '');
                }
            }
        });
    }

})(jQuery);
