(function ($) {
    'use strict';

    function ajax_call(data, success, error) {
        // Add the nonce to the data object
        data.nonce = upcasted_offload_s3_params.nonce;
        
        jQuery.ajax({
            url: upcasted_offload_s3_params.ajaxurl,
            data: data,
            type: 'POST',
            dataType: 'json',
            success: function (response) {
                success(response);
            },
            error: function (response) {
                error(response);
            }
        });
    }

    function trigger_upcasted_change_s3_provider() {
        $('#upcasted-save-s3-provider').on('click', function () {
            const selected_s3_provider = $("#upcasted-select-s3-provider");
            change_s3_provider_event(selected_s3_provider);
        });
    }

    function change_s3_provider_event(selected_s3_provider) {
        ajax_call({
            'action': 'set_s3_provider',
            'selected_s3_provider': selected_s3_provider.val()
        }, function (response) {
            window.location.reload();
        }, function (response) {
            display_modal_error(response);
        });
    }

    function close_upcasted_modal() {
        const modal = $('.upcasted-modal');
        $('.upcasted-modal-content').on('click', function () {
            event.stopPropagation();
        });
        modal.on('click', function () {
            modal.addClass('hidden');
        });
        $('.upcasted-close-modal-button').on('click', function () {
            modal.addClass('hidden');
        });
    }

    function on_region_change() {
        $("#upcasted_offload_select_region").change(function () {
            var value = $(this).children(':selected').val();
            $("#upcasted_offload_region").focus().val(value);
        });
    }

    function trigger_upcasted_save_settings() {
        $('#upcasted-save-settings, #change-current-bucket').on('click', function () {
            const access_key_id = $("input[name='upcasted_s3_offload_access_key_id']");
            const secret_access_key = $("input[name='upcasted_s3_offload_secret_access_key']");
            const region = $("input[name='upcasted_offload_region']");
            const custom_endpoint = $("input[name='upcasted_custom_endpoint']");

            $('.upcasted-missing-mandatory-fields').remove();
            check_mandatory_field(access_key_id);
            check_mandatory_field(secret_access_key);
            if ('' === custom_endpoint.val()) {
                check_mandatory_field(region);
            }
            init_modal();
            if (0 === $('.upcasted-missing-mandatory-fields').size()) {
                if ($(this).attr('id') !== 'change-current-bucket') {
                    change_bucket_event(access_key_id, secret_access_key, region, custom_endpoint);
                } else {
                    if (confirm('!WARNING: Changing your bucket can break your file delivery because you can only serve files from one bucket. Are you sure that you want to change the bucket?')) {
                        change_bucket_event(access_key_id, secret_access_key, region, custom_endpoint);
                    } else {
                        $('.upcasted-tools-container ').removeClass('hidden');
                    }
                }
            }

        });
    }

    function change_bucket_event(access_key_id, secret_access_key, region, custom_endpoint) {
        ajax_call({
            'action': 'upcasted_offload_connect',
            'access_key_id': access_key_id.val(),
            'secret_access_key': secret_access_key.val(),
            'region': region.val(),
            'custom_endpoint': custom_endpoint.val()
        }, function (response) {
            if (response.success) {
                const buckets = response.data; // Use `response.data` as sent by `wp_send_json_success`
                // Clear any existing bucket options
                $('.upcasted-buckets-list').empty();
                if (Array.isArray(buckets) && buckets.length > 0) {
                    $('.upcasted-modal-error').addClass('hidden');
                    $('#select-bucket-modal').removeClass('hidden');
                    $('.upcasted-modal-result').removeClass('hidden');
                    // Append new bucket options
                    $.each(buckets, function (index, value) {
                        $('.upcasted-buckets-list').append($('<option />').text(value));
                    });
                } else {
                    // No buckets found, show custom bucket input
                    $('#select-bucket-modal').removeClass('hidden');
                    $('.upcasted-custom-bucket-name').removeClass('hidden');
                }
            } else {
                // Handle error response: pass the full error object so indications are available
                display_modal_error(response.data || { message: 'An unexpected error occurred.' });
            }
        },
        function (error) {
            // Generic error handling
            display_modal_error(error.responseJSON?.data || { message: 'An unexpected error occurred.' });
        });
    }

    function trigger_upcasted_save_bucket() {
        $('#upcasted-save-bucket').on('click', function () {
            const bucket = $("select[name='upcasted_s3_offload_bucket']");
            check_mandatory_field(bucket);
            if (0 === $('.upcasted-missing-mandatory-fields').size()) {
                select_bucket_event(bucket.val());
            }
        });
        $('#upcasted-save-bucket-name').on('click', function () {
            const bucket = $("input[name='upcasted_write_bucket_name']");
            check_mandatory_field(bucket);
            if (0 === $('.upcasted-missing-mandatory-fields').size()) {
                select_bucket_event(bucket.val());
            }
        });
    }

    function select_bucket_event(bucket) {
        // Cache jQuery selectors - only S3 connection settings
        const $accessKeyId = $("input[name='upcasted_s3_offload_access_key_id']");
        const $secretAccessKey = $("input[name='upcasted_s3_offload_secret_access_key']");
        const $region = $("input[name='upcasted_offload_region']");
        const $customEndpoint = $("input[name='upcasted_custom_endpoint']");
    
        // Prepare data for AJAX call - only credentials and bucket
        const data = {
            action: 'upcasted_init',
            access_key_id: $accessKeyId.val(),
            secret_access_key: $secretAccessKey.val(),
            custom_endpoint: $customEndpoint.val(),
            region: $region.val(),
            bucket: bucket
        };
    
        // Execute AJAX call
        ajax_call(
            data,
            function(response) {
                if (response.success) {
                    // Hide modal and show tools container
                    $('.upcasted-modal').addClass('hidden');
                    $('.upcasted-tools-container').removeClass('hidden');
                    // Reset active buttons if necessary
                    remove_active_buttons();
                    // Update the current bucket display
                    $('.upcasted-current-bucket span strong').text(bucket);
                } else {
                    // Handle server-side errors: pass the full error object so indications are available
                    display_modal_error(response.data || { message: 'An unexpected error occurred.' });
                }
            },
            function(error) {
                // Handle AJAX errors
                display_modal_error(error.responseJSON?.data || { message: 'An unexpected error occurred.' });
            }
        );
    }    

    function trigger_upcasted_create_bucket() {
        // Attach click event to the button
        $('#upcasted-create-bucket').on('click', function () {
            const bucket_name = $("input[name='upcasted_created_bucket']").val();
    
            // Check if bucket name is empty
            if (bucket_name === '') {
                display_modal_error('Bucket name cannot be empty.');
                return;
            }
    
            // Make AJAX call to create bucket
            ajax_call(
                {
                    action: 'upcasted_create_bucket', // WordPress AJAX action
                    bucket_name: bucket_name
                },
                function (response) {
                    // Handle successful response
                    if (response.success) {
                        select_bucket_event(bucket_name); // Proceed to select bucket event
                    } else {
                        display_modal_error(response.data || 'An unknown error occurred.');
                    }
                },
                function (errorResponse) {
                    // Handle AJAX error response
                    display_modal_error(errorResponse.responseJSON?.data || 'An unexpected error occurred.');
                }
            );
        });
    }    

    function display_error(message) {
        const error_div = $('.upcasted-tools-error');
        error_div.removeClass('hidden');
        error_div.text(message);
    }

    function remove_error() {
        $('.upcasted-tools-error').addClass('hidden');
    }

    function display_modal_error(response) {
        $('#select-bucket-modal').removeClass('hidden');
        const error = $('.upcasted-modal-error');
        error.removeClass('hidden');

        let message = '';
        // Try to handle WP JSON responses (success or error)
        if (typeof response === 'object') {
            // AJAX error: check for responseJSON
            if (response.responseJSON) {
                if (typeof response.responseJSON.data === 'string') {
                    message = response.responseJSON.data;
                } else if (response.responseJSON.data && response.responseJSON.data.message) {
                    message = response.responseJSON.data.message;
                } else if (response.responseJSON.message) {
                    message = response.responseJSON.message;
                } else {
                    message = JSON.stringify(response.responseJSON, null, 2);
                }
            } else if (typeof response.data === 'string') {
                message = response.data;
            } else if (response.data && response.data.message) {
                message = response.data.message;
            } else if (response.message) {
                message = response.message;
            } else if (response.responseText) {
                // Raw responseText (HTML or text)
                message = '<pre>' + response.responseText + '</pre>';
            } else if (response.message) {
                message = response.message;
            } else if (typeof response.message === 'string') {
                message = response.message;
            } else {
                message = JSON.stringify(response, null, 2);
            }
            // If still empty, try root-level message property
            if (!message && response.message) {
                message = response.message;
            }
        } else {
            // Not an object, just show as preformatted
            message = '<pre>' + response + '</pre>';
        }

        // If not already wrapped in <pre>, wrap it
        if (!/^<pre>/i.test(message)) {
            message = '<pre>' + message + '</pre>';
        }

        // Show indications if present (check all possible locations)
        let indications = '';
        let ind = null;
        if (response && typeof response === 'object') {
            if (response.indications) {
                ind = response.indications;
            } else if (response.data && response.data.indications) {
                ind = response.data.indications;
            } else if (response.responseJSON && response.responseJSON.indications) {
                ind = response.responseJSON.indications;
            } else if (response.responseJSON && response.responseJSON.data && response.responseJSON.data.indications) {
                ind = response.responseJSON.data.indications;
            }
        }
        if (ind) {
            indications = '<div class="upcasted-error-indications-box"><div class="upcasted-error-indications-title">Troubleshooting Tips</div><div class="upcasted-error-indications-content">' + ind + '</div></div>';
        }

        // Render two separate divs inside .upcasted-modal-error
        let html = '';
        html += '<div class="upcasted-modal-error-main">' + message + '</div>';
        if (indications) {
            html += indications;
        }
        error.html(html);
        $('.upcasted-modal-title').html('Error');
        $('.upcasted-tools-container').addClass('hidden');
    }

    function check_mandatory_field(field) {
        if ('' === field.val()) {
            $('<div class="upcasted-missing-mandatory-fields">Missing mandatory field</div>').insertAfter(field);
        }
    }

    function init_modal() {
        $('#select-bucket-modal').addClass('hidden');
        $('.upcasted-modal-result').addClass('hidden');
        $('.upcasted-modal-error').addClass('hidden');
        $('.upcasted-tools-container').addClass('hidden')
        $('.upcasted-buckets-list option').remove();
    }

    function remove_active_buttons() {
        $('#local-to-s3-button').removeClass('upcasted-active-button');
        $('#s3-to-local-button').removeClass('upcasted-active-button');
    }

    function show_upcasted_helper_text() {
        $("button.upcasted-find-out-more").click(function () {
            $(this).siblings(".upcasted-hidden-help-description").toggle();
        });
    }

    /**
     * Save behavior settings (file types and upload/delete behavior)
     */
    function trigger_save_behavior_settings() {
        $('#upcasted-save-behavior-settings').on('click', function () {
            const message = $('#upcasted-behavior-settings-message');
            const $includedFiletypes = $("select[name='upcasted_s3_offload_included_filetypes']");
            const $keepLocalFiles = $("select[name='upcasted-keep-local-files'] option:selected");
            const $keepS3Files = $("select[name='upcasted-keep-s3-files'] option:selected");
            const $autoUploadToS3 = $("select[name='upcasted-auto-upload-to-s3'] option:selected");
            
            message.text('Saving...').css('color', '#999');
            
            ajax_call({
                'action': 'upcasted_update_behavior_settings',
                'included_filetypes': $includedFiletypes.val(),
                'keep_local_files': $keepLocalFiles.val(),
                'keep_s3_files': $keepS3Files.val(),
                'auto_upload_to_s3': $autoUploadToS3.val()
            }, function (response) {
                if (response.success) {
                    message.text(response.data).css('color', '#46b450');
                    setTimeout(function() {
                        message.text('');
                    }, 3000);
                } else {
                    message.text(response.data || 'Error saving settings').css('color', '#dc3232');
                }
            }, function (error) {
                message.text('Error saving settings').css('color', '#dc3232');
            });
        });
    }

    
    

    function trigger_upcasted_migration_status_checker() {
        let checkerRunning = false;
        let retryRunning = false;
        let progressTimer = null;
        let retryProgressTimer = null;
        let retryPollErrorCount = 0;
        let retryStartTime = 0;

        // Check for saved results and active checks on page load
        loadSavedMigrationResults();
        checkForActiveBackgroundProcess();
        // Retry migration now uses unified progress bar - no separate check needed

        $('#upcasted-run-migration-check').on('click', function() {
            if (checkerRunning) return;
            
            const checkWebp = $('#upcasted-check-webp').is(':checked');
            const direction = $('input[name="upcasted-check-direction"]:checked').val();
            
            // Start background checker
            startBackgroundMigrationCheck(checkWebp, direction);
        });

        $('#upcasted-stop-migration-check').on('click', function() {
            stopBackgroundMigrationCheck();
        });

        $('#upcasted-dismiss-status-message').on('click', function() {
            $('#upcasted-migration-status-message').slideUp();
        });

        // Handle retry migration button
        $(document).on('click', '#upcasted-retry-missing-files', function() {
            if (retryRunning || checkerRunning) return;
            
            const checkWebp = $('#upcasted-check-webp').is(':checked');
            startRetryMigration(checkWebp);
        });

        $(document).on('click', '#upcasted-stop-retry-migration', function() {
            stopRetryMigration();
        });
        


        function checkForActiveBackgroundProcess() {
            ajax_call({
                action: 'upcasted_get_migration_status_progress'
            }, function(response) {
                if (response.success && response.data && response.data.status === 'running') {
                    // Resume monitoring the active background process
                    checkerRunning = true;
                    $('#upcasted-migration-checker-progress').show();
                    $('#upcasted-run-migration-check').prop('disabled', true).text('Running...');
                    $('#upcasted-stop-migration-check').show().prop('disabled', false);
                    $('#upcasted-checker-status').text('Resuming monitoring of background check...');
                    
                    // Start polling immediately
                    startProgressPolling();
                }
            }, function(error) {
                // No active background process or error checking
            });
        }

        function startBackgroundMigrationCheck(checkWebp, direction) {
            checkerRunning = true;
            
            // Reset UI
            $('#upcasted-migration-status-message').hide();
            $('#upcasted-migration-checker-progress').show();
            $('#upcasted-checker-progress-fill').css('width', '0%');
            $('#upcasted-checker-progress-text').text('Starting...');
            $('#upcasted-checker-status').text('Initializing background check...');
            $('#upcasted-run-migration-check').prop('disabled', true).text('Running...');
            $('#upcasted-stop-migration-check').show().prop('disabled', false);
            
            ajax_call({
                action: 'upcasted_start_migration_status_cron',
                check_webp: checkWebp,
                direction: direction || 'local_to_cloud'
            }, function(response) {
                if (response.success) {
                    $('#upcasted-checker-status').text(`Background check started. Processing ${response.data.total_files} attachments...`);
                    
                    // Start polling for progress
                    startProgressPolling();
                } else {
                    showError('Failed to start background check: ' + response.data);
                    resetUI();
                }
            }, function(error) {
                showError('Failed to start background check.');
                resetUI();
            });
        }

        function stopBackgroundMigrationCheck() {
            ajax_call({
                action: 'upcasted_stop_migration_status_cron'
            }, function(response) {
                if (response.success) {
                    $('#upcasted-checker-status').text('Background check stopped.');
                    stopProgressPolling();
                    resetUI();
                }
            }, function(error) {
                showError('Failed to stop background check.');
            });
        }

        function startProgressPolling() {
            if (progressTimer) return;
            
            progressTimer = setInterval(() => {
                pollProgress();
            }, 2000); // Poll every 2 seconds
        }

        function stopProgressPolling() {
            if (progressTimer) {
                clearInterval(progressTimer);
                progressTimer = null;
            }
        }

        function pollProgress() {
            ajax_call({
                action: 'upcasted_get_migration_status_progress'
            }, function(response) {
                if (response.success && response.data) {
                    updateProgressUI(response.data);
                    
                    if (response.data.status === 'completed') {
                        handleCompletion(response.data);
                    } else if (response.data.status === 'error') {
                        showError('Background check failed: ' + response.data.error);
                        resetUI();
                    } else if (response.data.status === 'stopped') {
                        $('#upcasted-checker-status').text('Background check was stopped.');
                        resetUI();
                    }
                } else {
                    // If no progress data found, the background job may have been cleared
                    resetUI();
                }
            }, function(error) {
            });
        }

        function updateProgressUI(data) {
            const progressPercent = data.total > 0 ? Math.round((data.processed / data.total) * 100) : 0;
            $('#upcasted-checker-progress-fill').css('width', progressPercent + '%');
            $('#upcasted-checker-progress-text').text(progressPercent + '%');
            
            const timeElapsed = Math.round((Date.now() / 1000) - data.started_at);
            $('#upcasted-checker-status').text(
                `Processing: ${data.processed}/${data.total} attachments (${timeElapsed}s elapsed)`
            );
        }

        function handleCompletion(data) {
            stopProgressPolling();
            checkerRunning = false;
            
            // Update progress to 100%
            $('#upcasted-checker-progress-fill').css('width', '100%');
            $('#upcasted-checker-progress-text').text('✓ Complete');
            $('#upcasted-stop-migration-check').hide();
            $('#upcasted-run-migration-check').prop('disabled', false).text('Start Migration Status Check');
            
            // Check if there are any missing files
            const totalMissing = (data.missing_main || 0) + (data.missing_thumbnails || 0) + (data.missing_webp || 0);
            
            if (totalMissing === 0) {
                // No missing files - show success message based on direction
                const duration = data.completed_at - data.started_at;
                const direction = data.direction || 'local_to_cloud';
                const message = direction === 'cloud_to_local' 
                    ? `All ${data.total} local attachments have all their files present on the server. No files need to be downloaded from S3!`
                    : `All ${data.total} attachments have all their files successfully stored on S3. No missing files detected!`;
                
                const successHtml = `
                    <div class="upcasted-migration-results" style="border-left-color: #00a32a;">
                        <strong>✓ Migration Status Check Complete (${duration}s):</strong>
                        <p style="color: #00a32a; margin: 10px 0 0 0;">${message}</p>
                    </div>
                `;
                $('#upcasted-checker-status').html(successHtml);
                return;
            }
            
            // Show final results only if there are missing files
            const duration = data.completed_at - data.started_at;
            const direction = data.direction || 'local_to_cloud';
            const locationLabel = direction === 'cloud_to_local' ? 'from Server' : 'from S3';
            
            const statsHtml = `
                <div class="upcasted-migration-results">
                    <strong>Migration Status Results (Completed in ${duration}s):</strong>
                    <ul>
                        <li class="error">Missing Main Images ${locationLabel}: ${data.missing_main}</li>
                        <li class="error">Missing Thumbnails ${locationLabel}: ${data.missing_thumbnails}</li>
                        <li class="error">Missing WebP ${locationLabel}: ${data.missing_webp}</li>
                        <li class="success">Total Attachments: ${data.total}</li>
                        <li class="success">Processed: ${data.processed}</li>
                    </ul>
                    ${addRetryButtonIfNeeded(data)}
                </div>
            `;
            
            $('#upcasted-checker-status').html(statsHtml);
        }

        function loadSavedMigrationResults() {
            ajax_call({
                action: 'upcasted_get_saved_migration_results'
            }, function(response) {
                if (response.success && response.data && Object.keys(response.data).length > 0) {
                    const data = response.data;
                    
                    // Check if there are any missing files
                    const totalMissing = (data.missing_main || 0) + (data.missing_thumbnails || 0) + (data.missing_webp || 0);
                    
                    if (totalMissing === 0) {
                        // No missing files - show success message based on direction
                        const timeAgo = Math.round((Date.now() / 1000) - data.completed_at);
                        const direction = data.direction || 'local_to_cloud';
                        const message = direction === 'cloud_to_local' 
                            ? `All ${data.total} local attachments have all their files present on the server. No files need to be downloaded from S3!`
                            : `All ${data.total} attachments have all their files successfully stored on S3. No missing files detected!`;
                        
                        $('#upcasted-migration-checker-progress').show();
                        $('#upcasted-checker-progress-fill').css('width', '100%');
                        $('#upcasted-checker-progress-text').text('✓ Complete');
                        
                        const successHtml = `
                            <div class="upcasted-migration-results" style="border-left-color: #00a32a;">
                                <strong>✓ Migration Status Check Complete (${formatTimeAgo(timeAgo)}):</strong>
                                <p style="color: #00a32a; margin: 10px 0 0 0;">${message}</p>
                            </div>
                        `;
                        $('#upcasted-checker-status').html(successHtml);
                        return;
                    }
                    
                    const timeAgo = Math.round((Date.now() / 1000) - data.completed_at);
                    
                    // Show saved results only if there are missing files
                    $('#upcasted-migration-checker-progress').show();
                    $('#upcasted-checker-progress-fill').css('width', '100%');
                    $('#upcasted-checker-progress-text').text('✓ Complete');
                    
                    const direction = data.direction || 'local_to_cloud';
                    const locationLabel = direction === 'cloud_to_local' ? 'from Server' : 'from S3';
                    
                    const statsHtml = `
                        <div class="upcasted-migration-results">
                            <strong>Migration Status Results (Completed ${formatTimeAgo(timeAgo)}):</strong>
                            <ul>
                                <li class="error">Missing Main Images ${locationLabel}: ${data.missing_main}</li>
                                <li class="error">Missing Thumbnails ${locationLabel}: ${data.missing_thumbnails}</li>
                                <li class="error">Missing WebP ${locationLabel}: ${data.missing_webp}</li>
                                <li class="success">Total Attachments: ${data.total}</li>
                                <li class="success">Processed: ${data.processed}</li>
                            </ul>
                            ${addRetryButtonIfNeeded(data)}
                        </div>
                    `;
                    $('#upcasted-checker-status').html(statsHtml);
                }
            }, function(error) {
                // No saved results or error - that's fine
            });
        }

        function formatTimeAgo(seconds) {
            if (seconds < 60) return seconds + 's ago';
            if (seconds < 3600) return Math.round(seconds / 60) + 'm ago';
            if (seconds < 86400) return Math.round(seconds / 3600) + 'h ago';
            return Math.round(seconds / 86400) + 'd ago';
        }

        function resetUI() {
            checkerRunning = false;
            stopProgressPolling();
            $('#upcasted-run-migration-check').prop('disabled', false).text('Start Migration Status Check');
            $('#upcasted-stop-migration-check').hide();
        }

        function showError(message) {
            $('#upcasted-checker-status').html(`<span style="color: #d63638;">❌ ${message}</span>`);
        }

        function addRetryButtonIfNeeded(data) {
            const totalMissing = (data.missing_main || 0) + (data.missing_thumbnails || 0) + (data.missing_webp || 0);
            if (totalMissing > 0) {
                // Check if retry is currently running to disable button
                const buttonDisabled = retryRunning ? 'disabled' : '';
                const buttonText = retryRunning ? 'Migration in Progress' : `Retry Migration of Missing Files (${totalMissing} files)`;
                
                return `
                    <div class="upcasted-retry-migration-section">
                        <button id="upcasted-retry-missing-files" class="upcasted-retry-button" ${buttonDisabled}>
                            ${buttonText}
                        </button>
                        <button id="upcasted-stop-retry-migration" class="upcasted-retry-button" style="display: ${retryRunning ? 'inline-block' : 'none'}; margin-left: 10px;">
                            Stop Retry
                        </button>
                        <div id="upcasted-retry-progress" style="display: ${retryRunning ? 'block' : 'none'}; margin-top: 10px;">
                            <div style="background: #f1f1f1; border-radius: 4px; overflow: hidden; height: 20px;">
                                <div id="upcasted-retry-progress-fill" style="background: #007cba; height: 100%; width: 0%; transition: width 0.3s;"></div>
                            </div>
                            <div id="upcasted-retry-status" style="margin-top: 5px; font-size: 12px;">Ready to retry...</div>
                        </div>
                    </div>
                `;
            }
            return '';
        }

        function startRetryMigration(checkWebp) {
            // Use same approach as regular migrations - start cron and reload page
            $('#upcasted-retry-missing-files').prop('disabled', true).text('Starting...');
            
            const cronMessage = $('.upcasted-cron-message');
            
            ajax_call({
                action: 'upcasted_start_retry_migration_cron',
                check_webp: checkWebp
            }, function(response) {
                if (response.success) {
                    // Show countdown message like regular migrations
                    cronMessage.removeClass('hidden').text('Retry migration started. Please reload the page to see the progress. The screen will refresh in ');
                    startCountdown(5, cronMessage);
                } else {
                    showRetryError('Failed to start retry migration: ' + (response.data || 'Unknown error'));
                    $('#upcasted-retry-missing-files').prop('disabled', false).text('Retry Migration');
                }
            }, function(error) {
                console.error('Retry migration AJAX error:', error);
                showRetryError('Failed to start retry migration.');
                $('#upcasted-retry-missing-files').prop('disabled', false).text('Retry Migration');
            });
        }

        function stopRetryMigration() {
            ajax_call({
                action: 'upcasted_stop_retry_migration_cron'
            }, function(response) {
                if (response.success) {
                    $('#upcasted-retry-status').text('Retry migration stopped.');
                    stopRetryProgressPolling();
                    resetRetryUI();
                }
            }, function(error) {
                showRetryError('Failed to stop retry migration.');
            });
        }

        function startRetryProgressPolling() {
            if (retryProgressTimer) return;
            
            retryProgressTimer = setInterval(() => {
                pollRetryProgress();
            }, 2000);
        }

        function stopRetryProgressPolling() {
            if (retryProgressTimer) {
                clearInterval(retryProgressTimer);
                retryProgressTimer = null;
            }
        }

        function pollRetryProgress() {
            ajax_call({
                action: 'upcasted_get_retry_migration_progress'
            }, function(response) {
                if (response.success && response.data) {
                    updateRetryProgressUI(response.data);
                    
                    // Check if finished (backend uses 'finished' flag, not 'status')
                    if (response.data.finished) {
                        handleRetryCompletion(response.data);
                    } else if (response.data.status === 'error' || response.data.error) {
                        showRetryError('Retry migration failed: ' + (response.data.error || 'Unknown error'));
                        resetRetryUI();
                    } else if (response.data.stopped) {
                        $('#upcasted-retry-status').text('Retry migration was stopped.');
                        resetRetryUI();
                    }
                } else {
                    // Check if we should try to restart the migration (in case it was interrupted)
                    if (retryRunning) {
                        $('#upcasted-retry-status').text('Migration appears interrupted. Checking status...');
                        
                        // Wait a bit longer for recovery
                        setTimeout(() => {
                            if (retryRunning) {
                                showRetryError('Migration appears to have stopped unexpectedly. Please try again.');
                                resetRetryUI();
                            }
                        }, 10000);
                    } else {
                        resetRetryUI();
                    }
                }
            }, function(error) {
                // Continue polling for a while in case of temporary network issues
                retryPollErrorCount = (retryPollErrorCount || 0) + 1;
                if (retryPollErrorCount >= 5 && retryRunning) {
                    showRetryError('Lost connection to migration process. Please check manually.');
                    resetRetryUI();
                }
            });
        }

        function updateRetryProgressUI(data) {
            const progressPercent = data.total_missing > 0 ? Math.round((data.processed / data.total_missing) * 100) : 0;
            $('#upcasted-retry-progress-fill').css('width', progressPercent + '%');
            
            const timeElapsed = Math.round((Date.now() / 1000) - data.started_at);
            $('#upcasted-retry-status').text(
                `Retrying: ${data.processed}/${data.total_missing} files (${timeElapsed}s elapsed)`
            );

            // Force completion after 2 minutes if progress seems stuck
            if (timeElapsed > 120 && data.processed >= data.total_missing) {
                $('#upcasted-retry-status').text('Migration appears complete but still processing. Forcing completion...');
                setTimeout(() => {
                    if (retryRunning) {
                        forceRetryCompletion(data);
                    }
                }, 3000);
            }
        }

        function handleRetryCompletion(data) {
            stopRetryProgressPolling();
            retryRunning = false;
            
            // Update progress to 100%
            $('#upcasted-retry-progress-fill').css('width', '100%');
            $('#upcasted-stop-retry-migration').hide();
            
            // Calculate duration
            const duration = data.duration || (data.completed_at ? data.completed_at - data.start : 0);
            const migrated = (data.processed || 0) - (data.failed || 0);
            
            // If there were failures, show results
            if (data.failed > 0) {
                $('#upcasted-retry-missing-files').prop('disabled', false).text('Retry Migration Complete');
                
                const retryResultsHtml = `
                    <div class="upcasted-migration-results" style="margin-top: 15px; border-left-color: ${data.failed > 0 ? '#d63638' : '#00a32a'};">
                        <strong>Retry Migration Results (Completed in ${duration}s):</strong>
                        <ul>
                            <li class="success">Successfully Migrated: ${migrated}</li>
                            <li class="error">Failed to Migrate: ${data.failed}</li>
                            <li class="success">Total Processed: ${data.processed || 0}</li>
                        </ul>
                    </div>
                `;
                
                $('#upcasted-retry-progress').after(retryResultsHtml);
                $('#upcasted-retry-status').text(data.failed > 0 ? '⚠ Retry completed with failures' : '✓ Retry migration completed!');
            } else {
                // No failures - hide the entire retry section
                $('.upcasted-retry-migration-section').fadeOut(300, function() {
                    $(this).remove();
                });
            }
        }

        function resetRetryUI() {
            retryRunning = false;
            retryPollErrorCount = 0;
            retryStartTime = 0;
            stopRetryProgressPolling();
            $('#upcasted-retry-missing-files').prop('disabled', false).text('Retry Migration of Missing Files');
            $('#upcasted-stop-retry-migration').hide();
        }

        function forceRetryCompletion(data) {
            // Force stop the retry migration
            ajax_call({
                action: 'upcasted_force_complete_retry_migration'
            }, function(response) {
                // Simulate completion
                const completionData = {
                    ...data,
                    status: 'completed',
                    completed_at: Math.floor(Date.now() / 1000)
                };
                handleRetryCompletion(completionData);
            }, function(error) {
                // Force local completion even if server call fails
                const completionData = {
                    ...data,
                    status: 'completed',
                    completed_at: Math.floor(Date.now() / 1000)
                };
                handleRetryCompletion(completionData);
            });
        }

        function showRetryError(message) {
            $('#upcasted-retry-status').html(`<span style="color: #d63638;">❌ ${message}</span>`);
        }
    }

    function add_s3_filter_to_media_library() {
        // Wait for wp.media to be ready
        if (typeof wp !== 'undefined' && wp.media && wp.media.view) {
            // Run the code only on the Media Library page
            if (typeof pagenow !== 'undefined' && pagenow === 'upload') {
                // Save the original render function for later use
                const originalRender = wp.media.view.Attachment.Library.prototype.render;

                // Extend the Media Library view to add the cloud icon
                wp.media.view.Attachment.Library = wp.media.view.Attachment.Library.extend({
                    render: function () {
                        // Call the original render method
                        originalRender.apply(this, arguments);

                        // Check if the attachment has the custom property
                        if (this.model.get('is_cloud')) {
                            // Add a cloud icon overlay
                            if (!this.$el.find('.cloud-icon').length) { // Prevent duplicate icons
                                this.$el.addClass('upcasted-cloud-attachment');
                                this.$el.append('<span class="dashicons dashicons-cloud cloud-icon" title="File stored on S3"></span>');
                            }
                        }

                        return this;
                    }
                });
            }
        }
    };


    function upcasted_dismiss_notice() {
        $('#dismiss-upcasted-notice').on('click', function(e) {
            e.preventDefault();
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'dismiss_finished_cron_admin_notice',
                },
                success: function(response) {
                    if (response.success) {
                        $('.notice-success').fadeOut(); // Hide the notice
                    }
                }
            });
        });
    }

    function upcasted_toggle_info_panel() {
        window.upcasted_toggle_info_panel = function() {
            const infoPanel = $('.upcasted-plugin-info');
            const button = $('#toggle-info');
        
            if (infoPanel.is(':hidden')) {
                infoPanel.css('display', 'flex');
                button.text('Close Info Panel');
            } else {
                infoPanel.css('display', 'none');
                button.text('Read More');
            }
        };
      
        // Attach the function to the button click event
        $('#toggle-info').click(function() {
            upcasted_toggle_info_panel();
        });
    }

    $(document).ready(function () {
        upcasted_toggle_info_panel();
        trigger_upcasted_change_s3_provider();
        trigger_upcasted_create_bucket();
        trigger_upcasted_save_bucket();
        on_region_change();
        close_upcasted_modal();
        trigger_upcasted_save_settings();
        upcasted_dismiss_notice();
        add_s3_filter_to_media_library();
        show_upcasted_helper_text();
        trigger_save_behavior_settings();
        
    });

})
(jQuery);
