/**
 * Reconciliation JavaScript — NEW in v4.
 *
 * Drives the dry-run preview and live reconciliation flows for Wrenio_Reconcile.
 * Same pagination principle as bulk-sync.js: execute mode uses offset=0
 * because reconciled items drop out of the scan query; dry-run mode
 * increments offset because nothing changes.
 */
jQuery(document).ready(function($) {
    var running = false;
    var mode = 'dry'; // 'dry' or 'execute'
    var currentOffset = 0;
    var totalProcessed = 0;
    var totalSucceeded = 0;
    var totalFailed = 0;
    var initialCount = 0;

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

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

    $('#refresh-count').on('click', function() {
        var $btn = $(this);
        $btn.prop('disabled', true).text('Refreshing…');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wrenio_media_offload_reconcile_scan',
                nonce: wrenio_media_offload_reconcile.nonce
            },
            success: function(response) {
                if (response.success) {
                    $('#misaligned-count').text(response.data.misaligned);
                    // v4.1: capped count
                    if (typeof response.data.capped !== 'undefined') {
                        $('#capped-count').text(response.data.capped);
                    }
                    var count = parseInt(response.data.misaligned, 10);
                    $('#start-dry-run, #start-reconcile').prop('disabled', count === 0);
                } else {
                    log('Refresh failed: ' + (response.data || 'Unknown error'), 'error');
                }
            },
            error: function(xhr, status, error) {
                log('Refresh request failed: ' + error, 'error');
            },
            complete: function() {
                $btn.prop('disabled', false).text('Refresh count');
            }
        });
    });

    // v4.1: reset retry counters
    $(document).on('click', '#reset-retries', function() {
        if (!confirm('Reset retry counters for all capped attachments? They will be eligible for reconciliation again.')) {
            return;
        }
        var $btn = $(this);
        $btn.prop('disabled', true).text('Resetting…');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wrenio_media_offload_reconcile_reset_retries',
                nonce: wrenio_media_offload_reconcile.nonce
            },
            success: function(response) {
                if (response.success) {
                    log('Retry counters reset: ' + response.data.reset + ' cleared.', 'success');
                    // Refresh the counts
                    $('#refresh-count').trigger('click');
                } else {
                    log('Reset failed: ' + (response.data || 'Unknown error'), 'error');
                }
            },
            error: function(xhr, status, error) {
                log('Reset request failed: ' + error, 'error');
            },
            complete: function() {
                $btn.prop('disabled', false).text('Reset Retries');
            }
        });
    });

    $('#start-dry-run').on('click', function() {
        if (running) return;
        mode = 'dry';
        startReconciliation();
    });

    $('#start-reconcile').on('click', function() {
        if (running) return;
        var confirmed = confirm(
            'This will move objects on Cloudflare R2 and delete the old copies.\n\n' +
            'Before continuing, confirm you have:\n' +
            '  • a database backup\n' +
            '  • a backup of your R2 bucket (or know you can tolerate losing misplaced objects)\n\n' +
            'Proceed?'
        );
        if (!confirmed) return;
        mode = 'execute';
        startReconciliation();
    });

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

    function startReconciliation() {
        running = true;
        currentOffset = 0;
        totalProcessed = 0;
        totalSucceeded = 0;
        totalFailed = 0;

        initialCount = parseInt($('#misaligned-count').text().replace(/\D/g, ''), 10) || 0;

        $('#start-dry-run, #start-reconcile').prop('disabled', true);
        $('#stop-reconcile').show();
        $('#reconcile-status').text(mode === 'dry' ? 'Dry run in progress…' : 'Reconciliation in progress…');
        $('#reconcile-progress').show();
        $('#reconcile-log').empty();

        log(mode === 'dry' ? 'Starting dry run — no changes will be made.' : 'Starting reconciliation.', 'info');
        processBatch();
    }

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

        var batchSize = parseInt($('#reconcile_batch_size').val(), 10) || 5;
        batchSize = Math.max(1, Math.min(20, batchSize));

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wrenio_media_offload_reconcile_batch',
                nonce: wrenio_media_offload_reconcile.nonce,
                offset: currentOffset,
                batch_size: batchSize,
                dry_run: mode === 'dry' ? 'true' : 'false'
            },
            timeout: 120000, // 2 minutes
            success: function(response) {
                if (!running) return;

                if (!response.success) {
                    log('Error: ' + (response.data || 'Unknown error'), 'error');
                    complete();
                    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, initialCount || totalProcessed);

                // Pagination: dry run walks the query, execute stays at offset 0
                if (mode === 'dry') {
                    currentOffset += (data.processed || 0);
                } else {
                    currentOffset = 0;
                }

                if (data.has_more && running && (data.processed || 0) > 0) {
                    setTimeout(processBatch, 500);
                } else {
                    complete();
                }
            },
            error: function(xhr, status, error) {
                if (!running) return;
                log('Request failed: ' + error + ' (status: ' + status + ')', 'error');
                complete();
            }
        });
    }

    function complete() {
        running = false;
        $('#start-dry-run, #start-reconcile').prop('disabled', false);
        $('#stop-reconcile').hide();
        $('#reconcile-status').text('Done.');
        log(
            (mode === 'dry' ? 'Dry run complete. ' : 'Reconciliation complete. ') +
            'Processed: ' + totalProcessed +
            ', Succeeded: ' + totalSucceeded +
            ', Failed: ' + totalFailed,
            totalFailed > 0 ? 'warning' : 'success'
        );

        if (mode === 'execute') {
            // Refresh the misaligned count
            $('#refresh-count').trigger('click');
        }
    }
});
