/**
 * PE NewsBot Admin JS — Per-post batch + stop + post links + error capture
 * @since 2.7.1
 */
(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');
    var $results = $('#dba-pe-results');

    $runBtn.on('click', function(e) {
        e.preventDefault();
        if (!confirm('Run the PE News Batch now?')) 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('');
        $results.empty().show();

        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;
                addResult('info', 'Batch initialized — target: ' + batchState.target + ' posts (' + (resp.data.day || '?') + '), existing today: ' + (resp.data.existing || 0));
                $('#dba-pe-progress-label').text('Generating ' + batchState.target + ' posts…');
                $('#dba-pe-progress-bar').css('width', '5%');
                generateNextPost(1);
            },
            error: function(xhr, status) {
                batchError('Init 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…');
    });

    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++;
                    var errMsg = resp.data ? (resp.data.message || resp.data.error || JSON.stringify(resp.data)) : 'Unknown error';
                    addResult('fail', 'Post ' + postIndex + ' FAILED: ' + errMsg);
                } else if (resp.data && resp.data.status === 'failed') {
                    batchState.failed++;
                    addResult('fail', 'Post ' + postIndex + ' FAILED: ' + (resp.data.error || 'Unknown'));
                } else if (resp.data) {
                    batchState.created++;
                    var d = resp.data;
                    var link = d.permalink ? '<a href="' + d.permalink + '" target="_blank">' + (d.title || 'View Post') + '</a>' : (d.title || 'Created');
                    addResult('ok', 'Post ' + postIndex + ': ' + link + ' <span style="color:#888;">(' + (d.geo || '') + ' — ' + (d.company || '') + ')</span>');
                }

                if (stopped) { batchStopped(); return; }
                setTimeout(function() { generateNextPost(postIndex + 1); }, 2000);
            },
            error: function(xhr, status) {
                clearInterval(polling);
                batchState.failed++;

                // Try to read response body — shutdown handler may have written JSON
                var serverMsg = '';
                try {
                    if (xhr.responseText) {
                        var parsed = JSON.parse(xhr.responseText);
                        if (parsed.data && parsed.data.error) {
                            serverMsg = parsed.data.error;
                        }
                    }
                } catch(e) {
                    serverMsg = xhr.responseText ? xhr.responseText.substring(0, 300) : '';
                }

                if (!serverMsg) {
                    // PHP died completely — fetch the stored error
                    fetchLastError(postIndex, function(storedErr) {
                        var msg = storedErr || (status === 'timeout' ? 'Request timed out (host killed PHP)' : 'PHP crashed — check server error log');
                        addResult('fail', 'Post ' + postIndex + ' FAILED: ' + msg);
                        if (stopped) { batchStopped(); return; }
                        setTimeout(function() { generateNextPost(postIndex + 1); }, 3000);
                    });
                    return;
                }

                addResult('fail', 'Post ' + postIndex + ' FAILED: ' + serverMsg);
                if (stopped) { batchStopped(); return; }
                setTimeout(function() { generateNextPost(postIndex + 1); }, 3000);
            }
        });
    }

    // Fetch the last stored PE error from the database via a quick AJAX call
    function fetchLastError(postIndex, callback) {
        $.ajax({
            url: dba_pe.ajaxurl,
            type: 'POST',
            data: { action: 'dba_pe_get_progress', nonce: dba_pe.nonce },
            timeout: 5000,
            success: function(resp) {
                // Also try reading the last error from progress detail
                var detail = '';
                if (resp.success && resp.data && resp.data.last_error) {
                    detail = resp.data.last_error;
                }
                callback(detail);
            },
            error: function() {
                callback('');
            }
        });
    }

    function finishRoundup() {
        if (stopped) { batchStopped(); return; }
        $('#dba-pe-progress-bar').css('width', '92%');
        $('#dba-pe-progress-label').text('Creating roundup…');

        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) {
                if (resp.success && resp.data && resp.data.roundup_id) {
                    addResult('ok', 'Roundup: <a href="/?p=' + resp.data.roundup_id + '" target="_blank">Post #' + resp.data.roundup_id + '</a>');
                }
                batchDone('Created: ' + batchState.created + ' | Failed: ' + batchState.failed + (resp.data ? ' | Roundup: #' + (resp.data.roundup_id || '?') : ''));
            },
            error: function(xhr, status) {
                batchDone('Created: ' + batchState.created + ' | Failed: ' + batchState.failed + ' | Roundup failed: ' + status);
            }
        });
    }

    function addResult(type, html) {
        var colors = { ok: '#28a745', fail: '#dc3545', info: '#6c757d' };
        var icons = { ok: '✅', fail: '❌', info: 'ℹ️' };
        $results.append(
            '<div style="padding:6px 0;border-bottom:1px solid #eee;font-size:13px;line-height:1.5;">' +
            '<span style="color:' + (colors[type] || '#333') + ';">' + (icons[type] || '') + '</span> ' +
            html + '</div>'
        );
    }

    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('⛔ Stopped');
        $('#dba-pe-progress-detail').text('Created: ' + batchState.created + ' | Failed: ' + batchState.failed);
    }

    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();
        addResult('fail', message);
        $('#dba-pe-progress-label').text('❌ Error');
        $('#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) {
                    $('#dba-pe-progress-label').text(
                        'Post ' + (p.current_post || '?') + '/' + batchState.target +
                        ' — ' + (p.current_step_name || '')
                    );
                    if (p.current_detail) {
                        $('#dba-pe-progress-detail').text(p.current_detail);
                    }
                }
            }
        });
    }

})(jQuery);
