/**
 * Sequential Health Issues Module
 * Handles fetching health issues one by one with a delay between requests
**/
(function($, rankLocalizedData) {
    'use strict';
    
    // Module variables
    let issueTypes = [];
    let currentIndex = 0;
    let isProcessing = false;
    let $healthIssuesContainer;
    let $loadingIndicator;
    let $globalCreditStatusArea;
    let processedIssues = {};
    let lastCrawledAt = null;
    
    // Initialize the module
    function init(elements) {
        $healthIssuesContainer = elements.healthIssuesContainer || $('#rank-health-issues-container');
        $loadingIndicator = elements.healthIssuesLoading || $('#rank-health-issues-loading');
        $globalCreditStatusArea = elements.globalCreditStatusArea || $('#rank-global-credit-status');
        
        // Ensure rank.state is initialized
        rank.state = rank.state || {};
        
        // Initialize URL list modal if available
        if (rank.urlListModal && typeof rank.urlListModal.init === 'function') {
            rank.urlListModal.init();
        }
        
        // Check if we're on the health issues tab and load issues
        if ($healthIssuesContainer.length > 0) {
            loadHealthIssuesOverview();
        }
    }
    
    /**
     * Load the initial health issues overview structure
     */
    function loadHealthIssuesOverview() {
        // Clear processing area when loading health issues overview
        if (rank.processing && typeof rank.processing.clearProcessingArea === 'function') {
            rank.processing.clearProcessingArea();
        } else {
            // Fallback if the function isn't available
            if (rank.elements && rank.elements.processingArea) {
                rank.elements.processingArea.hide();
            }
            if (rank.elements && rank.elements.healthIssuesContainer) {
                rank.elements.healthIssuesContainer.show();
            }
        }
        
        // Show multilingual notice when in overview mode
        $('#rank-multilingual-notice').show();
        
        if (!$healthIssuesContainer.length || !$loadingIndicator.length) {
            console.error('RANK AI: Critical UI elements (issues container or loading indicator) not found.');
            if ($loadingIndicator.length) $loadingIndicator.hide();
            return;
        }
        
        // Check if rankLocalizedData is available
        if (!rankLocalizedData || typeof rankLocalizedData !== 'object' || !rankLocalizedData.ajax_url || !rankLocalizedData.nonce) {
            console.error('RANK AI: rankLocalizedData is missing or incomplete (ajax_url, nonce). Current value:', rankLocalizedData);
            $loadingIndicator.hide();
            $healthIssuesContainer.html(`<p style="color: red;">Error: Plugin localization data (rankLocalizedData) is missing or incomplete. Cannot load health issues. Please check browser console.</p>`).show();
            return;
        }
        
        // Show the container with just the heading, description, and loading indicator
        $healthIssuesContainer.show();
        $loadingIndicator.show();
        
        // Save the heading, description, and loading indicator before clearing the rest
        const $heading = $healthIssuesContainer.find('h2').first();
        const $description = $healthIssuesContainer.find('p.description').first();
        const $loadingSection = $loadingIndicator.detach(); // Remove but keep reference
        
        // Clear all other content except what we saved
        $healthIssuesContainer.children().not($heading).not($description).remove();
        
        // Re-add the heading, description, and loading indicator
        if ($heading.length === 0 || $description.length === 0) {
            // If heading and description weren't found, add them manually
            $healthIssuesContainer.empty().append('<h2>Fix health problems automatically</h2>')
                              .append('<p class="description">Get all pages on your website fixed automatically for each health problem found in your Morningscore account.</p>');
        }
        
        // Add the loading indicator back after the heading and description
        $healthIssuesContainer.append($loadingSection);
        
        // Make the initial request using the new optimized overview endpoint
        const request = rank.helpers.trackAjaxRequest($.ajax({
            url: rankLocalizedData.ajax_url,
            type: 'POST',
            data: {
                action: 'rank_get_health_issues_overview_optimized',
                nonce: rankLocalizedData.nonce
            },
            success: function(response) {
                if (rank.state && rank.state.isBackgroundProcessing) {
                    return;
                }
                if (response.success && response.data) {
                    // --- CREDIT HANDLING ---
                    let creditsInfo = { remaining: 0, total: 0 }; // Default structure
                    if (response.data.credits && typeof response.data.credits.limit !== 'undefined' && typeof response.data.credits.usage !== 'undefined') {
                        creditsInfo.total = parseInt(response.data.credits.limit, 10);
                        creditsInfo.remaining = parseInt(response.data.credits.limit, 10) - parseInt(response.data.credits.usage, 10);
                        // Ensure remaining is not negative
                        if (creditsInfo.remaining < 0) {
                            creditsInfo.remaining = 0;
                        }
                    } else {
                        console.warn('Credits data missing or incomplete. Using defaults.');
                    }
                    // --- END CREDIT HANDLING ---
                    
                    // Update global credit display
                    if ($globalCreditStatusArea.length) {
                        $globalCreditStatusArea.text(`AI Credits left: ${creditsInfo.remaining} / ${creditsInfo.total}`);
                    }
                    
                    // Process the optimized response - no sequential processing needed!
                    processOptimizedOverviewResponse(response.data);
                } else {
                    // AJAX call was successful but response.success was false or no data
                    const errorMessage = response.data && response.data.message ? response.data.message : (response.data || 'Unknown error');
                    const errorCode = response.data && response.data.debug_info && response.data.debug_info.error_code ? response.data.debug_info.error_code : '';
                    $loadingIndicator.hide();
                    
                    // Clear the container and re-add heading/description
                    $healthIssuesContainer.empty();
                    $healthIssuesContainer.append('<h2>Fix health problems automatically</h2>')
                                      .append('<p class="description">Get all pages on your website fixed automatically for each health problem found in your Morningscore account.</p>');
                    
                    // Check for specific error types and display appropriate messages
                    if (errorCode === 'inactive_account' || (response.data && response.data.message && response.data.message.toLowerCase().includes('inactive'))) {
                        // Display specific message for inactive account error
                        $healthIssuesContainer.append(`<div class="rank-connection-error"><p>⚠️ It seems your API is not active. You need an active account to use the API. Write us in our chat if you believe this is wrong 💬</p></div>`);
                    } else if (response.data && response.data.message && response.data.message.includes('domain was not found in your Morningscore account')) {
                        // Display specific message for domain not found error
                        $healthIssuesContainer.append(`<div class="rank-connection-error"><p>⚠️ This website was not found in your Morningscore account. Please write us in our chat if you need help 💬</p></div>`);
                    } else {
                        $healthIssuesContainer.append(`<div class="rank-connection-error"><p>⚠️ ${rankLocalizedData.text_error_loading_issues || 'Error loading health issues:'} ${errorMessage} Please write us in our chat 💬</p></div>`);
                    }
                    
                    // Display debug info if available (for support screenshots)
                    if (response.data && response.data.debug_info) {
                        const debugInfo = response.data.debug_info;
                        let debugHtml = `
                            <div class="rank-debug-info" style="
                                background: #f8f9fa;
                                border: 1px solid #dee2e6;
                                border-radius: 4px;
                                padding: 15px;
                                margin-top: 15px;
                                font-family: monospace;
                                font-size: 12px;
                                max-height: 300px;
                                overflow-y: auto;
                                text-align: left;
                            ">
                                <p style="margin: 0 0 10px 0; font-weight: bold; color: #495057;">📋 Debug Information (screenshot this for support):</p>
                                <table style="width: 100%; border-collapse: collapse;">`;
                        
                        // Add each debug field
                        if (debugInfo.timestamp) {
                            debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap;">Timestamp:</td><td style="padding: 3px 0; word-break: break-all;">${debugInfo.timestamp}</td></tr>`;
                        }
                        if (debugInfo.error_code) {
                            debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap;">Error Code:</td><td style="padding: 3px 0; word-break: break-all;">${debugInfo.error_code}</td></tr>`;
                        }
                        if (debugInfo.error_message) {
                            debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap;">Error Message:</td><td style="padding: 3px 0; word-break: break-all;">${debugInfo.error_message}</td></tr>`;
                        }
                        if (debugInfo.http_status) {
                            debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap;">HTTP Status:</td><td style="padding: 3px 0; word-break: break-all;">${debugInfo.http_status}</td></tr>`;
                        }
                        if (debugInfo.site_url) {
                            debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap;">Site URL:</td><td style="padding: 3px 0; word-break: break-all;">${debugInfo.site_url}</td></tr>`;
                        }
                        if (debugInfo.wp_version) {
                            debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap;">WP Version:</td><td style="padding: 3px 0; word-break: break-all;">${debugInfo.wp_version}</td></tr>`;
                        }
                        if (debugInfo.php_version) {
                            debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap;">PHP Version:</td><td style="padding: 3px 0; word-break: break-all;">${debugInfo.php_version}</td></tr>`;
                        }
                        if (debugInfo.original_error) {
                            debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap;">Original Error:</td><td style="padding: 3px 0; word-break: break-all;">${debugInfo.original_error}</td></tr>`;
                        }
                        if (debugInfo.api_response) {
                            // Escape HTML and truncate if too long
                            let apiResponse = debugInfo.api_response;
                            if (apiResponse.length > 500) {
                                apiResponse = apiResponse.substring(0, 500) + '...';
                            }
                            // Basic HTML escaping
                            apiResponse = apiResponse.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
                            debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap; vertical-align: top;">API Response:</td><td style="padding: 3px 0; word-break: break-all;"><pre style="margin: 0; white-space: pre-wrap; font-size: 11px; background: #e9ecef; padding: 5px; border-radius: 3px;">${apiResponse}</pre></td></tr>`;
                        }
                        
                        debugHtml += `</table></div>`;
                        
                        $healthIssuesContainer.append(debugHtml);
                    }
                    
                    $healthIssuesContainer.show();
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                if (rank.state && rank.state.isBackgroundProcessing) {
                    return;
                }
                $loadingIndicator.hide();
                
                // If the request was aborted, don't show an error message
                if (textStatus === 'abort') {
                    return;
                }
                
                console.error('AJAX Error in loadHealthIssuesOverview:', {
                    textStatus: textStatus,
                    errorThrown: errorThrown,
                    status: jqXHR.status,
                    readyState: jqXHR.readyState,
                    responseText: jqXHR.responseText,
                    jqXHR: jqXHR
                });
                
                // Clear the issues container completely to remove any previous content
                $healthIssuesContainer.empty();
                
                // Re-add the heading and description
                $healthIssuesContainer.append('<h2>Fix health problems automatically</h2>')
                                  .append('<p class="description">Get all pages on your website fixed automatically for each health problem found in your Morningscore account.</p>');
                
                // Create grid container if it doesn't exist
                let $gridContainer = $healthIssuesContainer.find('.rank-issues-grid');
                if ($gridContainer.length === 0) {
                    $gridContainer = $('<div class="rank-issues-grid"></div>');
                    $healthIssuesContainer.append($gridContainer);
                }
                
                // Grid container is created but notification will be added conditionally in finishProcessing
                
                // Only show error message for non-abort errors
                let detailedError = `Connection issue: ${textStatus}.`;
                if (errorThrown) {
                    detailedError += ` errorThrown: ${errorThrown}.`;
                }
                if (jqXHR.status !== undefined) {
                     detailedError += ` HTTP Code: ${jqXHR.status}.`;
                }
                
                // Check if this is a domain not found error and extract debug info
                let responseData = null;
                let debugInfo = null;
                try {
                    responseData = JSON.parse(jqXHR.responseText);
                    // Extract debug_info if available from server
                    if (responseData && responseData.data && responseData.data.debug_info) {
                        debugInfo = responseData.data.debug_info;
                    }
                } catch (e) {
                    // Not valid JSON, continue with default error message
                }
                
                // If no debug_info from server, create one from available data
                // This ensures we always have debug info for support screenshots
                if (!debugInfo) {
                    debugInfo = {
                        timestamp: new Date().toISOString(),
                        error_code: 'ajax_error',
                        error_message: responseData && responseData.data && responseData.data.message
                            ? responseData.data.message
                            : (textStatus + (errorThrown ? ': ' + errorThrown : '')),
                        http_status: jqXHR.status || 'N/A',
                        ready_state: jqXHR.readyState || 'N/A',
                        site_url: window.location.origin,
                        response_headers: jqXHR.getAllResponseHeaders ? jqXHR.getAllResponseHeaders().substring(0, 500) : 'N/A',
                        api_response: jqXHR.responseText ? jqXHR.responseText.substring(0, 2000) : 'No response body'
                    };
                }
                
                // Check for specific error types in the response
                const errorCode = responseData && responseData.data && responseData.data.debug_info && responseData.data.debug_info.error_code 
                    ? responseData.data.debug_info.error_code 
                    : '';
                const errorMessageFromServer = responseData && responseData.data && responseData.data.message 
                    ? responseData.data.message 
                    : '';
                
                if (errorCode === 'inactive_account' || errorMessageFromServer.toLowerCase().includes('inactive')) {
                    // Display specific message for inactive account error
                    $healthIssuesContainer.append(`<div class="rank-connection-error"><p>⚠️ It seems your API is not active. You need an active account to use the API. Write us in our chat if you believe this is wrong 💬</p></div>`);
                } else if (responseData &&
                    responseData.success === false &&
                    responseData.data &&
                    responseData.data.message &&
                    responseData.data.message.includes('domain was not found in your Morningscore account')) {
                    // Display specific message for domain not found error
                    $healthIssuesContainer.append(`<div class="rank-connection-error"><p>⚠️ This website was not found in your Morningscore account. Please write us in our chat if you need help 💬</p></div>`);
                } else {
                    // Display generic error message for other errors
                    $healthIssuesContainer.append(`<div class="rank-connection-error"><p>⚠️ Could not connect to Morningscore. ${detailedError} Please write us in our chat 💬</p></div>`);
                }
                
                // Display debug info box if available (for support screenshots)
                if (debugInfo) {
                    let debugHtml = `
                        <div class="rank-debug-info" style="
                            background: #f8f9fa;
                            border: 1px solid #dee2e6;
                            border-radius: 4px;
                            padding: 15px;
                            margin-top: 15px;
                            font-family: monospace;
                            font-size: 12px;
                            max-height: 300px;
                            overflow-y: auto;
                            text-align: left;
                        ">
                            <p style="margin: 0 0 10px 0; font-weight: bold; color: #495057;">📋 Debug Information (screenshot this for support):</p>
                            <table style="width: 100%; border-collapse: collapse;">`;
                    
                    // Add each debug field
                    if (debugInfo.timestamp) {
                        debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap;">Timestamp:</td><td style="padding: 3px 0; word-break: break-all;">${debugInfo.timestamp}</td></tr>`;
                    }
                    if (debugInfo.error_code) {
                        debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap;">Error Code:</td><td style="padding: 3px 0; word-break: break-all;">${debugInfo.error_code}</td></tr>`;
                    }
                    if (debugInfo.error_message) {
                        debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap;">Error Message:</td><td style="padding: 3px 0; word-break: break-all;">${debugInfo.error_message}</td></tr>`;
                    }
                    if (debugInfo.http_status) {
                        debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap;">HTTP Status:</td><td style="padding: 3px 0; word-break: break-all;">${debugInfo.http_status}</td></tr>`;
                    }
                    if (debugInfo.ready_state) {
                        debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap;">Ready State:</td><td style="padding: 3px 0; word-break: break-all;">${debugInfo.ready_state}</td></tr>`;
                    }
                    if (debugInfo.site_url) {
                        debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap;">Site URL:</td><td style="padding: 3px 0; word-break: break-all;">${debugInfo.site_url}</td></tr>`;
                    }
                    if (debugInfo.wp_version) {
                        debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap;">WP Version:</td><td style="padding: 3px 0; word-break: break-all;">${debugInfo.wp_version}</td></tr>`;
                    }
                    if (debugInfo.php_version) {
                        debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap;">PHP Version:</td><td style="padding: 3px 0; word-break: break-all;">${debugInfo.php_version}</td></tr>`;
                    }
                    if (debugInfo.memory_usage) {
                        debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap;">Memory Usage:</td><td style="padding: 3px 0; word-break: break-all;">${debugInfo.memory_usage}</td></tr>`;
                    }
                    if (debugInfo.memory_peak) {
                        debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap;">Memory Peak:</td><td style="padding: 3px 0; word-break: break-all;">${debugInfo.memory_peak}</td></tr>`;
                    }
                    if (debugInfo.original_error) {
                        debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap;">Original Error:</td><td style="padding: 3px 0; word-break: break-all;">${debugInfo.original_error}</td></tr>`;
                    }
                    if (debugInfo.response_headers) {
                        // Escape HTML
                        let headers = debugInfo.response_headers;
                        headers = headers.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
                        debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap; vertical-align: top;">Response Headers:</td><td style="padding: 3px 0; word-break: break-all;"><pre style="margin: 0; white-space: pre-wrap; font-size: 11px; background: #e9ecef; padding: 5px; border-radius: 3px;">${headers}</pre></td></tr>`;
                    }
                    if (debugInfo.api_response) {
                        // Escape HTML and truncate if too long
                        let apiResponse = debugInfo.api_response;
                        if (apiResponse.length > 1000) {
                            apiResponse = apiResponse.substring(0, 1000) + '...';
                        }
                        // Basic HTML escaping
                        apiResponse = apiResponse.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
                        debugHtml += `<tr><td style="padding: 3px 10px 3px 0; color: #6c757d; white-space: nowrap; vertical-align: top;">API Response:</td><td style="padding: 3px 0; word-break: break-all;"><pre style="margin: 0; white-space: pre-wrap; font-size: 11px; background: #e9ecef; padding: 5px; border-radius: 3px;">${apiResponse}</pre></td></tr>`;
                    }
                    
                    debugHtml += `</table></div>`;
                    
                    $healthIssuesContainer.append(debugHtml);
                }
                
                // Make sure the container is visible
                $healthIssuesContainer.show();
            }
        }));
    }
    
    /**
     * Process the optimized overview response (no sequential processing needed)
     */
    function processOptimizedOverviewResponse(data) {
        // Store crawled_at early so it's available in all display paths
        lastCrawledAt = data.crawled_at || null;
        
        // Check if a health scan is currently running
        if (data.crawl_status === 'crawling') {
            displayCrawlingInProgress();
            return;
        }
        
        // Check if the crawl data is too old (older than 30 days)
        if (data.is_data_too_old === true) {
            displayDataTooOldWarning();
            return;
        }
        
        // Create a grid container for the issue boxes if it doesn't exist
        let $gridContainer = $healthIssuesContainer.find('.rank-issues-grid');
        if ($gridContainer.length === 0) {
            $gridContainer = $('<div class="rank-issues-grid"></div>');
            $healthIssuesContainer.append($gridContainer);
        }
        
        // Process all issues at once from the optimized response
        const issues = data.issues || {};
        
        // Get supported health check categories from localized data
        const supportedCategories = rankLocalizedData.healthCheckCategories || {};
        
        // Store processed issues for later use
        processedIssues = {};
        
        // Define the static order for issue types (left to right)
        const issueTypeOrder = [
            'missing_alt_tags',
            'missing_meta_description',
            'long_meta_description',
            'short_meta_description',
            'duplicate_meta_description',
            'missing_title_tag',
            'long_title_tag',
            'short_title_tag',
            'duplicate_title',
            'long_h1_h2_tag',
            'missing_h1_tag',
            'large_images',
            'broken_links_internal',
            'broken_links_external'
        ];
        
        // Create and populate all issue boxes in the specified order
        for (const issueType of issueTypeOrder) {
            // Only process if the issue exists in the data and is supported by the plugin
            if (issues.hasOwnProperty(issueType) && supportedCategories.hasOwnProperty(issueType)) {
                const issue = issues[issueType];
                
                // Store the issue data
                processedIssues[issueType] = issue;
                
                // Create the issue box
                createIssueBox(issueType, issue);
                
                // Update the box with data immediately
                updateIssueBox(issueType, issue);
            }
        }
        
        // Finish processing immediately since we have all data
        finishProcessing();
    }
    
    /**
     * Display warning message when health scan data is too old
     */
    function displayDataTooOldWarning() {
        // Hide loading indicator
        $loadingIndicator.hide();
        
        // Hide the grid container completely
        let $gridContainer = $healthIssuesContainer.find('.rank-issues-grid');
        if ($gridContainer.length > 0) {
            $gridContainer.hide();
        }
        
        // Remove any existing warning
        $healthIssuesContainer.find('.rank-data-too-old-warning').remove();
        
        // Create the warning message HTML with full width
        const warningHtml = `
            <div class="rank-data-too-old-warning" style="
                background: #fff;
                border: 1px solid #ddd;
                border-radius: 8px;
                padding: 30px;
                text-align: center;
                width: 940px;
                max-width: 940px;
                margin: 20px auto;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                position: relative;
                z-index: 10;
            ">
                <div style="margin-bottom: 20px;">
                </div>
                <h2 style="color: #d63638; margin: 0 0 15px 0; font-size: 21px; font-weight: 600;">
                    Last full health scan is older than 30 days
                </h2>
                <p style="color: #666; margin: 0 0 25px 0; font-size: 16px; line-height: 1.5;">
                    You need to finish a fresh health scan before you can fix issues. Come back here when the full scan is finished.
                </p>
                <a href="https://v3.morningscore.io" target="_blank" class="button button-primary" style="
                    background:rgb(0, 156, 60);
                    border-color: rgb(0, 156, 60);
                    color: #fff;
                    text-decoration: none;
                    padding: 12px 24px;
                    font-size: 16px;
                    border-radius: 4px;
                    display: inline-block;
                    transition: background-color 0.2s;"
                     >
                    Login to Morningscore
                </a>
                <div style="margin-top: 20px;">
                    <img src="${(typeof rank_ajax_obj !== 'undefined' && rank_ajax_obj.plugin_url) ? (rank_ajax_obj.plugin_url.endsWith('/') ? rank_ajax_obj.plugin_url + 'admin/scan.png' : rank_ajax_obj.plugin_url + '/admin/scan.png') : 'admin/scan.png'}" alt="Health Scan" style="max-width: 100%; height: auto; border-radius: 4px;">
                </div>
            </div>
        `;
        
        // Add the warning directly to the main container, not inside the grid
        $healthIssuesContainer.append(warningHtml);
        
        // Make sure the container is visible
        $healthIssuesContainer.show();
    }
    
    /**
     * Display message when a health scan is currently running
     */
    function displayCrawlingInProgress() {
        // Hide loading indicator
        $loadingIndicator.hide();
        
        // Hide the grid container completely
        let $gridContainer = $healthIssuesContainer.find('.rank-issues-grid');
        if ($gridContainer.length > 0) {
            $gridContainer.hide();
        }
        
        // Remove any existing crawling notice
        $healthIssuesContainer.find('.rank-crawling-in-progress').remove();
        
        // Create the crawling in progress message HTML
        const crawlingHtml = `
            <div class="rank-crawling-in-progress" style="
                background: #fff;
                border: 1px solid #ddd;
                border-radius: 8px;
                padding: 30px;
                text-align: center;
                width: 500px;
                max-width: 940px;
                margin: 30px 0px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                position: relative;
                z-index: 10;
            ">
                <div style="margin-bottom: 20px;">
                    <span class="spinner is-active" style="float: none; margin: 0 auto; display: block;"></span>
                </div>
                <p style="color: #3c434a;margin: 0 0 20px 0;font-size: 20px;line-height: 1.5;">
                    Health scan currently running in Morningscore. Wait for it to finish to be able to fix issues.
                </p>
                <div style="margin-top: 20px;">
                    <img src="${(typeof rank_ajax_obj !== 'undefined' && rank_ajax_obj.plugin_url) ? (rank_ajax_obj.plugin_url.endsWith('/') ? rank_ajax_obj.plugin_url + 'admin/scanning.png' : rank_ajax_obj.plugin_url + '/admin/scanning.png') : 'admin/scanning.png'}" alt="Health Scan Running" style="max-width: 100%; height: auto; border-radius: 4px;">
                </div>
            </div>
        `;
        
        // Add the notice directly to the main container, not inside the grid
        $healthIssuesContainer.append(crawlingHtml);
        
        // Display latest scan date below the crawling notice
        $healthIssuesContainer.find('.rank-crawling-in-progress').after(buildScanDateElement());
        
        // Make sure the container is visible
        $healthIssuesContainer.show();
    }
    
    /**
     * Create an issue box with the given data
     */
    function createIssueBox(issueType, issue) {
        const $gridContainer = $healthIssuesContainer.find('.rank-issues-grid');
        
        let issueBoxHtml = `
            <div class="rank-issue-box" data-issue-type="${issueType}">
                <h3>${issue.label}</h3>
                <p>Problems: <span class="rank-issue-count">0</span></p>
                <button class="button rank-fix-issues-button" data-issue-type="${issueType}" disabled>Loading...</button>
                <p class="rank-issue-status" style="visibility: hidden;"></p>
            </div>`;
        $gridContainer.append(issueBoxHtml);
    }
    
    /**
     * Update an issue box with data (simplified for optimized endpoint)
     */
    function updateIssueBox(issueType, data) {
        const $box = $(`.rank-issue-box[data-issue-type="${issueType}"]`);
        const issueCount = parseInt(data.count, 10) || 0;
        
        // Update the count
        $box.find('.rank-issue-count').text(issueCount);
        
        // Remove any existing limit warning
        $box.find('.rank-issue-limit-warning').remove();
        
        // Update box class and button based on count
        if (issueCount > 0) {
            $box.removeClass('rank-issue-box-good');
            
            // Update button
            $box.find('button').text(rankLocalizedData.text_fix_issues || 'Fix Issues').prop('disabled', false);
            
            // Hide status message since we no longer have sampling data
            $box.find('.rank-issue-status').css('visibility', 'hidden');
        } else {
            // No issues found
            $box.addClass('rank-issue-box-good');
            $box.find('button').text(rankLocalizedData.text_all_good || 'All good ✅').prop('disabled', true);
            $box.find('.rank-issue-status').css('visibility', 'hidden');
        }
        
        // Add limit warning if count is above 5000 (after button is updated)
        if (issueCount > 5000) {
            const $warning = $('<p class="rank-issue-limit-warning" style="background-color: #fff8e5; color: #856404; font-size: 12px; padding: 5px; margin: 5px 0; border-radius: 3px;text-align:center;">You can fix max 5000 per run</p>');
            $box.find('.rank-fix-issues-button').after($warning);
        }
    }
    
    /**
     * Finish processing all issue types (simplified for optimized endpoint)
     */
    function finishProcessing() {
        isProcessing = false;
        $loadingIndicator.css('visibility', 'hidden');
        $loadingIndicator.find('.spinner').removeClass('is-active');
        
        // Check if we have any positive issues
        let hasPositiveIssues = false;
        
        for (const issueType in processedIssues) {
            const issueData = processedIssues[issueType];
            const issueCount = parseInt(issueData.count, 10) || 0;
            
            if (issueCount > 0) {
                hasPositiveIssues = true;
                break; // We found at least one issue, no need to continue
            }
        }
        
        // Display an overall message if no issues requiring fixes were found
        if (!hasPositiveIssues) {
            // Get credits info
            let creditsRemaining = 0;
            if ($globalCreditStatusArea.length) {
                const creditText = $globalCreditStatusArea.text();
                const creditMatch = creditText.match(/AI Credits left: (\d+)/);
                if (creditMatch && creditMatch[1]) {
                    creditsRemaining = parseInt(creditMatch[1], 10);
                }
            }
            
            const $gridContainer = $healthIssuesContainer.find('.rank-issues-grid');
            if (creditsRemaining > 0) {
                $gridContainer.append(`<p class="rank-overall-status-message">${rankLocalizedData.text_no_issues_found || 'No health issues found that require fixing. Good job!'}</p>`);
            } else {
                // Credits exhausted AND no positive issues
                $gridContainer.append(`<p class="rank-overall-status-message">${rankLocalizedData.text_no_issues_credits_exhausted || 'No health issues found that require fixing, and AI credits are exhausted.'}</p>`);
            }
        }
        
        // Display latest scan date above the yellow follow-steps bar
        const $gridContainer = $healthIssuesContainer.find('.rank-issues-grid');
        $gridContainer.append(buildScanDateElement());
        
        // Add static notification about scanning website for fresh data
        if (hasPositiveIssues) {
            $gridContainer.append(`
                <div class="rank-scan-notification">
                    <p><b>Follow these steps:</b> 1. <a href="javascript:void(0);" onclick="window.open('https://help.morningscore.io/en/article/how-to-refresh-your-health-data-10o0v7t/','_blank');">Scan full health</a> ⮞ 2. Fix issues here ⮞ 3. Scan full health again to update issues</p>
                </div>
            `);
        }
    }
    
    /**
     * Build a jQuery element showing the latest scan date
     */
    function buildScanDateElement() {
        let scanDateText = 'No info';
        if (lastCrawledAt) {
            const d = new Date(lastCrawledAt);
            if (!isNaN(d.getTime())) {
                const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
                const month = months[d.getMonth()];
                const day = d.getDate();
                const hours = String(d.getHours()).padStart(2, '0');
                const minutes = String(d.getMinutes()).padStart(2, '0');
                scanDateText = month + ' ' + day + ' ' + hours + ':' + minutes;
            }
        }
        return $('<p class="rank-latest-scan-date">Latest scan: ' + scanDateText + '</p>');
    }
    
    /**
     * Prepare health issues for processing
     * @param {string} issueType - The type of issue to prepare
     */
    function prepareHealthIssues(issueType) {
        // Validate required data
        if (!rankLocalizedData || !rankLocalizedData.ajax_url || !rankLocalizedData.nonce) {
            rank.helpers.showNotice('Error: Plugin configuration data is missing.', 'error');
            return;
        }


        // Reset UI and state
        rank.helpers.clearNotices();
        rank.elements.logOutput.empty();
        rank.helpers.updateProgressBar(0);
        rank.elements.counts.text('');
        $('#rank-approval-area').empty().hide();
        $('.rank-credits-warning').remove();
        
        // Clear old batch data from localStorage to ensure fresh preparation
        localStorage.removeItem('rank_batch_id');
        localStorage.removeItem('rank_review_started');
        localStorage.setItem('rank_auto_approve', '0');
        
        // Set up state - reset ALL relevant state values
        rank.state.processedCount = 0;
        rank.state.autoProcessActionCompleted = false;
        rank.state.isBackgroundProcessing = false;
        rank.state.issueType = issueType;
        rank.state.batchId = null; // Clear old batch ID
        rank.state.totalCount = 0; // Reset total count
        rank.state.alreadyFixedCount = 0; // Reset already fixed count to prevent stale data
        rank.state.unsupportedCount = 0;
        rank.state.healthIssueName = '';
        
        // Clear the batch input field to ensure fresh preparation
        if (rank.elements.batchIdInput) {
            rank.elements.batchIdInput.val('');
        }
        
        // Update UI for preparation
        rank.elements.healthIssuesContainer.hide();
        $('.rank-refresh-button').hide();
        $('#rank-multilingual-notice').hide(); // Hide multilingual notice during processing
        rank.elements.processingArea.show();
        rank.elements.statusMessage.html('<span class="spinner is-active" style="float: none; margin-right: 5px;"></span>' +
            (rankLocalizedData.status_preparing || 'Preparing issues...'));
        
        // Hide buttons during preparation
        if (rank.elements.startButton) rank.elements.startButton.hide();
        if (rank.elements.autoProcessButton) rank.elements.autoProcessButton.hide();
        if (rank.elements.cancelBtn) {
            rank.elements.cancelBtn.text('Cancel').removeClass('cancelling').prop('disabled', false);
        }
        
        // Store selected issue type
        if (rank.elements.selectedIssueType) {
            rank.elements.selectedIssueType.val(issueType);
        }
        
        // Start chunked preparation
        prepareIssuesInChunks(issueType);
    }
    
    // Function to handle chunked preparation
    function prepareIssuesInChunks(issueType, batchId = null, chunkOffset = 0) {
        const data = {
            action: 'rank_prepare_health_issues',
            nonce: rankLocalizedData.nonce,
            issue_type: issueType,
            chunk_offset: chunkOffset
        };
        
        // Add batch_id if this is a continuation request
        if (batchId) {
            data.batch_id = batchId;
        }
        
        // Make AJAX request
        rank.helpers.trackAjaxRequest($.ajax({
            url: rankLocalizedData.ajax_url,
            type: 'POST',
            data: data,
            dataType: 'json',
            success: function(response) {
                if (response.success && response.data) {
                    const currentBatchId = response.data.batchId;
                    const currentCount = response.data.count || 0;
                    const totalCount = response.data.total_count || 0;
                    const hasMore = response.data.has_more || false;
                    const nextOffset = response.data.next_offset || 0;
                    const unsupportedCount = response.data.unsupported_count || 0;
                    
                    // Handle no issues case
                    if (totalCount === 0) {
                        const message = response.data.message || 'No issues found to prepare for this category.';
                        rank.helpers.showNotice(message, 'info');
                        rank.elements.statusMessage.text(message);
                        rank.elements.healthIssuesContainer.show();
                        $('.rank-refresh-button').show();
                        rank.elements.processingArea.hide();
                        return;
                    }
                    
                    // Update progress
                    const progressPercent = totalCount > 0 ? Math.round((currentCount / totalCount) * 100) : 0;
                    rank.elements.statusMessage.text(`Preparing issues... ${currentCount}/${totalCount} (${progressPercent}%)`);
                    
                    // Get health issue name for display
                    let healthIssueName = '';
                    if (issueType && rankLocalizedData && rankLocalizedData.healthCheckCategories &&
                        rankLocalizedData.healthCheckCategories[issueType]) {
                        healthIssueName = rankLocalizedData.healthCheckCategories[issueType] + ': ';
                    }
                    rank.state.healthIssueName = healthIssueName;
                    
                    // Update counts display
                    rank.elements.counts.text(`${healthIssueName}${currentCount}/${totalCount} problems`);
                    
                    if (hasMore) {
                        // Continue with next chunk
                        setTimeout(() => {
                            prepareIssuesInChunks(issueType, currentBatchId, nextOffset);
                        }, 100); // Small delay to prevent overwhelming the server
                    } else {
                        // Preparation complete
                        rank.state.batchId = currentBatchId;
                        rank.state.totalCount = currentCount;
                        rank.state.unsupportedCount = unsupportedCount;
                        rank.state.autoApproveFlag = false;
                        localStorage.setItem('rank_batch_id', currentBatchId);
                        localStorage.setItem('rank_auto_approve', '0');
                        
                        // Update UI
                        rank.elements.batchIdInput.val(currentBatchId);
                        rank.elements.counts.text(`${healthIssueName}${currentCount} problems`);
                        rank.helpers.addLogMessage(`Preparation complete. Found ${currentCount} problems.`);
                        
                        // Check for already fixed issues in chunks
                        checkAlreadyFixedInChunks(currentBatchId, issueType, healthIssueName);
                    }
                } else {
                    // Handle error
                    const errorMsg = (response.data && response.data.message) || 'Error preparing issues.';
                    rank.helpers.showNotice(errorMsg, 'error');
                    rank.helpers.addLogMessage('Error during preparation: ' + errorMsg);
                    
                    // Reset UI
                    rank.elements.healthIssuesContainer.show();
                    $('.rank-refresh-button').show();
                    rank.elements.processingArea.hide();
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                // Handle AJAX error
                const errorMsg = `Error preparing issues: ${textStatus}`;
                rank.helpers.showNotice(errorMsg, 'error');
                rank.helpers.addLogMessage(errorMsg);
                
                // Reset UI
                rank.elements.healthIssuesContainer.show();
                $('.rank-refresh-button').show();
                rank.elements.processingArea.hide();
            }
        }));
    }
    
    /**
     * Check for already fixed issues in chunks to prevent timeouts
     */
    function checkAlreadyFixedInChunks(batchId, issueType, healthIssueName, offset = 0, totalFixed = 0, totalUniqueImages = null) {
        const data = {
            action: 'rank_check_already_fixed',
            nonce: rankLocalizedData.nonce,
            batchId: batchId,
            offset: offset
        };
        
        rank.helpers.trackAjaxRequest($.ajax({
            url: rankLocalizedData.ajax_url,
            type: 'POST',
            data: data,
            dataType: 'json',
            success: function(response) {
                if (response.success && response.data) {
                    const chunkFixed = response.data.already_fixed || 0;
                    const hasMore = response.data.has_more || false;
                    const nextOffset = response.data.next_offset || 0;
                    const progressPercent = response.data.progress_percent || 0;
                    const totalChecked = response.data.total_checked || 0;
                    const totalIssues = response.data.total_issues || 0;
                    // For large_images: total unique image files across the whole
                    // batch (returned on every chunk; we just keep the last one).
                    const chunkUniqueImages = response.data.total_unique_images;

                    // Accumulate total fixed count
                    totalFixed += chunkFixed;
                    if (chunkUniqueImages !== undefined && chunkUniqueImages !== null) {
                        totalUniqueImages = chunkUniqueImages;
                    }

                    // Update status message with progress
                    if (hasMore) {
                        rank.elements.statusMessage.html(`Checking for already fixed issues... <span style="color: #563ac9 !important;">${progressPercent}%</span>`);

                        // Continue with next chunk
                        setTimeout(() => {
                            checkAlreadyFixedInChunks(batchId, issueType, healthIssueName, nextOffset, totalFixed, totalUniqueImages);
                        }, 100); // Small delay between chunks
                    } else {
                        // Check complete
                        if (totalFixed > 0) {
                            rank.helpers.addLogMessage(`⚠️ Found ${totalFixed} already fixed issues out of ${totalIssues} total.`);

                            // Update counts display to show remaining unfixed issues
                            const remainingIssues = totalIssues - totalFixed;
                            // Store the fixed count in state for later use
                            rank.state.alreadyFixedCount = totalFixed;

                            // Show the total only for now; the "View pages" links are wired up
                            // after filtering (so the already-fixed list exists server-side).
                            rank.elements.counts.html(`${healthIssueName}<strong>${totalIssues} problems total</strong>`);

                            // Filter out already-fixed issues from the batch
                            rank.elements.statusMessage.text('Removing already fixed issues from batch...');
                            filterAlreadyFixedFromBatch(batchId, healthIssueName, remainingIssues, totalFixed, totalUniqueImages);
                        } else {
                            // No fixed issues, continue with normal flow
                            showProcessingButtons();
                        }
                    }
                } else {
                    // Error checking, but continue anyway
                    console.warn('Could not check for already fixed issues:', response);
                    showProcessingButtons();
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                // Error checking, but continue anyway
                console.error('Error checking for already fixed issues:', {
                    textStatus: textStatus,
                    errorThrown: errorThrown,
                    status: jqXHR.status,
                    responseText: jqXHR.responseText
                });
                
                // Try to parse error message from response
                let errorMessage = textStatus;
                try {
                    const response = JSON.parse(jqXHR.responseText);
                    if (response && response.data && response.data.message) {
                        errorMessage = response.data.message;
                        console.error('Server error message:', errorMessage);
                    }
                } catch (e) {
                    // Not JSON, use default message
                }
                
                showProcessingButtons();
            }
        }));
    }

    /**
     * Filter already-fixed issues from the batch
     */
    function filterAlreadyFixedFromBatch(batchId, healthIssueName, expectedRemaining, totalFixed, totalUniqueImages) {
        const data = {
            action: 'rank_filter_already_fixed',
            nonce: rankLocalizedData.nonce,
            batch_id: batchId
        };

        rank.helpers.trackAjaxRequest($.ajax({
            url: rankLocalizedData.ajax_url,
            type: 'POST',
            data: data,
            dataType: 'json',
            success: function(response) {
                if (response.success && response.data) {
                    const removedCount = response.data.removed_count || 0;
                    const remainingCount = response.data.remaining_count || 0;
                    // total_pages_batch is the page-occurrence count of the
                    // ORIGINAL batch (before filtering). Prefer it from the
                    // server response; fall back to removed + remaining.
                    const totalPagesBatch = response.data.total_pages_batch
                        || (removedCount + remainingCount);

                    rank.helpers.addLogMessage(`✅ Removed ${removedCount} already fixed issues. ${remainingCount} remaining to process.`);

                    // Update the total count in state
                    rank.state.totalCount = remainingCount;

                    // The "detected as already fixed" number must equal what
                    // the "View pages" modal shows. For image_optimize the
                    // modal is grouped by image, so use the server's grouped
                    // unique_image_count instead of the chunked-check total
                    // (which counts differently and disagrees with the modal).
                    const displayedFixed = (response.data.unique_image_count !== null
                        && response.data.unique_image_count !== undefined)
                        ? response.data.unique_image_count
                        : totalFixed;

                    // Store the fixed count in state for later use
                    rank.state.alreadyFixedCount = displayedFixed;

                    // Update counts display - split into "ready to fix" and "already fixed",
                    // each with its own "View pages" modal link.
                    renderPreparedCounts(healthIssueName, remainingCount, displayedFixed, rank.state.unsupportedCount || 0, {
                        totalPages: totalPagesBatch + (rank.state.unsupportedCount || 0),
                        totalUniqueImages: totalUniqueImages
                    });

                    // Continue with normal flow
                    showProcessingButtons();
                } else {
                    // Error filtering, but continue anyway
                    console.warn('Could not filter already fixed issues:', response);
                    showProcessingButtons();
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                // Error filtering, but continue anyway
                console.error('Error filtering already fixed issues:', {
                    textStatus: textStatus,
                    errorThrown: errorThrown
                });
                showProcessingButtons();
            }
        }));
    }

    /**
     * Render the prepared-state counts with separate "ready to fix" and
     * "already fixed" lines, each linking to its own "View pages" modal.
     *
     * @param {string} healthIssueName Label prefix, e.g. "Long Meta Description: "
     * @param {number} remaining       Issues still to fix (page-occurrences)
     * @param {number} fixed           Issues detected as already fixed
     * @param {object} totals          { totalPages, totalUniqueImages } — the
     *                                 ORIGINAL batch's page-occurrence count
     *                                 and unique-image count. Used to show
     *                                 "73 total images used on 382 pages".
     */
    function renderPreparedCounts(healthIssueName, remaining, fixed, unsupported, totals) {
        ensurePreparedCountsStyles();

        unsupported = unsupported || 0;
        const totalPages = (totals && totals.totalPages)
            ? totals.totalPages
            : (remaining + fixed + unsupported);
        const tooltip = `<span class="rank-inline-tooltip" data-tooltip="${rankLocalizedData.tooltip_already_fixed}">❓</span>`;

        let html = `<div class="rank-prepared-counts">`;

        // Image-style headline: show "X total images used on Y pages".
        // The "total images" number is just ready + already-fixed — a rough
        // sum that gives the user a single at-a-glance figure (e.g. 30
        // ready + 43 already fixed = 73 total). The page count is the
        // total page-occurrences in the batch.
        if (remaining > 0 || fixed > 0) {
            const totalImages = (remaining || 0) + (fixed || 0);
            html += `<div class="rank-prepared-title">${healthIssueName}<strong>${totalImages}</strong> total images used on <strong>${totalPages}</strong> pages</div>`;
        } else {
            html += `<div class="rank-prepared-title">${healthIssueName}<strong>${totalPages}</strong> problems total</div>`;
        }

        if (remaining > 0) {
            html += `<div class="rank-prepared-line">`
                + `<span class="rank-count">${remaining}</span>`
                + `<span class="rank-prepared-label">ready to be fixed now</span>`
                + `<a href="#" class="rank-view-pages-link" data-source="issues">View pages</a>`
                + `</div>`;
        }

        if (fixed > 0) {
            html += `<div class="rank-prepared-line">`
                + `<span class="rank-count">${fixed}</span>`
                + `<span class="rank-prepared-label">detected as already fixed${tooltip}</span>`
                + `<a href="#" class="rank-view-pages-link" data-source="already_fixed">View pages</a>`
                + `</div>`;
        }

        if (unsupported > 0) {
            html += `<div class="rank-prepared-line">`
                + `<span class="rank-count">${unsupported}</span>`
                + `<span class="rank-prepared-label">unsupported pages</span>`
                + `<a href="#" class="rank-view-pages-link" data-source="unsupported">View pages</a>`
                + `</div>`;
        }

        html += `</div>`;
        rank.elements.counts.html(html);

        // Wire up each "View pages" link to open the matching modal list
        rank.elements.counts.find('.rank-view-pages-link').off('click').on('click', function(e) {
            e.preventDefault();
            const source = $(this).data('source');
            if (rank.urlListModal && typeof rank.urlListModal.showUrlsModal === 'function') {
                rank.urlListModal.showUrlsModal(rank.state.batchId, rank.state.issueType, source);
            }
        });
    }

    /**
     * Inject the styles for the prepared-counts block once.
     */
    function ensurePreparedCountsStyles() {
        if (document.getElementById('rank-prepared-counts-styles')) {
            return;
        }

        const css = `
            .rank-prepared-counts {
                line-height: 1.5;
                border: 1px solid #e2e4e7;
                border-radius: 6px;
                max-width: 420px;
                overflow: hidden;
            }
            .rank-prepared-title {
                font-size: 15px;
                font-weight: 600;
                color: #1d2327;
                padding: 10px 14px;
                background: #f6f7f7;
                border-bottom: 1px solid #e2e4e7;
            }
            .rank-prepared-line {
                display: flex;
                align-items: center;
                gap: 6px;
                font-size: 13px;
                font-weight: 400;
                color: #50575e;
                padding: 10px 14px;
            }
            .rank-prepared-line + .rank-prepared-line {
                border-top: 1px solid #e2e4e7;
            }
            .rank-prepared-line .rank-count {
                font-weight: 600;
                color: #1d2327;
            }
            .rank-prepared-line .rank-prepared-label { color: #50575e; }
            .rank-prepared-line .rank-view-pages-link {
                margin-left: auto;
                color: #2271b1;
                font-weight: 500;
                text-decoration: none;
                white-space: nowrap;
            }
            .rank-prepared-line .rank-view-pages-link:hover { text-decoration: underline; }
        `;

        const style = document.createElement('style');
        style.id = 'rank-prepared-counts-styles';
        style.textContent = css;
        document.head.appendChild(style);
    }

    /**
     * Show processing buttons after preparation is complete
     */
    function showProcessingButtons() {
        // Unsupported pages are filtered before any AI request, but remain
        // visible through the prepared-count UI so users can see why they
        // cannot be processed.
        if ((rank.state.alreadyFixedCount > 0 || rank.state.unsupportedCount > 0)
            && !rank.elements.counts.find('.rank-prepared-counts').length) {
            renderPreparedCounts(
                rank.state.healthIssueName || '',
                rank.state.totalCount || 0,
                rank.state.alreadyFixedCount || 0,
                rank.state.unsupportedCount || 0,
                null
            );
        }

        // When nothing is left to fix (e.g. everything was detected as already
        // fixed), there is no point in showing the Manual/Automatic buttons.
        // Hide them and turn the cancel button into a "Back to overview" button.
        const nothingToFix = !(rank.state.totalCount > 0);

        if (nothingToFix) {
            rank.elements.statusMessage.text(rank_ajax_obj.status_nothing_to_fix || 'Nothing to fix - everything is already fixed.');

            if (rank.elements.startButton) rank.elements.startButton.hide();
            if (rank.elements.autoProcessButton) rank.elements.autoProcessButton.hide();
            if (rank.elements.cancelBtn) rank.elements.cancelBtn.show();
            if (rank.elements.progressBarContainer) rank.elements.progressBarContainer.hide();
            return;
        }

        // Show buttons for user to choose processing mode
        rank.elements.statusMessage.text(rank_ajax_obj.status_prepared || 'Ready. Choose how to proceed:');
        
        // Show buttons
        if (rank.elements.startButton) {
            rank.elements.startButton.text(rank_ajax_obj.text_process_manually || 'Manual').show();
        }
        if (rank.elements.autoProcessButton) {
            rank.elements.autoProcessButton.text(rank_ajax_obj.text_auto_process || 'Automatic')
                .data('action', 'setup').show();
        }
        if (rank.elements.cancelBtn) rank.elements.cancelBtn.show();
        if (rank.elements.progressBarContainer) rank.elements.progressBarContainer.hide();
        
        // Add the default single "View pages" link only when no prepared-count
        // rows exist. Those rows each provide their own filtered page list.
        if (rank.urlListModal && typeof rank.urlListModal.addViewUrlsButton === 'function'
            && rank.state.totalCount > 0
            && !(rank.state.alreadyFixedCount > 0 || rank.state.unsupportedCount > 0)) {
            setTimeout(function() {
                rank.urlListModal.addViewUrlsButton(rank.state.batchId, rank.state.issueType);
            }, 100);
        }
        
        // Check credits
        if (rank.state.totalCount > 0) {
            const $globalCreditStatusArea = $('#rank-global-credit-status');
            let creditsRemaining = 0;
            
            if ($globalCreditStatusArea.length) {
                const creditMatch = $globalCreditStatusArea.text().match(/AI Credits left: (\d+)/);
                if (creditMatch && creditMatch[1]) {
                    creditsRemaining = parseInt(creditMatch[1], 10);
                }
            }
            
            // Show warning if not enough credits
            if (creditsRemaining < rank.state.totalCount && rank.elements.autoProcessButton) {
                const $warningBox = $('<div>', {
                    class: 'rank-credits-warning',
                    style: 'background-color: #fff8e5; border-left: 4px solid #ffb900; padding: 10px; margin: 10px 0;'
                }).html(`Fixing all these problems takes ${rank.state.totalCount} credits but you only have ${creditsRemaining} available. You can still continue and fix things until you run out.`);
            
                rank.elements.autoProcessButton.after($warningBox);
            }
        }
    }

    // Expose public methods
    rank.sequentialHealthIssues = {
        init: init,
        loadHealthIssuesOverview: loadHealthIssuesOverview,
        prepareHealthIssues: prepareHealthIssues
    };
    
})(jQuery, window.rankLocalizedData);