jQuery(document).ready(function ($) {
    var syncInProgress = false;
    var currentBatch = 0;
    var paused = false;

    // Start bulk sync
    $('#start-bulk-sync').on('click', function (e) {
        e.preventDefault();
        initBulkSync();
        //window.location.href = $(this).attr('href');
    });

    // Initialize progress bar if we're on the bulk sync page
    if ($('#bulk-sync-container').hasClass('active')) {
        initBulkSync();
    }

    function initBulkSync() {
        // Get initial stats
        updateProgressStats();

        // Start the sync process
        startSync();

        // Set up event handlers
        $('#pause-sync').on('click', pauseSync);
        $('#resume-sync').on('click', resumeSync);
        $('#cancel-sync').on('click', cancelSync);
    }

    function startSync() {
        if (syncInProgress) return;

        syncInProgress = true;
        paused = false;
        $('#pause-sync').show();
        $('#resume-sync').hide();
        $('.status-text').text(cloud_uploads_vars.text_processing);

        processNextBatch();
    }

    function pauseSync() {
        paused = true;
        $('#pause-sync').hide();
        $('#resume-sync').show();
        $('.status-text').text('Paused');
    }

    function resumeSync() {
        paused = false;
        $('#pause-sync').show();
        $('#resume-sync').hide();
        $('.status-text').text(cloud_uploads_vars.text_processing);

        processNextBatch();
    }

    function cancelSync() {
        syncInProgress = false;
        paused = false;
        $('.status-text').text('Cancelled');
        $('#pause-sync, #resume-sync').hide();
    }

    function processNextBatch() {
        if (!syncInProgress || paused) return;

        $.ajax({
            url: cloud_uploads_vars.ajax_url,
            type: 'POST',
            data: {
                action: 'cloud_uploads_batch',
                nonce: cloud_uploads_vars.nonce,
                batch: currentBatch,
                batch_size: cloud_uploads_vars.batch_size
            },
            beforeSend: function () {
                $('.status-text').text('Processing batch ' + (currentBatch + 1) + '...');
            },
            success: function (response) {
                if (response.success) {
                    var data = response.data;

                    // Update progress
                    updateProgressUI(data);

                    // Check if completed
                    if (data.completed) {
                        completeSync();
                    } else {
                        currentBatch++;
                        setTimeout(processNextBatch, 500); // Small delay between batches
                    }
                } else {
                    handleSyncError('Batch processing failed');
                }
            },
            error: function () {
                handleSyncError('AJAX request failed');
            }
        });
    }

    function updateProgressUI(data) {
        // Update progress bar
        var percentage = data.stats.percentage;
        $('.progress-fill').css('width', percentage + '%');
        $('.percentage').text(percentage + '%');

        // Update counts
        $('.processed').text(data.processed);
        $('.success').text(data.succeeded);
        $('.failed').text(data.failed);

        // Update status text
        $('.status-text').text('Processed ' + data.processed + ' items in batch ' + (data.batch + 1));
    }

    function updateProgressStats() {
        $.ajax({
            url: cloud_uploads_vars.ajax_url,
            type: 'POST',
            data: {
                action: 'cloud_uploads_get_stats',
                nonce: cloud_uploads_vars.nonce
            },
            success: function (response) {
                if (response.success) {
                    var stats = response.data;
                    $('.total').text(stats.unsynced);
                    $('.progress-fill').css('width', stats.percentage + '%');
                    $('.percentage').text(stats.percentage + '%');
                }
            }
        });
    }

    function completeSync() {
        syncInProgress = false;
        $('.status-text').text(cloud_uploads_vars.text_completed);
        $('#pause-sync, #resume-sync, #cancel-sync').hide();

        // Show success message
        showMessage('Bulk sync completed successfully!', 'success');

        // Refresh stats after a delay
        setTimeout(updateProgressStats, 1000);
    }

    function handleSyncError(message) {
        syncInProgress = false;
        $('.status-text').text(cloud_uploads_vars.text_error + ': ' + message);
        $('#pause-sync, #resume-sync').hide();

        showMessage('Sync error: ' + message, 'error');
    }

    function showMessage(text, type) {
        var noticeClass = type === 'error' ? 'notice-error' : 'notice-success';
        var notice = $('<div class="notice ' + noticeClass + ' is-dismissible"><p>' + text + '</p></div>');

        $('.wrap h1').after(notice);

        // Auto-dismiss after 5 seconds
        setTimeout(function () {
            notice.fadeOut(500, function () {
                $(this).remove();
            });
        }, 5000);
    }
});