/**
 * API Key Notice Module
 * Ensures the API key notice is displayed when needed
 */
(function($, rank) {
    'use strict';
    
    // Function to add the API key notice
    function addApiKeyNotice() {
        // Check if we're on the correct admin page
        const urlParams = new URLSearchParams(window.location.search);
        const currentPage = urlParams.get('page');
        
        if (currentPage !== 'rank-admin') {
            return;
        }
        
        const currentTab = urlParams.get('tab') || 'bulk_fix';
        
        if (currentTab !== 'bulk_fix') {
            return;
        }
        
        const $wrapWithApiKey = $('.wrap[data-api-key-set]');
        
        if ($wrapWithApiKey.length === 0) {
            if ($('#rank-health-issues-container').length > 0 || $('.rank-section').length > 0) {
                return;
            }
        } else {
            const isApiKeySet = $wrapWithApiKey.data('api-key-set') === 'yes';
            if (isApiKeySet) {
                return;
            }
        }
        
        if ($('.rank-api-key-notice').length > 0) {
            return;
        }
        
        // Get the current URL and replace or add the tab parameter
        const currentUrl = new URL(window.location.href);
        currentUrl.searchParams.set('tab', 'api_config');
        
        // Create the notice with a link to the API config tab
        const $notice = $('<div class="notice notice-warning rank-api-key-notice" style="display: block !important; margin-top: 10px;">' +
            '<p><a href="' + currentUrl.toString() + '">Add API key in settings</a> to start fixing issues 🚀</p>' +
            '</div>');
        
        $('.nav-tab-wrapper').after($notice);
    }
    
    // Run when the document is ready
    $(document).ready(function() {
        // Add a small delay to ensure other scripts have run and DOM is fully loaded
        setTimeout(function() {
            try {
                addApiKeyNotice();
            } catch (error) {
                console.error('RANK AI: Error in addApiKeyNotice:', error);
            }
        }, 100);
    });
    
})(jQuery, window.rank = window.rank || {});