/**
 * Filename Cleanup JavaScript — NEW in v4.1
 *
 * Drives scan / preview / repair flows for Wrenio_Filename_Cleanup.
 * Uses the same offset=0 pattern as reconcile.js for execute mode
 * (items drop out of the scan query as they're fixed).
 */
jQuery(document).ready(function($) {
    var running = false;
    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();
        $('#filename-log').append(
            '<div style="color: ' + (colors[type] || '#333') + ';">' +
            '[' + ts + '] ' + $('<div>').text(message).html() +
            '</div>'
        );
        $('#filename-log').scrollTop($('#filename-log')[0].scrollHeight);
    }

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

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

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wrenio_media_offload_filename_scan',
                nonce: wrenio_media_offload_filename.nonce
            },
            success: function(response) {
                if (response.success) {
                    $('#filename-mismatch-count').text(response.data.count);
                    var count = parseInt(response.data.count, 10);
                    $('#filename-preview, #filename-start-repair').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');
            }
        });
    });

    $('#filename-preview').on('click', function() {
        var $btn = $(this);
        $btn.prop('disabled', true).text('Loading…');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wrenio_media_offload_filename_preview',
                nonce: wrenio_media_offload_filename.nonce,
                offset: 0,
                limit: 20
            },
            success: function(response) {
                if (response.success) {
                    var rows = response.data.rows || [];
                    var $tbody = $('#filename-preview-rows').empty();
                    for (var i = 0; i < rows.length; i++) {
                        var r = rows[i];
                        var tr = $('<tr></tr>');
                        tr.append($('<td></td>').text(r.id));
                        tr.append($('<td></td>').text(r.title || '-'));
                        tr.append($('<td></td>').append($('<code></code>').text(r.current_file)));
                        tr.append($('<td></td>').append($('<code></code>').text(r.current_key)));
                        tr.append($('<td></td>').append($('<code></code>').css('color', '#00a32a').text(r.proposed_file)));
                        $tbody.append(tr);
                    }
                    $('#filename-preview-container').show();
                    log('Loaded ' + rows.length + ' row(s) for preview.', 'info');
                } else {
                    log('Preview failed: ' + (response.data || 'Unknown error'), 'error');
                }
            },
            error: function(xhr, status, error) {
                log('Preview request failed: ' + error, 'error');
            },
            complete: function() {
                $btn.prop('disabled', false).text('Preview (first 20)');
            }
        });
    });

    $('#filename-start-repair').on('click', function() {
        if (running) return;
        if (!confirm('Repair all filename mismatches? This updates _wp_attached_file post meta to match R2 keys. Take a database backup first if running on production.')) {
            return;
        }

        running = true;
        totalProcessed = 0;
        totalSucceeded = 0;
        totalFailed = 0;
        initialCount = parseInt($('#filename-mismatch-count').text().replace(/[^0-9]/g, ''), 10) || 0;

        $('#filename-start-repair').hide();
        $('#filename-stop-repair').show();
        $('#filename-progress').show();
        $('#filename-status').text('Running…');

        log('Starting repair of ' + initialCount + ' attachment(s).', 'info');
        processBatch();
    });

    $('#filename-stop-repair').on('click', function() {
        running = false;
        log('Stopped by user.', 'warning');
        $('#filename-stop-repair').hide();
        $('#filename-start-repair').show();
        $('#filename-status').text('Stopped.');
    });

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

        var batchSize = parseInt($('#filename_batch_size').val(), 10) || 25;

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wrenio_media_offload_filename_repair',
                nonce: wrenio_media_offload_filename.nonce,
                batch_size: batchSize
            },
            success: function(response) {
                if (!response.success) {
                    log('Batch failed: ' + (response.data || 'Unknown error'), 'error');
                    running = false;
                    $('#filename-stop-repair').hide();
                    $('#filename-start-repair').show();
                    $('#filename-status').text('Error.');
                    return;
                }

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

                (data.messages || []).forEach(function(m) {
                    log(m.message, m.type);
                });

                updateProgress(totalProcessed, initialCount);

                if (data.has_more && running) {
                    setTimeout(processBatch, 500);
                } else {
                    running = false;
                    $('#filename-stop-repair').hide();
                    $('#filename-start-repair').show();
                    $('#filename-status').text('Complete.');
                    log('Complete. ' + totalSucceeded + ' repaired, ' + totalFailed + ' failed.',
                        totalFailed === 0 ? 'success' : 'warning');
                    $('#filename-refresh-count').trigger('click');
                }
            },
            error: function(xhr, status, error) {
                log('Batch request failed: ' + error, 'error');
                running = false;
                $('#filename-stop-repair').hide();
                $('#filename-start-repair').show();
                $('#filename-status').text('Error.');
            }
        });
    }
});
