/**
 * RANK SEO Admin
 * Main initialization file
 */
(function($) {
    'use strict';
    
    // Global state object
    window.rank = window.rank || {
        state: {
            batchId: '',
            totalCount: 0,
            processedCount: 0,
            autoApproveFlag: false,
            isBackgroundProcessing: false
        },
        elements: {},
        // Helper functions
        utils: {
            // Check if processing is currently active
            isProcessingActive: function() {
                try {
                    // Safely check if state exists
                    if (!rank || !rank.state) {
                        return false;
                    }
                    
                    // Safely get localStorage value
                    let reviewStarted = false;
                    try {
                        reviewStarted = localStorage.getItem('rank_review_started') === '1';
                    } catch (storageErr) {
                        console.error('RANK ERROR - Error accessing localStorage:', storageErr);
                    }
                    
                    const isActive = !rank.state.isBackgroundProcessing && (
                        rank.state.isAutoProcessingActive ||
                        (rank.state.batchId && reviewStarted)
                    );
                    
                    // Ensure we always return a boolean
                    return !!isActive;
                } catch (err) {
                    console.error('RANK ERROR - Error in isProcessingActive:', err);
                    return false; // Default to not active if there's an error
                }
            }
        }
    };
    
    // Document ready
    $(document).ready(function() {
        // Initialize DOM element references
        initElements();
        
        // Initialize modules
        initModules();
        
        // Initialize event listeners
        initEventListeners();
        
        // Restore session state if available
        restoreSessionState();
        
        // Initialize API Key Form Handling
        initApiKeyForm();
        
        // Initialize tab switching behavior
        initTabSwitching();
        
        // For tabs other than the fixes overview tab, hide the spinner after initialization
        // The fixes overview tab will handle hiding the spinner after counts are loaded
        if (!$('#rank-fixes-accordion').length) {
            setTimeout(function() {
                $('.tab-content-loader').fadeOut(300);
            }, 500);
        }
        // Otherwise, the spinner will be hidden by the fixesOverview module
    });
    
    // Initialize DOM element references
    function initElements() {
        rank.elements = {
            // Main containers
            healthIssuesLoading: $('#rank-health-issues-loading'),
            healthIssuesContainer: $('#rank-health-issues-container'),
            processingArea: $('#rank-processing-area'),
            approvalArea: $('#rank-approval-area'),
            noticeArea: $('#rank-notice-area'),
            
            // Buttons
            startButton: $('#rank-start-button'),
            prepareButton: $('#rank-prepare-button'),
            autoProcessButton: $('#rank-auto-process-button'),
            cancelBtn: $('#rank-cancel-button'),
            
            // Inputs
            batchIdInput: $('#rank-batch-id'),
            selectedIssueType: $('#rank-selected-issue-type'),
            
            // Status displays
            statusMessage: $('#rank-status-message'),
            counts: $('#rank-counts'),
            logOutput: $('#rank-log-output'),
            
            // Progress bar
            progressBarContainer: $('#rank-progress-bar-container'),
            progressBar: $('#rank-progress-bar'),
            progressBarText: $('#rank-progress-bar'),
            
            // API key form
            apiKeyForm: $('#rank-api-key-form')
        };
    }
    
    // Initialize modules
    function initModules() {
        // Initialize helpers first
        if (rank.helpers && typeof rank.helpers.init === 'function') {
            rank.helpers.init();
        }
        
        // Initialize sequential health issues module (the regular one is now deprecated)
        if (rank.sequentialHealthIssues && typeof rank.sequentialHealthIssues.init === 'function') {
            rank.sequentialHealthIssues.init(rank.elements);
        }
        
        if (rank.processing && typeof rank.processing.init === 'function') {
            rank.processing.init();
        }
        
        if (rank.approval && typeof rank.approval.init === 'function') {
            rank.approval.init();
        }
    }
    
    // Helper function to start auto-approval process
    function _startAutoApproval() {
        // Remove the "View all pages" link immediately
        if (rank.urlListModal && typeof rank.urlListModal.removeViewUrlsButton === 'function') {
            rank.urlListModal.removeViewUrlsButton();
        }
        
        // Check if we have valid data to process
        if (!rank.state.batchId) {
            console.error('RANK ERROR: Cannot start auto-approval - batchId is missing');
            rank.helpers.showNotice('Error: Batch ID is missing, cannot start automatic processing.', 'error');
            return;
        }
        
        if (!rank.state.issueType) {
            console.error('RANK ERROR: Cannot start auto-approval - issueType is missing');
            rank.helpers.showNotice('Error: Issue type is missing, cannot start automatic processing.', 'error');
            return;
        }
        
        if (!rank.state.totalCount || rank.state.totalCount <= 0) {
            rank.helpers.addLogMessage('No issues to process. Automatic processing completed.');
            rank.helpers.showNotice('Automatic processing completed - no issues found to process.', 'success');
            
            // Hide buttons and show completion message
            rank.elements.startButton.hide();
            rank.elements.autoProcessButton.hide();
            if (rank.elements.statusMessage) {
                rank.elements.statusMessage.text('Automatic processing completed for all pages ✅');
            }
            return;
        }
        
        // Set auto-approve flag to true
        rank.state.autoApproveFlag = true;
        rank.state.isAutoProcessingActive = true;
        localStorage.setItem('rank_auto_approve', '1');
        
        // Hide manual process button
        rank.elements.startButton.hide();
        
        // Hide auto process button (since we no longer have stop functionality)
        rank.elements.autoProcessButton.hide();
        
        rank.helpers.addLogMessage(`Starting batch auto-approval process.`);

        if (rank.elements.approvalArea) {
           rank.elements.approvalArea.empty().hide(); // Hide approval area for automatic processing
           rank.helpers.addLogMessage('Cleared approval area before starting auto process.');
        }
        rank.elements.progressBarContainer.show();
        
        // Show the log container when starting auto processing
        $('.rank-log-container').show();
        
        // Show the spinner to indicate processing
        $('#rank-log-spinner').addClass('is-active').show();
        
        // Start auto-processing with auto-approval
        if (rank.processing && typeof rank.processing.startBatchAutoApproval === 'function') {
            rank.processing.startBatchAutoApproval();
        } else {
            console.error('RANK ERROR: rank.processing.startBatchAutoApproval is not defined');
            _handleAutoProcessFunctionError('startBatchAutoApproval');
        }
    }
    
    // Helper to handle errors if processing functions are missing and reset UI
    function _handleAutoProcessFunctionError(functionName) {
        rank.helpers.showNotice(`Error: Core processing function (${functionName}) is not available.`, 'error');
        console.error(`RANK: rank.processing.${functionName} is not defined.`);
        // Reset UI
        rank.state.isAutoProcessingActive = false;
        if (rank.elements.autoProcessButton) {
            rank.elements.autoProcessButton.text(rank_ajax_obj.text_auto_process || 'Automatic').data('action', 'setup');
        }
        if (rank.elements.startButton) rank.elements.startButton.show();
        // autoApproveCheckbox is already hidden or should be
    }


    // Initialize event listeners
    function initEventListeners() {
        // Add beforeunload event to catch page navigation/closing
        $(window).on('beforeunload', function(e) {
            // Check if processing is active using the global helper with error handling
            let isProcessing = false;
            try {
                if (rank && rank.utils && typeof rank.utils.isProcessingActive === 'function') {
                    isProcessing = rank.utils.isProcessingActive();
                } else {
                    // Fallback check if the function isn't available (suppress warning during page unload)
                    if (rank && rank.state) {
                        isProcessing = !rank.state.isBackgroundProcessing && (
                            rank.state.isAutoProcessingActive ||
                            (rank.state.batchId && localStorage.getItem('rank_review_started') === '1')
                        );
                    } else {
                        isProcessing = false;
                    }
                }
            } catch (err) {
                console.error('RANK ERROR - Error checking if processing is active (beforeunload):', err);
            }
            
            // Ensure isProcessing is a boolean
            isProcessing = !!isProcessing;
            
            if (isProcessing) {
                
                // Standard beforeunload message (browser will show its own dialog)
                const message = rank_ajax_obj.confirm_cancel_text || 'Are you sure you want to cancel? This will reset processing. All processed fixes are saved.✅';
                
                // Modern browsers standardized on using returnValue
                e.preventDefault();
                e.returnValue = message;
                
                // Also trigger the cancel processing function to ensure state is properly reset
                // This will run if the user confirms leaving the page
                setTimeout(function() {
                    if (rank.processing && typeof rank.processing.cancelProcessing === 'function') {
                        rank.processing.cancelProcessing();
                    } else {
                        fallbackCancelProcessing();
                    }
                }, 0);
                
                return message;
            }
        });

        // Cancel button
        rank.elements.cancelBtn.on('click', function() {
            // Check if processing is already complete
            const isProcessingComplete = rank.elements.counts &&
                                        rank.elements.counts.text().includes('Processing Complete');

            // Nothing has started yet (prepared state or nothing-to-fix): the
            // Manual/Automatic buttons are still visible, so there is nothing to
            // cancel. Skip the confirmation and just return to the overview.
            const startBtnVisible = rank.elements.startButton && rank.elements.startButton.is(':visible');
            const autoBtnVisible = rank.elements.autoProcessButton && rank.elements.autoProcessButton.is(':visible');
            const nothingToFix = !(rank.state.totalCount > 0);
            const notStarted = startBtnVisible || autoBtnVisible || nothingToFix;

            // If processing is complete or never started, skip the confirmation
            if (isProcessingComplete || notStarted) {
                // Use the centralized cancel processing function
                if (rank.processing && typeof rank.processing.cancelProcessing === 'function') {
                    rank.processing.cancelProcessing();
                    
                    // Then reload the health issues overview after a short delay
                    setTimeout(function() {
                        if (rank.sequentialHealthIssues && typeof rank.sequentialHealthIssues.loadHealthIssuesOverview === 'function') {
                            rank.sequentialHealthIssues.loadHealthIssuesOverview();
                        }
                    }, 300);
                } else {
                    // Fallback if the function isn't available
                    fallbackCancelProcessing();
                }
                return;
            }
            
            // For active processing, confirm the user wants to cancel
            if (confirm(rank_ajax_obj.confirm_cancel_text || 'Are you sure you want to cancel? This will reset processing. All processed fixes are saved ✅')) {
                // Change button appearance to indicate cancellation in progress
                $(this).addClass('cancelling').prop('disabled', true);
                
                // First clear any pending decisions via AJAX
                if (rank.state.batchId) {
                    $.ajax({
                        url: rank_ajax_obj.ajax_url,
                        type: 'POST',
                        data: {
                            action: 'rank_clear_pending_decisions',
                            nonce: rank_ajax_obj.nonce,
                            batchId: rank.state.batchId
                        },
                        dataType: 'json',
                        success: function(response) {
                            // Use the centralized cancel processing function first
                            if (rank.processing && typeof rank.processing.cancelProcessing === 'function') {
                                rank.processing.cancelProcessing();
                                
                                // Then reload the health issues overview after a short delay
                                setTimeout(function() {
                                    if (rank.sequentialHealthIssues && typeof rank.sequentialHealthIssues.loadHealthIssuesOverview === 'function') {
                                        rank.sequentialHealthIssues.loadHealthIssuesOverview();
                                    }
                                }, 300);
                            } else {
                                // Fallback if the function isn't available
                                console.error('RANK: cancelProcessing function not available');
                                fallbackCancelProcessing();
                                
                                // Then reload the health issues overview after a short delay
                                setTimeout(function() {
                                    if (rank.sequentialHealthIssues && typeof rank.sequentialHealthIssues.loadHealthIssuesOverview === 'function') {
                                        rank.sequentialHealthIssues.loadHealthIssuesOverview();
                                    }
                                }, 300);
                            }
                        },
                        error: function(jqXHR, textStatus, errorThrown) {
                            console.error('RANK: Error clearing pending decisions:', textStatus, errorThrown);
                            rank.helpers.showNotice('Error clearing pending decisions. Please try again.', 'error');
                        },
                        complete: function() {
                            // This is now handled in the success callback
                        }
                    });
                } else {
                    // If no batch ID, just use the centralized cancel function
                    if (rank.processing && typeof rank.processing.cancelProcessing === 'function') {
                        rank.processing.cancelProcessing();
                        
                        // Then reload the health issues overview after a short delay
                        setTimeout(function() {
                            if (rank.sequentialHealthIssues && typeof rank.sequentialHealthIssues.loadHealthIssuesOverview === 'function') {
                                rank.sequentialHealthIssues.loadHealthIssuesOverview();
                            }
                        }, 300);
                    } else {
                        // Fallback if the function isn't available
                        console.error('RANK: cancelProcessing function not available');
                        fallbackCancelProcessing();
                        
                        // Then reload the health issues overview after a short delay
                        setTimeout(function() {
                            if (rank.sequentialHealthIssues && typeof rank.sequentialHealthIssues.loadHealthIssuesOverview === 'function') {
                                rank.sequentialHealthIssues.loadHealthIssuesOverview();
                            }
                        }, 300);
                    }
                }
            }
        });
        
        // Fallback cancel function in case the processing module isn't loaded
        function fallbackCancelProcessing() {
            // Reset state variables
            rank.state.isAutoProcessingActive = false;
            rank.state.autoApproveFlag = false;
            rank.state.autoProcessActionCompleted = false;
            rank.state.processedCount = 0;
            
            // Clear localStorage flags
            localStorage.setItem('rank_auto_approve', '0');
            localStorage.removeItem('rank_review_started');
            
            // Reset UI state
            rank.elements.processingArea.hide();
            rank.elements.healthIssuesContainer.show();
            $('.rank-log-container').hide();
            $('#rank-log-spinner').removeClass('is-active').hide();
            
            // Reset cancel button to normal state
            if (rank.elements.cancelBtn) {
                rank.elements.cancelBtn.removeClass('cancelling').prop('disabled', false);
            }
            
            // Reset any approval UI
            if (rank.approval && typeof rank.approval.resetApprovalUI === 'function') {
                rank.approval.resetApprovalUI();
            }
            
            // Show buttons in their default state
            if (rank.elements.startButton) {
                rank.elements.startButton.prop('disabled', false).show();
            }
            
            // Update UI for auto-process button if it exists
            if (rank.elements.autoProcessButton) {
                rank.elements.autoProcessButton.show();
            }
            
            // Reset progress bar
            if (rank.helpers && typeof rank.helpers.updateProgressBar === 'function') {
                rank.helpers.updateProgressBar(0);
            }
            
            // Clear status message
            if (rank.elements.statusMessage) {
                rank.elements.statusMessage.text('');
            }
            
            // Clear counts display
            if (rank.elements.counts) {
                rank.elements.counts.text('');
            }
            
            // Add log message
            rank.helpers.addLogMessage('Processing canceled by user. All state has been reset.');
            rank.helpers.showNotice('Processing canceled. All progress has been reset.', 'info');
            
            // Reload health issues overview after a short delay
            setTimeout(function() {
                if (rank.sequentialHealthIssues && typeof rank.sequentialHealthIssues.loadHealthIssuesOverview === 'function') {
                    rank.sequentialHealthIssues.loadHealthIssuesOverview();
                }
            }, 300);
        }
        
        // Automatic button
        if (rank.elements.autoProcessButton) {
            // Initial state of the button is set by prepareHealthIssues: text "Automatic", data-action "setup"
            // rank.state.isAutoProcessingActive is initialized to false globally

            rank.elements.autoProcessButton.on('click', function() {
                // Directly start auto-approval process
                _startAutoApproval();
            });
        }
        
        
        // Data Management Tab Logic
        const $showDeleteConfirm = $('#rank-show-delete-confirm');
        const $deleteConfirmArea = $('#rank-delete-confirmation-area');
        const $deleteConfirmInput = $('#rank-delete-confirm-input');
        const $confirmDeleteButton = $('#rank-confirm-delete-button');
        const $deleteStatus = $('#rank-delete-status');
        
        $showDeleteConfirm.on('click', function() {
            $deleteConfirmArea.slideToggle();
        });
        
        $deleteConfirmInput.on('input', function() {
            const canDelete = $(this).val().trim() === (rank_ajax_obj.confirm_delete_text || 'DELETE');
            $confirmDeleteButton.prop('disabled', !canDelete);
        });
        
        // Delete confirmation logic - can remain in main file
        $confirmDeleteButton.on('click', function() {
            rank.helpers.clearNotices();
            $deleteStatus.text('Deleting...').css('color', 'orange');
            $(this).prop('disabled', true);
            
            $.ajax({
                url: rank_ajax_obj.ajax_url,
                type: 'POST',
                data: {
                    action: 'rank_delete_all_data',
                    nonce: rank_ajax_obj.nonce,
                    confirmation: $deleteConfirmInput.val().trim()
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        $deleteStatus.text(rank_ajax_obj.delete_success_message || 'All RANK AI data deleted successfully.').css('color', 'green');
                        rank.helpers.showNotice(rank_ajax_obj.delete_success_message || 'All RANK AI data deleted successfully.', 'success');
                        $deleteConfirmInput.val(''); // Clear input
                        $deleteConfirmArea.slideUp(); // Hide confirmation area
                    } else {
                        const errorMsg = response.data || (rank_ajax_obj.delete_error_message || 'Error deleting data.');
                        $deleteStatus.text(errorMsg).css('color', 'red');
                        rank.helpers.showNotice(errorMsg, 'error');
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    const errorMsg = `${rank_ajax_obj.delete_error_message || 'Error deleting data.'} (${textStatus})`;
                    $deleteStatus.text(errorMsg).css('color', 'red');
                    rank.helpers.showNotice(errorMsg, 'error');
                },
                complete: function() {
                    $confirmDeleteButton.prop('disabled', false);
                }
            });
        });

        // Delegated event listener for dynamically added "Fix Issues" buttons
        // Ensure rank.elements.healthIssuesContainer is defined and available
        if (rank.elements && rank.elements.healthIssuesContainer && rank.elements.healthIssuesContainer.length) {
            rank.elements.healthIssuesContainer.on('click', '.rank-fix-issues-button', function() {
                const $button = $(this);
                const issueType = $button.data('issue-type');
                
                if (issueType) {
                    // Use sequentialHealthIssues instead of healthIssues (which doesn't exist)
                    if (rank.sequentialHealthIssues && typeof rank.sequentialHealthIssues.prepareHealthIssues === 'function') {
                        rank.sequentialHealthIssues.prepareHealthIssues(issueType);
                    } else {
                        console.error('RANK AI: rank.sequentialHealthIssues.prepareHealthIssues function not found!');
                        alert('Error: The function to prepare issues is missing. Please contact support.');
                    }
                } else {
                    console.error('RANK AI: Fix Issues button clicked, but no issue-type data attribute found.');
                }
            });
        } else {
            $(document).on('click', '.rank-fix-issues-button', function() {
                const $button = $(this);
                const issueType = $button.data('issue-type');
                if (issueType && rank.sequentialHealthIssues && typeof rank.sequentialHealthIssues.prepareHealthIssues === 'function') {
                    rank.sequentialHealthIssues.prepareHealthIssues(issueType);
                } else {
                     console.error('RANK AI (document fallback): Error processing Fix Issues click.');
                }
            });
        }
    }
    
    // Restore session state
    function restoreSessionState() {
        // If we have a stored batch ID, try to restore that session
        const storedBatchId = localStorage.getItem('rank_batch_id');
        if (storedBatchId) {
            rank.state.batchId = storedBatchId;
            rank.elements.batchIdInput.val(storedBatchId);
            
            // Restore auto-approve setting
            rank.state.autoApproveFlag = localStorage.getItem('rank_auto_approve') === '1';
            
            // If review was previously started, show processing area
            if (localStorage.getItem('rank_review_started') === '1') {
                if (rank.helpers && typeof rank.helpers.showProcessingArea === 'function') {
                    rank.helpers.showProcessingArea();
                } else {
                    console.error('RANK SEO: rank.helpers.showProcessingArea is not available. Cannot restore processing area view.');
                }
            }
        }

        // Server state is authoritative for automatic runs and works across
        // browsers. The localStorage restoration above remains for Manual mode.
        if (rank.processing && typeof rank.processing.reconnectBackgroundBatch === 'function') {
            rank.processing.reconnectBackgroundBatch();
        }
    }
    
    // Initialize API Key Form
    function initApiKeyForm() {
        if (rank.elements.apiKeyForm.length > 0) {
            rank.elements.apiKeyForm.on('submit', function() {
                // Clear any cached health issues when API key changes
                localStorage.removeItem('rank_health_issue_counts');
            });
        }
    }
    
    // Initialize tab switching behavior
    function initTabSwitching() {
        // Add click handler for tab navigation
        $('.nav-tab-wrapper .nav-tab').on('click', function(e) {
            // Show the spinner when a tab is clicked
            $('.nav-tab-spinner').show();
            
            // The spinner will be hidden when the page reloads with the new tab
            // No need to hide it manually as the page will refresh
        });
        // Use the global helper function to check if processing is active
        
        // Helper function to handle confirmation and cancellation
        function handleProcessingConfirmation(event) {
            // Check if processing is active using the global helper with error handling
            let isProcessing = false;
            try {
                if (rank && rank.utils && typeof rank.utils.isProcessingActive === 'function') {
                    isProcessing = rank.utils.isProcessingActive();
                } else {
                    // Fallback check if the function isn't available (suppress warning during initialization)
                    if (rank && rank.state) {
                        isProcessing = !rank.state.isBackgroundProcessing && (
                            rank.state.isAutoProcessingActive ||
                            (rank.state.batchId && localStorage.getItem('rank_review_started') === '1')
                        );
                    } else {
                        // Only warn if rank object should be available but isn't
                        if (document.readyState === 'complete') {
                            console.warn('RANK WARN - isProcessingActive function not available');
                        }
                        isProcessing = false;
                    }
                }
            } catch (err) {
                console.error('RANK ERROR - Error checking if processing is active:', err);
            }
            
            // Ensure isProcessing is a boolean
            isProcessing = !!isProcessing;
            
            if (isProcessing) {
                // Only prevent default action if processing is active
                event.preventDefault();
                event.stopPropagation();
                // Use the same confirmation text as the cancel button
                const confirmMessage = rank_ajax_obj.confirm_cancel_text || 'Are you sure you want to cancel? This will reset processing. All processed fixes are saved ✅.';
                
                // Force a small delay to ensure the browser processes the event correctly
                setTimeout(function() {
                    const userConfirmed = confirm(confirmMessage);
                    
                    if (userConfirmed) {
                        // User confirmed - handle cancellation the same way as the cancel button
                        
                        // Change cancel button appearance to indicate cancellation in progress
                        if (rank.elements.cancelBtn) {
                            rank.elements.cancelBtn.addClass('cancelling').prop('disabled', true);
                        }
                        
                        // First clear any pending decisions via AJAX
                        if (rank.state.batchId) {
                            $.ajax({
                                url: rank_ajax_obj.ajax_url,
                                type: 'POST',
                                data: {
                                    action: 'rank_clear_pending_decisions',
                                    nonce: rank_ajax_obj.nonce,
                                    batchId: rank.state.batchId
                                },
                                dataType: 'json',
                                success: function(response) {
                                    // Use the centralized cancel processing function
                                    if (rank.processing && typeof rank.processing.cancelProcessing === 'function') {
                                        rank.processing.cancelProcessing();
                                        
                                        // Then reload the health issues overview after a short delay
                                        setTimeout(function() {
                                            if (rank.sequentialHealthIssues && typeof rank.sequentialHealthIssues.loadHealthIssuesOverview === 'function') {
                                                rank.sequentialHealthIssues.loadHealthIssuesOverview();
                                            }
                                        }, 300);
                                    } else {
                                        // Fallback if the function isn't available
                                        console.error('RANK: cancelProcessing function not available');
                                        fallbackCancelProcessing();
                                        
                                        // Then reload the health issues overview after a short delay
                                        setTimeout(function() {
                                            if (rank.sequentialHealthIssues && typeof rank.sequentialHealthIssues.loadHealthIssuesOverview === 'function') {
                                                rank.sequentialHealthIssues.loadHealthIssuesOverview();
                                            }
                                        }, 300);
                                    }
                                    
                                    // Allow the navigation to continue after processing is cancelled
                                    const href = $(event.currentTarget).attr('href');
                                    if (href) {
                                        setTimeout(function() {
                                            window.location.href = href;
                                        }, 500);
                                    }
                                },
                                error: function(jqXHR, textStatus, errorThrown) {
                                    console.error('RANK: Error clearing pending decisions:', textStatus, errorThrown);
                                    rank.helpers.showNotice('Error clearing pending decisions. Please try again.', 'error');
                                }
                            });
                        } else {
                            // If no batch ID, just use the centralized cancel function
                            if (rank.processing && typeof rank.processing.cancelProcessing === 'function') {
                                rank.processing.cancelProcessing();
                                
                                // Then reload the health issues overview after a short delay
                                setTimeout(function() {
                                    if (rank.sequentialHealthIssues && typeof rank.sequentialHealthIssues.loadHealthIssuesOverview === 'function') {
                                        rank.sequentialHealthIssues.loadHealthIssuesOverview();
                                    }
                                }, 300);
                            } else {
                                // Fallback if the function isn't available
                                console.error('RANK: cancelProcessing function not available');
                                fallbackCancelProcessing();
                                
                                // Then reload the health issues overview after a short delay
                                setTimeout(function() {
                                    if (rank.sequentialHealthIssues && typeof rank.sequentialHealthIssues.loadHealthIssuesOverview === 'function') {
                                        rank.sequentialHealthIssues.loadHealthIssuesOverview();
                                    }
                                }, 300);
                            }
                            
                            // Allow the navigation to continue after processing is cancelled
                            const href = $(event.currentTarget).attr('href');
                            if (href) {
                                setTimeout(function() {
                                    window.location.href = href;
                                }, 500);
                            }
                        }
                    }
                }, 10);
                
                // Return false to prevent default action while we wait for the confirmation dialog
                return false;
            } else {
                // If no processing is active, allow the action to proceed
                
                // Get the href from the clicked element if it's a link
                const href = $(event.currentTarget).attr('href');
                if (href) {
                    // Allow a small delay for logging before navigating
                    setTimeout(function() {
                        window.location.href = href;
                    }, 50);
                } else {
                    // If it's not a link with href, just clear processing area
                    if (rank.processing && typeof rank.processing.clearProcessingArea === 'function') {
                        rank.processing.clearProcessingArea();
                    }
                }
            }
        }
        
        // Handle WordPress admin tab clicks - use event delegation for better capture
        $(document).on('click', '.nav-tab', function(e) {
            handleProcessingConfirmation(e);
        });
        
        // Handle clicks on links within the plugin that would navigate away
        // Use document instead of #rank-admin-wrap for better capture
        $(document).on('click', 'a:not(.nav-tab)', function(e) {
            // Only intercept links that would navigate away (not action buttons or tabs we already handle)
            if ($(this).attr('href') && !$(this).hasClass('button') &&
                !$(this).hasClass('rank-action-link') && !$(this).hasClass('no-confirm')) {
                
                // Skip confirmation if:
                // 1. Link has target="_blank" (opens in new tab)
                // 2. User is holding Ctrl/Cmd key (also opens in new tab)
                // 3. Link has class "open-new-tab" (explicit indicator)
                // 4. Link uses javascript:void(0) with window.open (common in log links)
                // 5. Link is within the log output area (rank-log-output)
                if ($(this).attr('target') === '_blank' ||
                    e.ctrlKey ||
                    e.metaKey ||
                    $(this).hasClass('open-new-tab') ||
                    $(this).attr('href') === 'javascript:void(0);' ||
                    $(this).closest('#rank-log-output').length > 0) {
                    
                    return true; // Allow default action
                }
                
                handleProcessingConfirmation(e);
            }
        });
        
        // Also clear processing area on page load
        if (rank.processing && typeof rank.processing.clearProcessingArea === 'function') {
            rank.processing.clearProcessingArea();
        }
    }
    
    // Initialize debug logs functionality
    function initDebugLogs() {
        
        // Initialize debug logs functionality for data management tab
        if ($('.nav-tab[href*="data_management"]').length > 0) {
            // Load logs when data management tab is active
            if (window.location.href.indexOf('tab=data_management') !== -1) {
                loadDebugLogs();
            }
            
            // Handle tab switching to data management
            $('.nav-tab[href*="data_management"]').on('click', function() {
                setTimeout(function() {
                    if (window.location.href.indexOf('tab=data_management') !== -1) {
                        loadDebugLogs();
                    }
                }, 100);
            });
        }
        
        // Refresh logs button
        $(document).on('click', '#rank-refresh-logs', function() {
            loadDebugLogs();
        });
        
        // Debug enabled checkbox
        $(document).on('change', '#rank-debug-enabled', function() {
            const isEnabled = $(this).is(':checked');
            
            $.ajax({
                url: rank_ajax_obj.ajax_url,
                type: 'POST',
                data: {
                    action: 'rank_toggle_debug',
                    nonce: rank_ajax_obj.nonce,
                    enabled: isEnabled ? 1 : 0
                },
                success: function(response) {
                    if (response.success) {
                        console.log('Debug logging ' + (isEnabled ? 'enabled' : 'disabled'));
                    } else {
                        console.error('Failed to toggle debug logging:', response.data);
                        // Revert checkbox state on error
                        $('#rank-debug-enabled').prop('checked', !isEnabled);
                    }
                },
                error: function() {
                    console.error('AJAX error toggling debug logging');
                    // Revert checkbox state on error
                    $('#rank-debug-enabled').prop('checked', !isEnabled);
                }
            });
        });
        
        
        
        function loadDebugLogs() {
            $('#rank-logs-loading').show();
            $('#rank-logs-content').hide();
            $('#rank-logs-error').hide();
            
            $.ajax({
                url: rank_ajax_obj.ajax_url,
                type: 'POST',
                data: {
                    action: 'rank_get_debug_logs',
                    nonce: rank_ajax_obj.nonce
                },
                dataType: 'json',
                success: function(response) {
                    $('#rank-logs-loading').hide();
                    
                    if (response.success) {
                        const logs = response.data.logs || '';
                        const timestamp = response.data.timestamp || '';
                        const fileSize = response.data.file_size || '';
                        const linesShown = response.data.lines_shown || 0;
                        
                        $('#rank-logs-content').text(logs).show();
                        
                        // Auto-scroll to bottom
                        const container = $('#rank-logs-container');
                        container.scrollTop(container[0].scrollHeight);
                        
                        // Update info
                        if (logs.trim() === '') {
                            $('#rank-logs-content').html('<div style="text-align: center; color: #666; padding: 20px;">No RANK AI debug logs found. Make sure processing is running or has run recently.</div>');
                        }
                        
                        console.log(`Debug logs loaded: ${linesShown} lines, file size: ${fileSize}, last updated: ${timestamp}`);
                    } else {
                        $('#rank-logs-error').show();
                        $('#rank-logs-error p').text(response.data.message || 'Unknown error loading debug logs');
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    $('#rank-logs-loading').hide();
                    $('#rank-logs-error').show();
                    $('#rank-logs-error p').text('AJAX error loading debug logs: ' + textStatus);
                    console.error('Debug logs AJAX error:', textStatus, errorThrown);
                }
            });
        }
    }
    
    // Initialize debug logs when document is ready
    $(document).ready(function() {
        initDebugLogs();
    });
    
})(jQuery);