/**
 * Admin Settings JavaScript for Wrenio Media Offload v4.
 *
 * - "Fix All Thumbnails" is now batched via AJAX to avoid browser timeouts
 *   on sites with thousands of images.
 * - Adds a "Test Write Access" button that does PUT+DELETE (more reliable
 *   than HEAD for catching token-scope issues).
 */
jQuery(document).ready(function($) {

    // In-page tab switching (General / Features / Auto Sync / Logs / Debug Info).
    // Moved out of an inline <script> tag in views/admin-settings.php so all
    // JS on this page is enqueued (WordPress.org plugin guideline).
    $('.nav-tab').on('click', function(e) {
        e.preventDefault();
        $('.nav-tab').removeClass('nav-tab-active');
        $(this).addClass('nav-tab-active');
        $('.tab-content').hide();
        $('#tab-' + $(this).data('tab')).show();
    });

    // AJAX-save settings on form submit (stays on the page, shows result inline)
    $('#wrenio-media-offload-settings-form').on('submit', function(e) {
        e.preventDefault();

        var $button = $(this).find('button[name="submit"]');
        var $form = $(this);
        $button.prop('disabled', true).text('Saving…');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wrenio_media_offload_save_settings',
                nonce: wrenio_media_offload_admin.save_settings_nonce,
                settings: $form.serialize()
            },
            success: function(response) {
                if (response.success) {
                    alert(response.data.message);
                    if (response.data.warning) {
                        alert(response.data.warning);
                    }
                } else {
                    alert('Save failed: ' + (response.data || 'Unknown error'));
                }
            },
            error: function() {
                alert('Request failed.');
            },
            complete: function() {
                $button.prop('disabled', false).text('Save Settings');
            }
        });
    });

    // Test connection (HEAD)
    $('#test-connection').on('click', function() {
        var $button = $(this);
        var $result = $('#test-connection-result');

        $button.prop('disabled', true).text('Testing…');
        $result.text('').removeClass('success error');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wrenio_media_offload_test_connection',
                nonce: wrenio_media_offload_admin.test_connection_nonce
            },
            success: function(response) {
                if (response.success) {
                    $result.css('color', '#00a32a').text('✓ ' + response.data);
                } else {
                    $result.css('color', '#d63638').text('✗ ' + response.data);
                }
            },
            error: function() {
                $result.css('color', '#d63638').text('✗ Request failed');
            },
            complete: function() {
                $button.prop('disabled', false).text(wrenio_media_offload_admin.test_connection_text);
            }
        });
    });

    // Test write access (PUT + DELETE)
    $('#test-put').on('click', function() {
        var $button = $(this);
        var $result = $('#test-connection-result');

        $button.prop('disabled', true).text('Testing…');
        $result.text('').removeClass('success error');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wrenio_media_offload_test_put',
                nonce: wrenio_media_offload_admin.test_put_nonce
            },
            success: function(response) {
                if (response.success) {
                    $result.css('color', '#00a32a').text('✓ ' + response.data);
                } else {
                    $result.css('color', '#d63638').text('✗ ' + response.data);
                }
            },
            error: function() {
                $result.css('color', '#d63638').text('✗ Request failed');
            },
            complete: function() {
                $button.prop('disabled', false).text(wrenio_media_offload_admin.test_put_text);
            }
        });
    });

    // Run auto-sync manually
    $('#run-auto-sync').on('click', function() {
        var $button = $(this);
        var $result = $('#run-auto-sync-result');

        $button.prop('disabled', true).text('Running…');
        $result.text('');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wrenio_media_offload_run_auto_sync',
                nonce: wrenio_media_offload_admin.run_sync_nonce
            },
            timeout: 120000,
            success: function(response) {
                if (response.success) {
                    $result.css('color', '#00a32a').text('✓ ' + response.data);
                } else {
                    $result.css('color', '#d63638').text('✗ ' + response.data);
                }
            },
            error: function() {
                $result.css('color', '#d63638').text('✗ Request failed');
            },
            complete: function() {
                $button.prop('disabled', false).text(wrenio_media_offload_admin.run_sync_text);
            }
        });
    });

    // Batched "Fix All Thumbnails"
    var fixRunning = false;
    var fixOffset = 0;
    var fixTotal = 0;
    var fixFixed = 0;
    var fixFailed = 0;

    $('#fix-all-thumbnails').on('click', function() {
        if (fixRunning) return;
        if (!confirm(wrenio_media_offload_admin.fix_thumbnails_confirm)) return;

        fixRunning = true;
        fixOffset = 0;
        fixTotal = 0;
        fixFixed = 0;
        fixFailed = 0;

        var $button = $(this);
        $button.prop('disabled', true);
        $('#fix-thumbnails-result').text('');
        $('#fix-thumbnails-progress').show();
        $('#fix-thumbnails-status').text('Counting images…');

        // First ask for total count so we can show progress
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wrenio_media_offload_fix_thumbnails_count',
                nonce: wrenio_media_offload_admin.fix_thumbnails_nonce
            },
            success: function(response) {
                if (response.success) {
                    fixTotal = parseInt(response.data.total, 10) || 0;
                    if (fixTotal === 0) {
                        finishFix('No images to process.');
                        return;
                    }
                    processFixBatch();
                } else {
                    finishFix('Failed to get image count: ' + (response.data || ''), true);
                }
            },
            error: function() {
                finishFix('Request failed getting image count.', true);
            }
        });
    });

    function processFixBatch() {
        if (!fixRunning) return;

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'wrenio_media_offload_fix_thumbnails_batch',
                nonce: wrenio_media_offload_admin.fix_thumbnails_nonce,
                offset: fixOffset,
                batch_size: 5
            },
            success: function(response) {
                if (!fixRunning) return;

                if (!response.success) {
                    finishFix('Error: ' + (response.data || 'Unknown'), true);
                    return;
                }

                var data = response.data;
                fixFixed  += data.fixed  || 0;
                fixFailed += data.failed || 0;
                fixOffset += data.processed || 0;

                var pct = fixTotal > 0 ? Math.round((fixOffset / fixTotal) * 100) : 0;
                $('#fix-thumbnails-bar').css('width', pct + '%');
                $('#fix-thumbnails-status').text(
                    fixOffset + ' / ' + fixTotal + ' — fixed: ' + fixFixed + ', failed: ' + fixFailed
                );

                if (data.has_more && fixRunning) {
                    setTimeout(processFixBatch, 300);
                } else {
                    finishFix('Done. Fixed: ' + fixFixed + ', Failed: ' + fixFailed);
                }
            },
            error: function(xhr, status, error) {
                finishFix('Request failed: ' + error, true);
            }
        });
    }

    function finishFix(message, isError) {
        fixRunning = false;
        $('#fix-all-thumbnails').prop('disabled', false);
        $('#fix-thumbnails-result')
            .css('color', isError ? '#d63638' : '#00a32a')
            .text(message);
        if (fixTotal > 0) {
            var pct = Math.round(((fixFixed + fixFailed) / fixTotal) * 100);
            $('#fix-thumbnails-bar').css('width', pct + '%');
        }
    }
});
