/**
 * 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 = {};
    
    // 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 (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');
                    $loadingIndicator.hide();
                    $healthIssuesContainer.html(`<p>${rankLocalizedData.text_error_loading_issues || 'Error loading health issues:'} ${errorMessage}</p>`).show();
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                $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
                let responseData = null;
                try {
                    responseData = JSON.parse(jqXHR.responseText);
                } catch (e) {
                    // Not valid JSON, continue with default error message
                }
                
                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>`);
                }
                
                // Make sure the container is visible
                $healthIssuesContainer.show();
            }
        }));
    }
    
    /**
     * Process the optimized overview response (no sequential processing needed)
     */
    function processOptimizedOverviewResponse(data) {
        // 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',
            'missing_title_tag',
            'long_title_tag',
            'short_title_tag',
            '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();
    }
    
    /**
     * 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>`);
            }
        }
        
        // Add static notification about scanning website for fresh data
        if (hasPositiveIssues) {
            const $gridContainer = $healthIssuesContainer.find('.rank-issues-grid');
            $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>
            `);
        }
    }
    
    /**
     * 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();
        
        // Set up state
        rank.state.processedCount = 0;
        rank.state.autoProcessActionCompleted = false;
        rank.state.issueType = issueType;
        
        // 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.removeClass('cancelling').text('Cancel').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;
                    
                    // 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] + ': ';
                    }
                    
                    // 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.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.`);
                        
                        // 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 "View URLs" button if the URL list modal is available
                        if (rank.urlListModal && typeof rank.urlListModal.addViewUrlsButton === 'function') {
                            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);
                            }
                        }
                        
                        // Check for already fixed issues after preparation is complete
                        checkAlreadyFixedIssues(currentBatchId);
                    }
                } 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 and display info box
     */
    function checkAlreadyFixedIssues(batchId) {
        if (!batchId) {
            return;
        }

        // Make AJAX call to check for already fixed issues
        rank.helpers.trackAjaxRequest($.ajax({
            url: rank_ajax_obj.ajax_url,
            type: 'POST',
            data: {
                action: 'rank_check_already_fixed',
                nonce: rank_ajax_obj.nonce,
                batchId: batchId
            },
            dataType: 'json',
            success: function(response) {
                if (response && response.success && response.data) {
                    const data = response.data;
                    
                    // Only show info box if we found already fixed issues
                    if (data.estimated_total_fixed > 0 || data.already_fixed > 0) {
                        displayAlreadyFixedInfoBox(data);
                    }
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                // Silently fail - this is not critical functionality
                console.log('Could not check for already fixed issues:', textStatus);
            }
        }));
    }

    /**
     * Display yellow info box showing already fixed issues
     */
    function displayAlreadyFixedInfoBox(data) {
        // Remove any existing info box
        $('.rank-already-fixed-info').remove();
        
        const alreadyFixed = data.estimated_total_fixed || data.already_fixed;
        const totalIssues = data.total_issues;
        
        // Don't display anything if no issues have been fixed
        if (data.estimated_total_fixed <= 0) {
            return;
        }
        
        const message = `We already fixed ${alreadyFixed} out of ${totalIssues} issues - <a href="https://help.morningscore.io/en/article/how-to-refresh-your-health-data-10o0v7t/" target="_blank">scan your health again</a> to update issues and avoid fixing the same issues twice`;
        
        // Create the yellow info box
        const infoBoxHtml = `
            <div class="rank-already-fixed-info">
                <span class="info-icon"></span>
                <span class="info-text">${message}</span>
            </div>
        `;
        
        // Insert the info box after the status message but before the buttons
        if (rank.elements.statusMessage && rank.elements.statusMessage.length) {
            rank.elements.statusMessage.after(infoBoxHtml);
        } else if (rank.elements.counts && rank.elements.counts.length) {
            rank.elements.counts.after(infoBoxHtml);
        } else {
            // Fallback: add to processing area
            if (rank.elements.processingArea && rank.elements.processingArea.length) {
                rank.elements.processingArea.prepend(infoBoxHtml);
            }
        }
    }

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