// Approach 3: Initialize when analyze button is clicked
$(document).on('click', '#easyai-analyze-button, #easyai-analyze-content', function() {
    console.log('Analyze button clicked');
    
    // Ensure the panel exists
    if (!$('#easyai-visualizations-panel').length) {
        console.log('Creating visualization panel after analyze click');
        createVisualizationsPanel();
    }
    
    // Add loading indicators
    $('.easyai-visualization-container').each(function() {
        const $container = $(this);
        if (!$container.find('.easyai-visualization-loading').length) {
            $container.append('<div class="easyai-visualization-loading"><span>Updating...</span></div>');
        }
    });
    
    // After a short delay, update the visualizations
    setTimeout(function() {
        $('.easyai-visualization-loading').remove();
        
        ensureChartJsLoaded(function() {
            loadVisualizationsScript(function() {
                console.log('Scripts loaded after analyze click, initializing visualizations');
                initializeVisualizations();
            });
        });
    }, 2000);
});

// Additional approach: Check if analyzing state persists too long
setTimeout(function() {
    const currentKeyword = $('#easyai-current-keyword').text();
    if (currentKeyword === 'Analyzing...' || !$('#easyai-visualizations-panel').length) {
        console.log('Still analyzing after timeout or visualization panel not found, creating fallback visualization');
        
        // Create the visualization panel if it doesn't exist
        if (!$('#easyai-visualizations-panel').length) {
            createVisualizationsPanel();
        }
        
        // Create fallback data
        window.analysisData = {
            keyword: 'example keyword',
            density: 1.2,
            keywordCount: 5,
            wordCount: 500,
            overallScore: 70
        };
        
        // Initialize visualizations
        ensureChartJsLoaded(function() {
            loadVisualizationsScript(function() {
                if (typeof window.initSEOVisualizations === 'function') {
                    console.log('Initializing visualizations with fallback data');
                    window.initSEOVisualizations(window.analysisData);
                }
            });
        });
    }
}, 5000); 