/**
 * Orphan Cleanup JavaScript — NEW in v4.1
 *
 * Three-phase workflow:
 *  1. Scan: kick off scan_start, then repeatedly call scan_step until complete.
 *  2. Preview: load slices of the orphan list via preview endpoint.
 *  3. Delete: call delete_batch repeatedly until no orphans remain.
 *
 * Each phase has its own running flag and log entries. Scan and delete
 * share the same log container.
 */
jQuery(document).ready(function($) {
    var scanning = false;
    var deleting = false;
    var previewOffset = 0;

    var deleteTotal = 0;
    var deleteProcessed = 0;
    var deleteSucceeded = 0;
    var deleteFailed = 0;

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

    function updateScanProgress(scanned, orphans) {
        // We don't know the bucket size in advance, so progress is indeterminate.
        // Show a slow sweep effect based on scanned count.
        var pct = Math.min(95, (scanned / 1000) * 5);
        $('#orphan-scan-progress-bar').css('width', pct + '%');
        $('#orphan-scan-progress-status').text(
            'Scanned: ' + scanned + ' — Orphans: ' + orphans
        );
    }

    function updateDeleteProgress() {
        var pct = deleteTotal > 0 ? Math.min(100, Math.round((deleteProcessed / deleteTotal) * 100)) : 0;
        $('#orphan-delete-progress-bar').css('width', pct + '%');
        $('#orphan-delete-progress-status').text(
            deleteProcessed + ' / ' + deleteTotal + ' processed (' + pct + '%)' +
            ' — deleted: ' + deleteSucceeded + ', failed: ' + deleteFailed
        );
    }

    // ========== SCAN ==========

    $('#orphan-start-scan').on('click', function() {
        if (scanning) return;
        if (!confirm('Start scanning the R2 bucket for orphans? This is read-only but may take several minutes for large buckets.')) {
            return;
        }

        scanning = true;
        var prefix = $('#orphan_prefix').val() || '';

        $('#orphan-start-scan').hide();
        $('#orphan-stop-scan').show();
        $('#orphan-scan-progress').show();
        $('#orphan-scan-status').text('Starting…');

        log('Scan started. Prefix: "' + (prefix || '(whole bucket)') + '"', 'info');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wrenio_media_offload_orphan_scan_start',
                nonce: wrenio_media_offload_orphan.nonce,
                prefix: prefix
            },
            success: function(response) {
                if (!response.success) {
                    log('Scan start failed: ' + (response.data || 'Unknown error'), 'error');
                    scanning = false;
                    $('#orphan-stop-scan').hide();
                    $('#orphan-start-scan').show();
                    return;
                }
                log('Collected ' + response.data.referenced_count + ' referenced keys from WordPress.', 'info');
                $('#orphan-referenced-count').text(response.data.referenced_count);
                stepScan();
            },
            error: function(xhr, status, error) {
                log('Scan start request failed: ' + error, 'error');
                scanning = false;
                $('#orphan-stop-scan').hide();
                $('#orphan-start-scan').show();
            }
        });
    });

    $('#orphan-stop-scan').on('click', function() {
        scanning = false;
        log('Scan paused. You can resume by clicking Start Scan again (it picks up where it left off).', 'warning');
        $('#orphan-stop-scan').hide();
        $('#orphan-start-scan').show();
        $('#orphan-scan-status').text('Paused.');
    });

    function stepScan() {
        if (!scanning) return;

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wrenio_media_offload_orphan_scan_step',
                nonce: wrenio_media_offload_orphan.nonce
            },
            success: function(response) {
                if (!response.success) {
                    log('Scan step failed: ' + (response.data || 'Unknown error'), 'error');
                    scanning = false;
                    $('#orphan-stop-scan').hide();
                    $('#orphan-start-scan').show();
                    $('#orphan-scan-status').text('Error.');
                    return;
                }

                var d = response.data;
                $('#orphan-scanned-count').text(d.objects_scanned);
                $('#orphan-count').text(d.orphans_found);
                updateScanProgress(d.objects_scanned, d.orphans_found);

                if (d.completed) {
                    scanning = false;
                    $('#orphan-scan-progress-bar').css('width', '100%');
                    $('#orphan-scan-state').text('Complete');
                    $('#orphan-stop-scan').hide();
                    $('#orphan-start-scan').show();
                    $('#orphan-scan-status').text('Complete.');
                    log('Scan complete. ' + d.orphans_found + ' orphan(s) found in ' + d.objects_scanned + ' object(s).',
                        d.orphans_found > 0 ? 'warning' : 'success');
                    // Enable delete button if orphans present
                    $('#orphan-start-delete').prop('disabled', d.orphans_found === 0);
                    return;
                }

                // Continue scanning
                setTimeout(stepScan, 200);
            },
            error: function(xhr, status, error) {
                log('Scan step request failed: ' + error, 'error');
                scanning = false;
                $('#orphan-stop-scan').hide();
                $('#orphan-start-scan').show();
                $('#orphan-scan-status').text('Error.');
            }
        });
    }

    $('#orphan-reset').on('click', function() {
        if (!confirm('Reset scan state and discard the current orphan list? A new scan will start from scratch.')) {
            return;
        }
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wrenio_media_offload_orphan_reset',
                nonce: wrenio_media_offload_orphan.nonce
            },
            success: function(response) {
                if (response.success) {
                    log('Scan state reset.', 'info');
                    $('#orphan-scanned-count').text('0');
                    $('#orphan-count').text('0');
                    $('#orphan-referenced-count').text('0');
                    $('#orphan-scan-state').text('Not started');
                    $('#orphan-scan-progress-bar').css('width', '0%');
                    $('#orphan-scan-progress').hide();
                    $('#orphan-preview-container').hide();
                    $('#orphan-preview-rows').empty();
                    $('#orphan-start-delete').prop('disabled', true);
                    previewOffset = 0;
                } else {
                    log('Reset failed: ' + (response.data || 'Unknown error'), 'error');
                }
            },
            error: function(xhr, status, error) {
                log('Reset request failed: ' + error, 'error');
            }
        });
    });

    // ========== PREVIEW ==========

    $('#orphan-preview').on('click', function() {
        previewOffset = 0;
        $('#orphan-preview-rows').empty();
        loadPreview();
    });

    $('#orphan-preview-next').on('click', function() {
        loadPreview();
    });

    function loadPreview() {
        var $btn = $('#orphan-preview');
        $btn.prop('disabled', true).text('Loading…');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wrenio_media_offload_orphan_preview',
                nonce: wrenio_media_offload_orphan.nonce,
                offset: previewOffset,
                limit: 20
            },
            success: function(response) {
                if (!response.success) {
                    log('Preview failed: ' + (response.data || 'Unknown error'), 'error');
                    return;
                }

                var keys = response.data.keys || [];
                var urls = response.data.sample_urls || [];
                var $tbody = $('#orphan-preview-rows');

                for (var i = 0; i < keys.length; i++) {
                    var tr = $('<tr></tr>');
                    tr.append($('<td></td>').append($('<code></code>').text(keys[i])));
                    var url = urls[i];
                    var linkCell = $('<td></td>');
                    if (url) {
                        linkCell.append(
                            $('<a></a>').attr('href', url).attr('target', '_blank').attr('rel', 'noopener').text(url)
                        );
                    }
                    tr.append(linkCell);
                    $tbody.append(tr);
                }

                previewOffset += keys.length;
                $('#orphan-preview-container').show();

                if (previewOffset < response.data.total) {
                    $('#orphan-preview-next').show();
                } else {
                    $('#orphan-preview-next').hide();
                }

                log('Loaded rows ' + (previewOffset - keys.length) + '–' + previewOffset + ' of ' + response.data.total, 'info');
            },
            error: function(xhr, status, error) {
                log('Preview request failed: ' + error, 'error');
            },
            complete: function() {
                $btn.prop('disabled', false).text('Load first 20');
            }
        });
    }

    // ========== DELETE ==========

    $('#orphan-start-delete').on('click', function() {
        if (deleting) return;

        var orphanCount = parseInt($('#orphan-count').text().replace(/[^0-9]/g, ''), 10) || 0;
        if (orphanCount === 0) {
            log('No orphans to delete.', 'info');
            return;
        }

        if (!confirm('Delete ' + orphanCount + ' orphan object(s) from R2? This is permanent and cannot be undone.')) {
            return;
        }

        deleting = true;
        deleteTotal = orphanCount;
        deleteProcessed = 0;
        deleteSucceeded = 0;
        deleteFailed = 0;

        $('#orphan-start-delete').hide();
        $('#orphan-stop-delete').show();
        $('#orphan-delete-progress').show();
        $('#orphan-delete-status').text('Deleting…');

        log('Starting deletion of ' + orphanCount + ' orphan(s).', 'warning');
        stepDelete();
    });

    $('#orphan-stop-delete').on('click', function() {
        deleting = false;
        log('Deletion stopped by user. Already-deleted objects cannot be restored.', 'warning');
        $('#orphan-stop-delete').hide();
        $('#orphan-start-delete').show();
        $('#orphan-delete-status').text('Stopped.');
    });

    function stepDelete() {
        if (!deleting) return;

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

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wrenio_media_offload_orphan_delete_batch',
                nonce: wrenio_media_offload_orphan.nonce,
                batch_size: batchSize
            },
            success: function(response) {
                if (!response.success) {
                    log('Delete batch failed: ' + (response.data || 'Unknown error'), 'error');
                    deleting = false;
                    $('#orphan-stop-delete').hide();
                    $('#orphan-start-delete').show();
                    $('#orphan-delete-status').text('Error.');
                    return;
                }

                var d = response.data;
                deleteProcessed += (d.deleted + d.failed);
                deleteSucceeded += d.deleted;
                deleteFailed += d.failed;

                if (d.deleted > 0) {
                    log(d.deleted + ' object(s) deleted. ' + d.remaining + ' remaining.', 'success');
                }
                if (d.failed > 0) {
                    log(d.failed + ' deletion(s) failed — kept in list for retry.', 'warning');
                }

                $('#orphan-count').text(d.remaining);
                updateDeleteProgress();

                if (d.remaining > 0 && deleting && d.deleted > 0) {
                    // Keep going; brief pause between batches to respect the server-side rate limit
                    setTimeout(stepDelete, 2100);
                } else if (d.remaining > 0 && d.deleted === 0) {
                    // Nothing deleted this round = all remaining are failures. Stop.
                    deleting = false;
                    $('#orphan-stop-delete').hide();
                    $('#orphan-start-delete').show();
                    $('#orphan-delete-status').text('Halted — remaining items all failed.');
                    log('All remaining items failed to delete. Check the R2 credentials/permissions.', 'error');
                } else {
                    // remaining === 0: done
                    deleting = false;
                    $('#orphan-delete-progress-bar').css('width', '100%');
                    $('#orphan-stop-delete').hide();
                    $('#orphan-start-delete').show().prop('disabled', true);
                    $('#orphan-delete-status').text('Complete.');
                    log('Deletion complete. ' + deleteSucceeded + ' deleted, ' + deleteFailed + ' failed.',
                        deleteFailed === 0 ? 'success' : 'warning');
                }
            },
            error: function(xhr, status, error) {
                log('Delete request failed: ' + error, 'error');
                deleting = false;
                $('#orphan-stop-delete').hide();
                $('#orphan-start-delete').show();
                $('#orphan-delete-status').text('Error.');
            }
        });
    }
});
