/**
 * Bulk Sync JavaScript for Wrenio Media Offload v4.
 *
 * P0-A fix vs v3: in "full" mode we no longer increment the client-side
 * offset between batches. Items that sync successfully drop out of the
 * unsynced query on the server, so passing offset=0 on every request
 * returns the next unsynced batch. Incrementing the offset client-side
 * caused ~50% of items to be skipped per run.
 *
 * Incremental mode keeps a client-side offset because the result set
 * there is stable while size variants get filled in (items stay matched
 * by the _r2_url filter).
 */
jQuery(document).ready(function($) {
    var syncRunning = false;
    var currentOffset = 0;
    var currentMode = 'full';
    var totalProcessed = 0;
    var totalSucceeded = 0;
    var totalFailed = 0;
    var initialTotal = 0;

    function log(message, type) {
        type = type || 'info';
        var colors = {
            success: '#00a32a',
            error:   '#d63638',
            info:    '#2271b1',
            warning: '#dba617'
        };
        var ts = new Date().toLocaleTimeString();
        $('#bulk-sync-log').append(
            '<div style="color: ' + (colors[type] || '#333') + ';">' +
            '[' + ts + '] ' + $('<div>').text(message).html() +
            '</div>'
        );
        $('#bulk-sync-log').scrollTop($('#bulk-sync-log')[0].scrollHeight);
    }

    function updateProgress(processed, total) {
        var pct = total > 0 ? Math.min(100, Math.round((processed / total) * 100)) : 0;
        $('#batch-progress-bar').css('width', pct + '%');
        $('#batch-progress-status').text(
            processed + ' / ' + total + ' processed (' + pct + '%)'
        );

        // Also update the overall progress bar using initial-baseline + newly synced
        if (initialTotal > 0) {
            var overallSynced = Math.min(initialTotal, $('#overall-progress-bar').data('baseline') + totalSucceeded);
            var overallPct = Math.round((overallSynced / initialTotal) * 100);
            $('#overall-progress-bar').css('width', overallPct + '%');
        }
    }

    $('#start-bulk-sync').on('click', function() {
        if (syncRunning) return;

        syncRunning = true;
        currentMode = $('input[name="sync_mode"]:checked').val() || 'full';
        currentOffset = 0;
        totalProcessed = 0;
        totalSucceeded = 0;
        totalFailed = 0;

        // Capture initial totals for the overall progress bar
        var totalText = $('.widefat tbody tr:nth-child(1) td:nth-child(2)').text().replace(/\D/g, '');
        var syncedText = $('.widefat tbody tr:nth-child(2) td:nth-child(2)').text().split(' ')[0].replace(/\D/g, '');
        initialTotal = parseInt(totalText, 10) || 0;
        $('#overall-progress-bar').data('baseline', parseInt(syncedText, 10) || 0);

        $(this).prop('disabled', true);
        $('#stop-bulk-sync').show();
        $('#bulk-sync-status').text('Starting sync…');
        $('#batch-progress').show();
        $('#bulk-sync-log').empty();

        log('Starting bulk sync in ' + currentMode + ' mode…', 'info');
        processBatch();
    });

    $('#stop-bulk-sync').on('click', function() {
        syncRunning = false;
        log('Stopped by user.', 'warning');
        $('#start-bulk-sync').prop('disabled', false);
        $('#stop-bulk-sync').hide();
        $('#bulk-sync-status').text('Stopped.');
    });

    function processBatch() {
        if (!syncRunning) return;

        var batchSize = parseInt($('#batch_size').val(), 10) || 10;
        batchSize = Math.max(1, Math.min(50, batchSize));
        var regenerateMetadata = $('#regenerate_metadata').is(':checked');

        // Server-side offset is ignored for full mode (always uses 0), but we
        // send it for clarity and for incremental mode.
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wrenio_media_offload_bulk_sync',
                nonce: wrenio_media_offload_bulk.nonce,
                offset: currentOffset,
                batch_size: batchSize,
                mode: currentMode,
                regenerate_metadata: regenerateMetadata ? 'true' : 'false'
            },
            success: function(response) {
                if (!syncRunning) return;

                if (!response.success) {
                    log('Error: ' + (response.data || 'Unknown error'), 'error');
                    syncComplete();
                    return;
                }

                var data = response.data;
                totalProcessed += data.processed || 0;
                totalSucceeded += data.succeeded || 0;
                totalFailed    += data.failed    || 0;

                if (Array.isArray(data.messages)) {
                    data.messages.forEach(function(msg) {
                        log(msg.message, msg.type);
                    });
                }

                updateProgress(totalProcessed, initialTotal || totalProcessed);

                // PAGINATION LOGIC (the v4 fix):
                //   full:        offset stays at 0, items drop out of query as they sync
                //   incremental: increment offset to walk the stable result set
                if (currentMode === 'incremental') {
                    currentOffset += (data.processed || 0);
                } else {
                    currentOffset = 0;
                }

                if (data.has_more && syncRunning && (data.processed || 0) > 0) {
                    // Short pause between batches to be polite
                    setTimeout(processBatch, 500);
                } else {
                    syncComplete();
                }
            },
            error: function(xhr, status, error) {
                if (!syncRunning) return;
                log('Request failed: ' + error, 'error');
                syncComplete();
            }
        });
    }

    function syncComplete() {
        syncRunning = false;
        $('#start-bulk-sync').prop('disabled', false);
        $('#stop-bulk-sync').hide();
        $('#bulk-sync-status').text('Done.');
        log(
            'Sync complete. Processed: ' + totalProcessed +
            ', Succeeded: ' + totalSucceeded +
            ', Failed: ' + totalFailed,
            totalFailed > 0 ? 'warning' : 'success'
        );
    }
});
