/**
 * SEO Visualizations JavaScript for Easy AI Blog Generator
 *
 * Implements visual charts and graphs for the SEO dashboard including:
 * - Keyword Density Gauge
 * - Keyword Distribution Heat Map
 * - Content Length Comparison Chart
 * - SEO Score Gauge
 * Plus 10 additional advanced visualizations
 */

(function($) {
    'use strict';
    
    // Log initialization for debugging
    console.log('SEO Visualizations script loaded');

    // Store Chart.js instances for potential reuse/destruction
    let densityGaugeChart = null;
    let contentLengthChart = null;
    let seoScoreGaugeChart = null;
    let keywordDistributionChart = null;
    
    // New chart instances
    let readabilityScoreChart = null;
    let mobileReadabilityChart = null;
    let contentFreshnessChart = null;
    let contentCompletenessChart = null;
    let linkDistributionChart = null;
    let topicCoverageChart = null;
    let keywordOpportunityChart = null;
    let seoProgressChart = null;
    let competitorBenchmarkChart = null;

    /**
     * Add help tooltips to each visualization
     * Contains explanation text and improvement tips for each chart
     */
    function addVisualizationHelpTooltips() {
        console.log('Adding visualization help tooltips');
        
        const visualizationHelp = {
            'keyword-density-gauge': {
                title: 'Keyword Density',
                explanation: 'Measures how frequently your target keyword appears in your content as a percentage of total words.',
                interpretation: 'Optimal range is 1-3%. Less than 1% may indicate under-optimization, while over 3% could suggest keyword stuffing.',
                tips: [
                    'Aim for 1-2% keyword density for best results',
                    'Include variations of your keyword to avoid repetition',
                    'Ensure keyword usage sounds natural in your content',
                    'Place keywords in important areas like headings, intro, and conclusion'
                ]
            },
            'seo-score-gauge': {
                title: 'SEO Score',
                explanation: 'An overall assessment of your content\'s SEO-friendliness based on multiple factors.',
                interpretation: 'Scores above 80 are excellent, 65-80 are good, 50-65 are average, and below 50 need improvement.',
                tips: [
                    'Address the specific recommendations in the SEO analysis',
                    'Improve lower-scoring aspects first for biggest gains',
                    'Balance keyword optimization with readability',
                    'Re-analyze after making changes to see improvement'
                ]
            },
            'readability-score-gauge': {
                title: 'Readability Score',
                explanation: 'Measures how easy your content is to read and understand based on factors like sentence length and complexity.',
                interpretation: 'Higher scores indicate easier readability. Most web content should aim for grade 6-8 reading level.',
                tips: [
                    'Use shorter sentences and paragraphs',
                    'Choose simpler words when possible',
                    'Break up text with subheadings and bullet points',
                    'Read content aloud to identify difficult sections'
                ]
            },
            'mobile-readability-gauge': {
                title: 'Mobile Readability',
                explanation: 'Assesses how well your content will display and read on mobile devices.',
                interpretation: 'Higher scores indicate better mobile-friendliness. This is crucial as Google uses mobile-first indexing.',
                tips: [
                    'Keep paragraphs to 2-3 sentences maximum',
                    'Use shorter headlines that won\'t wrap on small screens',
                    'Ensure images scale properly on mobile',
                    'Test your content on actual mobile devices'
                ]
            },
            'content-freshness-gauge': {
                title: 'Content Freshness',
                explanation: 'Evaluates how current and up-to-date your content appears to be.',
                interpretation: 'Higher scores indicate fresher content, which search engines often favor, especially for time-sensitive topics.',
                tips: [
                    'Update content regularly with current information',
                    'Add recent statistics or examples',
                    'Reference recent events or developments in your field',
                    'Revise outdated information and examples'
                ]
            },
            'content-completeness-radar': {
                title: 'Content Completeness',
                explanation: 'Shows how thoroughly your content covers different aspects of effective SEO content.',
                interpretation: 'Each point represents a different aspect of content quality. More balanced coverage across all points is ideal.',
                tips: [
                    'Focus on improving your lowest scoring areas first',
                    'Ensure balanced optimization across all elements',
                    'Add missing content elements like images or meta info',
                    'Review competitor content to identify gaps in your coverage'
                ]
            },
            'heading-structure-tree': {
                title: 'Heading Structure',
                explanation: 'Visualizes the hierarchy and organization of your content\'s headings (H1, H2, H3, etc.).',
                interpretation: 'A well-structured document should have a logical hierarchy with a single H1 and properly nested subheadings.',
                tips: [
                    'Use only one H1 tag containing your main keyword',
                    'Create logical sections with H2 headings',
                    'Add H3 and H4 subheadings for subsections',
                    'Include keywords in headings where natural',
                    'Ensure heading hierarchy doesn\'t skip levels (e.g., H2 to H4)'
                ]
            },
            'link-distribution-chart': {
                title: 'Link Distribution',
                explanation: 'Shows the breakdown of internal, external, and nofollow links in your content.',
                interpretation: 'A good mix of internal and external links helps with SEO. Internal links aid site navigation and external links add credibility.',
                tips: [
                    'Include 3-5 internal links to relevant content on your site',
                    'Add 2-3 external links to authoritative sources',
                    'Use nofollow for promotional or untrusted links',
                    'Ensure link text is descriptive and relevant',
                    'Distribute links naturally throughout your content'
                ]
            },
            'topic-coverage-chart': {
                title: 'Topic Coverage',
                explanation: 'Shows how well your content covers important topics related to your main keyword.',
                interpretation: 'Higher coverage percentages indicate more comprehensive content on that topic. Aim for strong coverage of main topics.',
                tips: [
                    'Research related topics using tools like Google\'s "People also ask"',
                    'Expand sections with low coverage percentages',
                    'Add more detail to topics with medium coverage',
                    'Ensure primary topics have at least 70-80% coverage',
                    'Consider creating separate content for related topics with low coverage'
                ]
            },
            'keyword-opportunity-chart': {
                title: 'Keyword Opportunities',
                explanation: 'Identifies potential keywords to target based on search volume, competition, and relevance.',
                interpretation: 'Larger bubbles indicate greater opportunity. Position shows the balance between competition (x-axis) and search volume (y-axis).',
                tips: [
                    'Target keywords in the upper-left quadrant first (high volume, low competition)',
                    'Incorporate secondary keywords naturally throughout your content',
                    'Create specific content for high-opportunity keywords',
                    'Use opportunity keywords in headings and prominent positions',
                    'Track rankings for these keywords after publishing'
                ]
            },
            'seo-progress-chart': {
                title: 'SEO Progress',
                explanation: 'Tracks how your SEO score has changed over time as you\'ve made improvements.',
                interpretation: 'An upward trend indicates your optimization efforts are working. Plateaus may indicate areas needing attention.',
                tips: [
                    'Document what changes led to score improvements',
                    'Address areas that haven\'t improved despite changes',
                    'Set realistic goals for continuous improvement',
                    'Implement advanced SEO techniques once basics are solid',
                    'Compare progress against ranking changes'
                ]
            },
            'competitor-benchmark-chart': {
                title: 'Competitor Benchmark',
                explanation: 'Compares your content against top-ranking competitors across multiple metrics.',
                interpretation: 'Areas where your content\'s line falls inside competitor lines indicate potential for improvement.',
                tips: [
                    'Focus first on metrics where you lag significantly behind competitors',
                    'Study competitor content for those metrics to understand differences',
                    'Don\'t just match competitors—aim to exceed them in key areas',
                    'Use competitor strengths as inspiration, not just for imitation',
                    'Develop unique strengths in areas competitors haven\'t addressed'
                ]
            },
            'content-length-chart': {
                title: 'Content Length',
                explanation: 'Compares your content\'s word count against benchmarks for effective content.',
                interpretation: 'Longer content often ranks better, but quality matters more than quantity. Different topics have different ideal lengths.',
                tips: [
                    'Aim for at least 600 words for standard posts',
                    '1,000-1,500 words is ideal for comprehensive coverage',
                    'Focus on quality and thoroughness, not just word count',
                    'Add depth with examples, statistics, and case studies',
                    'Remove fluff and repetition that doesn\'t add value'
                ]
            },
            'keyword-distribution-chart': {
                title: 'Keyword Distribution',
                explanation: 'Shows how your keywords are distributed throughout different sections of your content.',
                interpretation: 'Ideally, keywords should appear in all major sections, with emphasis in the introduction and conclusion.',
                tips: [
                    'Include your main keyword in the first 100 words',
                    'Distribute keywords naturally throughout the content',
                    'Ensure conclusion contains main keyword and variations',
                    'Add keywords to headings where appropriate',
                    'Avoid sections with no keyword coverage'
                ]
            }
        };
        
        // For each visualization, add the help icon with tooltip
        Object.keys(visualizationHelp).forEach(id => {
            const help = visualizationHelp[id];
            const $heading = $(`#${id}`).closest('.easyai-visualization-item').find('h4:first');
            
            if ($heading.length) {
                // Create the help icon
                const $helpIcon = $('<span class="easyai-help-icon">?</span>');
                
                // Create tooltip content
                const tooltipHTML = `
                    <div class="easyai-tooltip">
                        <div class="easyai-tooltip-section">
                            <h5>${help.title}</h5>
                            <p>${help.explanation}</p>
                        </div>
                        <div class="easyai-tooltip-section">
                            <h5>How to Interpret</h5>
                            <p>${help.interpretation}</p>
                        </div>
                        <div class="easyai-tooltip-section">
                            <h5>Tips to Improve</h5>
                            <ul>
                                ${help.tips.map(tip => `<li>${tip}</li>`).join('')}
                            </ul>
                        </div>
                    </div>
                `;
                
                $helpIcon.append(tooltipHTML);
                $heading.append($helpIcon);
                console.log(`Added help tooltip for: ${id}`);
            } else {
                console.log(`Heading not found for: ${id}`);
            }
        });
    }

    /**
     * Initialize scorecard help toggle functionality
     */
    function initHelpToggle() {
        $('.easyai-scorecard-help-header, .easyai-toggle-help').on('click', function(e) {
            e.preventDefault();
            const $content = $('.easyai-scorecard-help-content');
            const $button = $('.easyai-toggle-help');
            const isVisible = $content.is(':visible');
            
            // Toggle visibility
            if (isVisible) {
                $content.slideUp(200);
                $button.text('Show Help').attr('aria-expanded', 'false');
            } else {
                $content.slideDown(200);
                $button.text('Hide Help').attr('aria-expanded', 'true');
            }
        });
        
        // Initialize interpretation guide toggle
        $('.easyai-interpretation-header, .easyai-toggle-guide').on('click', function(e) {
            e.preventDefault();
            const $content = $('.easyai-interpretation-content');
            const $button = $('.easyai-toggle-guide');
            const isVisible = $content.is(':visible');
            
            // Toggle visibility
            if (isVisible) {
                $content.slideUp(200);
                $button.text('Show Guide').attr('aria-expanded', 'false');
            } else {
                $content.slideDown(200);
                $button.text('Hide Guide').attr('aria-expanded', 'true');
            }
        });
    }

    /**
     * Initialize SEO visualizations with analysis data
     * 
     * @param {Object} data Analysis data from the SEO dashboard
     */
    window.initSEOVisualizations = function(data) {
        console.log('initSEOVisualizations called with data:', data);
        
        try {
            // Remove any loading indicators
            $('.easyai-visualization-loading').remove();
            
            // Check if visualization panel exists
            if ($('#easyai-visualizations-panel').length === 0) {
                console.error('Visualization panel not found, cannot create charts');
                return;
            }

            // Check if Chart.js is loaded
            if (typeof Chart === 'undefined') {
                console.error('Chart.js is not loaded, cannot create charts');
                return;
            }
            
            console.log('Chart.js is loaded, proceeding with visualization creation');
            
            // Initialize help toggle
            initHelpToggle();
            
            // Update all visualizations with the data
            updateAllVisualizations(data);
            
            // Add help tooltips after visualizations are created
            setTimeout(addVisualizationHelpTooltips, 500);
            
            console.log('All visualizations updated');
        } catch (error) {
            console.error('Error in initSEOVisualizations:', error);
        }
    };

    /**
     * Update all visualizations with new data
     * 
     * @param {Object} data Analysis data
     */
    function updateAllVisualizations(data) {
        console.log('Updating all visualizations with data');
        
        try {
            // Make sure Chart.js is loaded before updating charts
            if (typeof Chart === 'undefined') {
                console.error('Chart.js not loaded in updateAllVisualizations');
                loadChartJS(function() {
                    console.log('Chart.js loaded via loadChartJS, retrying updateAllVisualizations');
                    updateAllVisualizations(data);
                });
                return;
            }
            
            // First destroy any existing charts to prevent memory leaks
            destroyCharts();
            
            // Enhance data with sample data for new visualizations
            data = enhanceWithSampleData(data);
            
            // Log canvas elements to check if they exist
            logCanvasElements();
            
            // Create main charts
            try {
                console.log('Creating keyword density gauge');
                densityGaugeChart = createKeywordDensityGauge(data.density);
                
                console.log('Creating SEO score gauge');
                seoScoreGaugeChart = createSEOScoreGauge(data.overallScore);
                
                console.log('Creating content length chart');
                contentLengthChart = createContentLengthChart(data.wordCount);
                
                console.log('Creating keyword distribution map');
                keywordDistributionChart = createKeywordDistributionMap(data);
            } catch (e) {
                console.error('Error creating main charts:', e);
            }
            
            // Create new visualizations
            try {
                console.log('Creating readability score gauge');
                readabilityScoreChart = createReadabilityScoreGauge(data.readabilityScore);
                
                console.log('Creating mobile readability gauge');
                mobileReadabilityChart = createMobileReadabilityGauge(data.mobileReadability);
                
                console.log('Creating content freshness gauge');
                contentFreshnessChart = createContentFreshnessGauge(data.contentFreshness);
                
                console.log('Creating content completeness radar');
                contentCompletenessChart = createContentCompletenessRadar(data.contentCompleteness);
                
                console.log('Creating heading structure tree');
                createHeadingStructureTree(data.headingStructure);
                
                console.log('Creating link distribution chart');
                linkDistributionChart = createLinkDistributionChart(data.linkDistribution);
                
                console.log('Creating topic coverage map');
                topicCoverageChart = createTopicCoverageMap(data.topicCoverage);
                
                console.log('Creating keyword opportunity graph');
                keywordOpportunityChart = createKeywordOpportunityGraph(data.keywordOpportunities);
                
                console.log('Creating SEO progress timeline');
                seoProgressChart = createSEOProgressTimeline(data.seoProgress);
                
                console.log('Creating competitor benchmark chart');
                competitorBenchmarkChart = createCompetitorBenchmarkChart(data.competitorBenchmark);
            } catch (e) {
                console.error('Error creating advanced charts:', e);
            }
            
            // Update the current keyword display if it exists
            if (data.keyword && $('#easyai-current-keyword').length) {
                $('#easyai-current-keyword').text(data.keyword);
            }
        } catch (error) {
            console.error('Error in updateAllVisualizations:', error);
        }
    }
    
    /**
     * Log information about canvas elements
     */
    function logCanvasElements() {
        const canvasIds = [
            'keyword-density-gauge',
            'seo-score-gauge',
            'content-length-chart',
            'keyword-distribution-chart',
            'readability-score-gauge',
            'mobile-readability-gauge',
            'content-freshness-gauge',
            'content-completeness-radar',
            'link-distribution-chart',
            'topic-coverage-chart',
            'keyword-opportunity-chart',
            'seo-progress-chart',
            'competitor-benchmark-chart'
        ];
        
        canvasIds.forEach(id => {
            const canvas = document.getElementById(id);
            if (canvas) {
                console.log(`Canvas #${id} found with dimensions ${canvas.width}x${canvas.height}`);
            } else {
                console.error(`Canvas #${id} not found in the DOM`);
            }
        });
    }
    
    /**
     * Destroy all chart instances to prevent memory leaks and duplicate charts
     */
    function destroyCharts() {
        console.log('Destroying existing chart instances');
        
        try {
            // Destroy main charts
            if (densityGaugeChart) {
                densityGaugeChart.destroy();
                densityGaugeChart = null;
            }
            if (seoScoreGaugeChart) {
                seoScoreGaugeChart.destroy();
                seoScoreGaugeChart = null;
            }
            if (contentLengthChart) {
                contentLengthChart.destroy();
                contentLengthChart = null;
            }
            if (keywordDistributionChart) {
                keywordDistributionChart.destroy();
                keywordDistributionChart = null;
            }
            
            // Destroy new charts if they exist
            if (readabilityScoreChart) {
                readabilityScoreChart.destroy();
                readabilityScoreChart = null;
            }
            if (mobileReadabilityChart) {
                mobileReadabilityChart.destroy();
                mobileReadabilityChart = null;
            }
            if (contentFreshnessChart) {
                contentFreshnessChart.destroy();
                contentFreshnessChart = null;
            }
            if (contentCompletenessChart) {
                contentCompletenessChart.destroy();
                contentCompletenessChart = null;
            }
            if (linkDistributionChart) {
                linkDistributionChart.destroy();
                linkDistributionChart = null;
            }
            if (topicCoverageChart) {
                topicCoverageChart.destroy();
                topicCoverageChart = null;
            }
            if (keywordOpportunityChart) {
                keywordOpportunityChart.destroy();
                keywordOpportunityChart = null;
            }
            if (seoProgressChart) {
                seoProgressChart.destroy();
                seoProgressChart = null;
            }
            if (competitorBenchmarkChart) {
                competitorBenchmarkChart.destroy();
                competitorBenchmarkChart = null;
            }
        } catch (error) {
            console.error('Error destroying charts:', error);
        }
    }
    
    /**
     * Enhance data with sample data for new visualizations
     * 
     * @param {Object} data The data object to enhance
     * @returns {Object} The enhanced data object
     */
    function enhanceWithSampleData(data) {
        if (!data) {
            console.log('No data provided, creating complete sample data');
            data = {
                keyword: 'sample keyword',
                density: 1.5,
                keywordCount: 6,
                wordCount: 550,
                overallScore: 75
            };
        }
        
        // Add sample readability score if not present
        if (!data.readabilityScore) {
            data.readabilityScore = {
                score: 68,
                grade: 'Grade 8',
                status: 'Good'
            };
        }
        
        // Add sample mobile readability if not present
        if (!data.mobileReadability) {
            data.mobileReadability = {
                score: 82,
                status: 'Good',
                issues: []
            };
        }
        
        // Add sample content freshness if not present
        if (!data.contentFreshness) {
            data.contentFreshness = {
                score: 75,
                lastUpdated: '2 weeks ago',
                status: 'Relatively Fresh'
            };
        }
        
        // Add sample content completeness if not present
        if (!data.contentCompleteness) {
            data.contentCompleteness = {
                metrics: [
                    { name: 'Keywords', score: 85 },
                    { name: 'Headings', score: 70 },
                    { name: 'Images', score: 60 },
                    { name: 'Links', score: 75 },
                    { name: 'Meta', score: 90 }
                ]
            };
        }
        
        // Add sample heading structure if not present
        if (!data.headingStructure) {
            data.headingStructure = [
                { tag: 'h1', text: 'Main Title' },
                { tag: 'h2', text: 'First Section' },
                { tag: 'h3', text: 'Subsection 1.1' },
                { tag: 'h3', text: 'Subsection 1.2' },
                { tag: 'h2', text: 'Second Section' },
                { tag: 'h3', text: 'Subsection 2.1' },
                { tag: 'h4', text: 'Sub-subsection 2.1.1' },
                { tag: 'h2', text: 'Third Section' },
                { tag: 'h3', text: 'Subsection 3.1' }
            ];
        }
        
        // Add sample link distribution if not present
        if (!data.linkDistribution) {
            data.linkDistribution = {
                internal: 7,
                external: 3,
                nofollow: 1
            };
        }
        
        // Add sample topic coverage if not present
        if (!data.topicCoverage) {
            data.topicCoverage = [
                { topic: 'Main Keyword', coverage: 90 },
                { topic: 'Related Topic 1', coverage: 75 },
                { topic: 'Related Topic 2', coverage: 60 },
                { topic: 'Related Topic 3', coverage: 45 },
                { topic: 'Related Topic 4', coverage: 30 },
                { topic: 'Related Topic 5', coverage: 80 },
                { topic: 'Related Topic 6', coverage: 65 },
                { topic: 'Related Topic 7', coverage: 50 },
                { topic: 'Related Topic 8', coverage: 35 },
                { topic: 'Related Topic 9', coverage: 20 }
            ];
        }
        
        // Add sample keyword opportunities if not present
        if (!data.keywordOpportunities) {
            data.keywordOpportunities = [
                { keyword: 'main keyword', volume: 1000, competition: 85, score: 60 },
                { keyword: 'long tail keyword', volume: 300, competition: 45, score: 80 },
                { keyword: 'alternative keyword', volume: 800, competition: 70, score: 65 },
                { keyword: 'question keyword', volume: 500, competition: 30, score: 85 },
                { keyword: 'related keyword', volume: 650, competition: 60, score: 75 }
            ];
        }
        
        // Add sample SEO progress if not present
        if (!data.seoProgress) {
            data.seoProgress = [
                { date: 'Week 1', score: 45 },
                { date: 'Week 2', score: 55 },
                { date: 'Week 3', score: 62 },
                { date: 'Week 4', score: 68 },
                { date: 'Current', score: 75 }
            ];
        }
        
        // Add sample competitor benchmark if not present
        if (!data.competitorBenchmark) {
            data.competitorBenchmark = {
                metrics: ['Word Count', 'Keyword Density', 'Readability', 'Link Count', 'Overall SEO'],
                competitors: [
                    { name: 'Your Content', values: [data.wordCount, data.density, data.readabilityScore.score, data.linkDistribution ? (data.linkDistribution.internal + data.linkDistribution.external) : 10, data.overallScore] },
                    { name: 'Competitor 1', values: [900, 1.8, 75, 15, 85] },
                    { name: 'Competitor 2', values: [750, 2.1, 70, 12, 78] },
                    { name: 'Competitor 3', values: [1200, 1.5, 65, 20, 82] }
                ]
            };
        }
        
        return data;
    }

    /**
     * Create the visualizations panel and initialize charts
     * 
     * @param {Object} data Analysis data
     */
    function createVisualizationsPanel(data) {
        console.log('Creating visualizations panel with data');
        data = enhanceWithSampleData(data);
        
        ensureChartJSLoaded(function() {
            console.log('Chart.js loaded, creating charts');
            updateAllVisualizations(data);
        });
    }

    /**
     * Ensure Chart.js is loaded before creating charts
     * 
     * @param {Function} callback Function to call when Chart.js is loaded
     */
    function ensureChartJSLoaded(callback) {
        if (typeof Chart !== 'undefined') {
            console.log('Chart.js already loaded in ensureChartJSLoaded');
            callback();
            return;
        }
        
        console.log('Chart.js not loaded, loading now...');
        loadChartJS(callback);
    }
    
    /**
     * Load Chart.js from CDN
     * 
     * @param {Function} callback Function to call when loaded
     */
    function loadChartJS(callback) {
        try {
            const script = document.createElement('script');
            // Use local Chart.js file path relative to plugin directory
            script.src = easyaiSEOVisualizations.pluginUrl + 'lib/chart.min.js';
            script.onload = function() {
                console.log('Chart.js successfully loaded');
                callback();
            };
            script.onerror = function(error) {
                console.error('Failed to load Chart.js:', error);
                // Try alternative loading method via jQuery
                if (typeof $ !== 'undefined' && $.getScript) {
                    $.getScript(easyaiSEOVisualizations.pluginUrl + 'lib/chart.min.js')
                        .done(function() {
                            console.log('Chart.js loaded via jQuery.getScript');
                            callback();
                        })
                        .fail(function(jqxhr, settings, exception) {
                            console.error('Failed to load Chart.js via jQuery:', exception);
                        });
                }
            };
            document.head.appendChild(script);
        } catch (error) {
            console.error('Error loading Chart.js:', error);
        }
    }

    /**
     * Create keyword density gauge
     * 
     * @param {number} density Keyword density percentage
     * @return {Chart} The Chart.js instance
     */
    function createKeywordDensityGauge(density) {
        const canvas = document.getElementById('keyword-density-gauge');
        if (!canvas) {
            console.error('Canvas element not found: keyword-density-gauge');
            return null;
        }
        
        if (typeof Chart === 'undefined') {
            console.error('Chart.js not available when creating density gauge');
            return null;
        }
        
        // Ensure density is a number
        density = parseFloat(density) || 0;
        
        // Set color based on density range (1-3% is optimal)
        const color = density >= 1 && density <= 3 ? '#46b450' : // Green for optimal
                     (density > 0.5 && density < 1) || (density > 3 && density <= 5) ? '#ffb900' : // Yellow for warning
                     '#dc3232'; // Red for poor
        
        try {
            return new Chart(canvas, {
                type: 'doughnut',
                data: {
                    datasets: [{
                        data: [density, 5 - density],
                        backgroundColor: [color, '#f0f0f0'],
                        borderWidth: 0
                    }]
                },
                options: {
                    circumference: 180,
                    rotation: 270,
                    cutout: '70%',
                    plugins: {
                        tooltip: { enabled: false },
                        legend: { display: false }
                    },
                    responsive: true,
                    maintainAspectRatio: false
                },
                plugins: [{
                    id: 'densityGaugeText',
                    afterDraw: function(chart) {
                        const ctx = chart.ctx;
                        ctx.save();
                        ctx.textAlign = 'center';
                        ctx.textBaseline = 'middle';
                        
                        // Draw density value
                        ctx.font = 'bold 16px Arial';
                        ctx.fillStyle = color;
                        ctx.fillText(density + '%', chart.width / 2, chart.height - 30);
                        
                        // Draw status text
                        ctx.font = '12px Arial';
                        ctx.fillText(
                            density >= 1 && density <= 3 ? 'Optimal' : 
                            (density > 0.5 && density < 1) || (density > 3 && density <= 5) ? 'Suboptimal' : 
                            'Poor', 
                            chart.width / 2, chart.height - 10
                        );
                        
                        ctx.restore();
                    }
                }]
            });
        } catch (error) {
            console.error('Error creating density gauge:', error);
            return null;
        }
    }

    /**
     * Create SEO score gauge
     * 
     * @param {number} score SEO score (0-100)
     * @return {Chart} The Chart.js instance
     */
    function createSEOScoreGauge(score) {
        const canvas = document.getElementById('seo-score-gauge');
        if (!canvas || typeof Chart === 'undefined') return null;
        
        // Determine color based on score
        const color = score >= 80 ? '#46b450' : // Green for excellent
                     (score >= 65 ? '#7ad03a' : // Light green for good
                     (score >= 50 ? '#ffb900' : // Yellow for average
                     (score >= 35 ? '#f56e28' : // Orange for poor
                     '#dc3232'))); // Red for needs work
        
        return new Chart(canvas, {
            type: 'doughnut',
            data: {
                datasets: [{
                    data: [score, 100 - score],
                    backgroundColor: [color, '#f0f0f0'],
                    borderWidth: 0
                }]
            },
            options: {
                circumference: 180, // Half circle
                rotation: 270, // Start from bottom
                cutout: '70%', // Donut hole size
                plugins: {
                    tooltip: { enabled: false },
                    legend: { display: false }
                },
                animation: {
                    animateRotate: true,
                    animateScale: true
                },
                responsive: true,
                maintainAspectRatio: false
            },
            plugins: [{
                id: 'scoreGaugeText',
                afterDraw: function(chart) {
                    const ctx = chart.ctx;
                    ctx.save();
                    ctx.textAlign = 'center';
                    ctx.textBaseline = 'middle';
                    
                    // Draw score value
                    ctx.font = 'bold 16px Arial';
                    ctx.fillStyle = color;
                    ctx.fillText(score + '/100', chart.width / 2, chart.height - 30);
                    
                    // Draw rating text
                    ctx.font = '12px Arial';
                    ctx.fillText(
                        score >= 80 ? 'Excellent' : 
                        (score >= 65 ? 'Good' : 
                        (score >= 50 ? 'Average' : 
                        (score >= 35 ? 'Poor' : 'Needs Work'))), 
                        chart.width / 2, chart.height - 10
                    );
                    
                    ctx.restore();
                }
            }]
        });
    }

    /**
     * Create content length comparison chart
     * 
     * @param {number} wordCount Current word count
     * @return {Chart} The Chart.js instance
     */
    function createContentLengthChart(wordCount) {
        const canvas = document.getElementById('content-length-chart');
        if (!canvas || typeof Chart === 'undefined') return null;
        
        // Define industry benchmarks - keep it simple
        const benchmarks = [
            { label: 'Minimum', count: 300 },
            { label: 'Basic', count: 600 },
            { label: 'Your Content', count: wordCount }
        ];
        
        // Determine color for your content bar
        let contentColor;
        if (wordCount < 300) {
            contentColor = '#dc3232'; // Red - too short
        } else if (wordCount < 600) {
            contentColor = '#ffb900'; // Yellow - basic
        } else {
            contentColor = '#46b450'; // Green - excellent
        }
        
        return new Chart(canvas, {
            type: 'bar',
            data: {
                labels: benchmarks.map(b => b.label),
                datasets: [{
                    label: 'Word Count',
                    data: benchmarks.map(b => b.count),
                    backgroundColor: benchmarks.map(b => 
                        b.label === 'Your Content' ? contentColor : '#e0e0e0'
                    ),
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'Word Count'
                        }
                    }
                },
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.raw + ' words';
                            }
                        }
                    }
                },
                responsive: true,
                maintainAspectRatio: false
            }
        });
    }

    /**
     * Create keyword distribution map
     * 
     * @param {Object} data Analysis data
     * @return {Chart} The Chart.js instance
     */
    function createKeywordDistributionMap(data) {
        const canvas = document.getElementById('keyword-distribution-chart');
        if (!canvas || typeof Chart === 'undefined') return null;
        
        // Create simplified distribution data (4 sections max)
        const sections = ['Introduction', 'Main Content 1', 'Main Content 2', 'Conclusion'];
        const distribution = [
            Math.round(data.keywordCount * 0.3), // 30% in intro
            Math.round(data.keywordCount * 0.4), // 40% in main content 1
            Math.round(data.keywordCount * 0.2), // 20% in main content 2
            Math.round(data.keywordCount * 0.1)  // 10% in conclusion
        ];
        
        return new Chart(canvas, {
            type: 'bar',
            data: {
                labels: sections,
                datasets: [{
                    label: 'Keyword Concentration',
                    data: distribution,
                    backgroundColor: distribution.map(value => {
                        // Color based on concentration
                        return value <= 1 ? 'rgba(171, 211, 174, 0.7)' : // Light green
                               (value <= 3 ? 'rgba(70, 180, 80, 0.7)' : // Green
                               (value <= 5 ? 'rgba(255, 185, 0, 0.7)' : // Yellow
                               'rgba(220, 50, 50, 0.7)')); // Red
                    }),
                    borderWidth: 1
                }]
            },
            options: {
                indexAxis: 'y',
                scales: {
                    x: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'Keyword Occurrences'
                        }
                    }
                },
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.raw + ' keywords';
                            }
                        }
                    }
                },
                responsive: true,
                maintainAspectRatio: false
            }
        });
    }

    /**
     * 1. Create readability score gauge
     * 
     * @param {Object} readabilityData Readability score data
     * @return {Chart} The Chart.js instance
     */
    function createReadabilityScoreGauge(readabilityData) {
        const canvas = document.getElementById('readability-score-gauge');
        if (!canvas || typeof Chart === 'undefined') return null;
        
        const score = readabilityData.score;
        
        // Determine color based on score
        const color = score >= 80 ? '#46b450' : // Green for excellent 
                     (score >= 60 ? '#7ad03a' : // Light green for good
                     (score >= 40 ? '#ffb900' : // Yellow for average
                     '#dc3232')); // Red for poor
        
        return new Chart(canvas, {
            type: 'doughnut',
            data: {
                datasets: [{
                    data: [score, 100 - score],
                    backgroundColor: [color, '#f0f0f0'],
                    borderWidth: 0
                }]
            },
            options: {
                circumference: 180,
                rotation: 270,
                cutout: '70%',
                plugins: {
                    tooltip: { enabled: false },
                    legend: { display: false }
                },
                responsive: true,
                maintainAspectRatio: false
            },
            plugins: [{
                id: 'readabilityGaugeText',
                afterDraw: function(chart) {
                    const ctx = chart.ctx;
                    ctx.save();
                    ctx.textAlign = 'center';
                    ctx.textBaseline = 'middle';
                    
                    // Draw score value
                    ctx.font = 'bold 16px Arial';
                    ctx.fillStyle = color;
                    ctx.fillText(score, chart.width / 2, chart.height - 30);
                    
                    // Draw grade level
                    ctx.font = '12px Arial';
                    ctx.fillText(readabilityData.grade || 'Grade 8', chart.width / 2, chart.height - 10);
                    
                    ctx.restore();
                }
            }]
        });
    }
    
    /**
     * 2. Create mobile readability gauge
     * 
     * @param {Object} mobileData Mobile readability data
     * @return {Chart} The Chart.js instance
     */
    function createMobileReadabilityGauge(mobileData) {
        const canvas = document.getElementById('mobile-readability-gauge');
        if (!canvas || typeof Chart === 'undefined') return null;
        
        const score = mobileData.score;
        
        // Determine color based on score
        const color = score >= 80 ? '#46b450' : // Green for excellent
                     (score >= 60 ? '#7ad03a' : // Light green for good
                     (score >= 40 ? '#ffb900' : // Yellow for average
                     '#dc3232')); // Red for poor
        
        return new Chart(canvas, {
            type: 'doughnut',
            data: {
                datasets: [{
                    data: [score, 100 - score],
                    backgroundColor: [color, '#f0f0f0'],
                    borderWidth: 0
                }]
            },
            options: {
                circumference: 180,
                rotation: 270,
                cutout: '70%',
                plugins: {
                    tooltip: { enabled: false },
                    legend: { display: false }
                },
                responsive: true,
                maintainAspectRatio: false
            },
            plugins: [{
                id: 'mobileGaugeText',
                afterDraw: function(chart) {
                    const ctx = chart.ctx;
                    ctx.save();
                    ctx.textAlign = 'center';
                    ctx.textBaseline = 'middle';
                    
                    // Draw score value
                    ctx.font = 'bold 16px Arial';
                    ctx.fillStyle = color;
                    ctx.fillText(score, chart.width / 2, chart.height - 30);
                    
                    // Draw status text
                    ctx.font = '12px Arial';
                    ctx.fillText(mobileData.status || 'Good', chart.width / 2, chart.height - 10);
                    
                    ctx.restore();
                }
            }]
        });
    }
    
    /**
     * 3. Create content freshness gauge
     * 
     * @param {Object} freshnessData Content freshness data
     * @return {Chart} The Chart.js instance
     */
    function createContentFreshnessGauge(freshnessData) {
        const canvas = document.getElementById('content-freshness-gauge');
        if (!canvas || typeof Chart === 'undefined') return null;
        
        const score = freshnessData.score;
        
        // Determine color based on score
        const color = score >= 80 ? '#46b450' : // Green for excellent
                     (score >= 60 ? '#7ad03a' : // Light green for good
                     (score >= 40 ? '#ffb900' : // Yellow for average
                     '#dc3232')); // Red for poor
        
        return new Chart(canvas, {
            type: 'doughnut',
            data: {
                datasets: [{
                    data: [score, 100 - score],
                    backgroundColor: [color, '#f0f0f0'],
                    borderWidth: 0
                }]
            },
            options: {
                circumference: 180,
                rotation: 270,
                cutout: '70%',
                plugins: {
                    tooltip: { enabled: false },
                    legend: { display: false }
                },
                responsive: true,
                maintainAspectRatio: false
            },
            plugins: [{
                id: 'freshnessGaugeText',
                afterDraw: function(chart) {
                    const ctx = chart.ctx;
                    ctx.save();
                    ctx.textAlign = 'center';
                    ctx.textBaseline = 'middle';
                    
                    // Draw score value
                    ctx.font = 'bold 16px Arial';
                    ctx.fillStyle = color;
                    ctx.fillText(score, chart.width / 2, chart.height - 30);
                    
                    // Draw last updated text
                    ctx.font = '12px Arial';
                    ctx.fillText(freshnessData.lastUpdated || 'Recent', chart.width / 2, chart.height - 10);
                    
                    ctx.restore();
                }
            }]
        });
    }
    
    /**
     * 4. Create content completeness radar chart
     * 
     * @param {Object} completenessData Content completeness data
     * @return {Chart} The Chart.js instance
     */
    function createContentCompletenessRadar(completenessData) {
        const canvas = document.getElementById('content-completeness-radar');
        if (!canvas || typeof Chart === 'undefined') return null;
        
        const metrics = completenessData.metrics;
        const labels = metrics.map(m => m.name);
        const scores = metrics.map(m => m.score);
        
        return new Chart(canvas, {
            type: 'radar',
            data: {
                labels: labels,
                datasets: [{
                    label: 'Content Completeness',
                    data: scores,
                    backgroundColor: 'rgba(0, 115, 170, 0.2)',
                    borderColor: 'rgba(0, 115, 170, 0.8)',
                    pointBackgroundColor: '#0073aa',
                    pointBorderColor: '#fff',
                    pointHoverBackgroundColor: '#fff',
                    pointHoverBorderColor: '#0073aa'
                }]
            },
            options: {
                scales: {
                    r: {
                        angleLines: {
                            display: true,
                            color: 'rgba(0, 0, 0, 0.1)'
                        },
                        suggestedMin: 0,
                        suggestedMax: 100,
                        ticks: {
                            stepSize: 20,
                            backdropColor: 'transparent',
                            display: false
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.raw + '/100';
                            }
                        }
                    }
                },
                elements: {
                    line: {
                        borderWidth: 2
                    }
                },
                responsive: true,
                maintainAspectRatio: false
            }
        });
    }
    
    /**
     * 5. Create heading structure tree
     * 
     * @param {Array} headingData Heading structure data
     */
    function createHeadingStructureTree(headingData) {
        const container = document.getElementById('heading-structure-tree');
        if (!container) return;
        
        container.innerHTML = '';
        
        let lastHeadingLevel = 0;
        let currentParent = container;
        const parents = { 0: container };
        
        headingData.forEach(heading => {
            // Get heading level
            const level = parseInt(heading.tag.charAt(1));
            
            // Create heading element
            const headingEl = document.createElement('div');
            headingEl.className = 'easyai-tree-node';
            
            const headingContent = document.createElement(heading.tag);
            headingContent.textContent = heading.text;
            headingEl.appendChild(headingContent);
            
            // If this is a direct child of the last heading, append to its parent
            if (level > lastHeadingLevel) {
                parents[lastHeadingLevel].appendChild(headingEl);
                parents[level] = headingEl;
            } 
            // If this is a sibling of the last heading, append to its parent's parent
            else if (level === lastHeadingLevel) {
                parents[level - 1].appendChild(headingEl);
                parents[level] = headingEl;
            }
            // If this is a higher level than the last heading, find the appropriate parent
            else {
                parents[level - 1].appendChild(headingEl);
                parents[level] = headingEl;
            }
            
            lastHeadingLevel = level;
        });
    }
    
    /**
     * 6. Create link distribution chart
     * 
     * @param {Object} linkData Link distribution data
     * @return {Chart} The Chart.js instance
     */
    function createLinkDistributionChart(linkData) {
        const canvas = document.getElementById('link-distribution-chart');
        if (!canvas || typeof Chart === 'undefined') return null;
        
        const total = linkData.internal + linkData.external + (linkData.nofollow || 0);
        const internalPercent = Math.round((linkData.internal / total) * 100);
        const externalPercent = Math.round((linkData.external / total) * 100);
        const nofollowPercent = Math.round(((linkData.nofollow || 0) / total) * 100);
        
        return new Chart(canvas, {
            type: 'doughnut',
            data: {
                labels: ['Internal', 'External', 'Nofollow'],
                datasets: [{
                    data: [linkData.internal, linkData.external, linkData.nofollow || 0],
                    backgroundColor: [
                        'rgba(70, 180, 80, 0.7)',
                        'rgba(0, 115, 170, 0.7)',
                        'rgba(255, 185, 0, 0.7)'
                    ],
                    borderColor: [
                        'rgba(70, 180, 80, 1)',
                        'rgba(0, 115, 170, 1)',
                        'rgba(255, 185, 0, 1)'
                    ],
                    borderWidth: 1
                }]
            },
            options: {
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            padding: 10,
                            boxWidth: 12,
                            font: {
                                size: 11
                            },
                            generateLabels: function(chart) {
                                const data = chart.data;
                                if (data.labels.length && data.datasets.length) {
                                    return data.labels.map(function(label, i) {
                                        const meta = chart.getDatasetMeta(0);
                                        const style = meta.controller.getStyle(i);
                                        const value = data.datasets[0].data[i];
                                        const percent = [internalPercent, externalPercent, nofollowPercent][i];
                                        
                                        return {
                                            text: `${label} (${value}, ${percent}%)`,
                                            fillStyle: style.backgroundColor,
                                            strokeStyle: style.borderColor,
                                            lineWidth: style.borderWidth,
                                            hidden: false,
                                            index: i
                                        };
                                    });
                                }
                                return [];
                            }
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const label = context.label || '';
                                const value = context.raw || 0;
                                const total = context.chart.data.datasets[0].data.reduce((a, b) => a + b, 0);
                                const percentage = Math.round((value / total) * 100);
                                return `${label}: ${value} (${percentage}%)`;
                            }
                        }
                    }
                },
                responsive: true,
                maintainAspectRatio: false
            }
        });
    }
    
    /**
     * 7. Create topic coverage map chart
     * 
     * @param {Array} topicData Topic coverage data
     * @return {Chart} The Chart.js instance
     */
    function createTopicCoverageMap(topicData) {
        const canvas = document.getElementById('topic-coverage-chart');
        if (!canvas || typeof Chart === 'undefined') return null;
        
        const sortedData = [...topicData].sort((a, b) => b.coverage - a.coverage);
        const labels = sortedData.map(item => item.topic);
        const values = sortedData.map(item => item.coverage);
        
        return new Chart(canvas, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: 'Coverage',
                    data: values,
                    backgroundColor: values.map(value => {
                        if (value >= 80) return 'rgba(70, 180, 80, 0.7)';
                        if (value >= 60) return 'rgba(109, 200, 94, 0.7)';
                        if (value >= 40) return 'rgba(255, 185, 0, 0.7)';
                        return 'rgba(220, 50, 50, 0.7)';
                    }),
                    borderColor: values.map(value => {
                        if (value >= 80) return 'rgba(70, 180, 80, 1)';
                        if (value >= 60) return 'rgba(109, 200, 94, 1)';
                        if (value >= 40) return 'rgba(255, 185, 0, 1)';
                        return 'rgba(220, 50, 50, 1)';
                    }),
                    borderWidth: 1
                }]
            },
            options: {
                indexAxis: 'y',
                scales: {
                    x: {
                        beginAtZero: true,
                        max: 100,
                        title: {
                            display: true,
                            text: 'Coverage %'
                        }
                    },
                    y: {
                        ticks: {
                            font: {
                                size: 10
                            },
                            callback: function(value) {
                                const label = this.getLabelForValue(value);
                                if (label.length > 15) {
                                    return label.substring(0, 12) + '...';
                                }
                                return label;
                            }
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.raw + '% covered';
                            }
                        }
                    }
                },
                responsive: true,
                maintainAspectRatio: false
            }
        });
    }
    
    /**
     * 8. Create keyword opportunity graph
     * 
     * @param {Array} opportunityData Keyword opportunity data
     * @return {Chart} The Chart.js instance
     */
    function createKeywordOpportunityGraph(opportunityData) {
        const canvas = document.getElementById('keyword-opportunity-chart');
        if (!canvas || typeof Chart === 'undefined') return null;
        
        // Set up data points
        const datasets = [{
            label: 'Keywords',
            data: opportunityData.map(item => ({
                x: item.competition,
                y: item.volume,
                r: item.score / 10, // Size based on opportunity score
                keyword: item.keyword
            })),
            backgroundColor: opportunityData.map(item => {
                if (item.score >= 80) return 'rgba(70, 180, 80, 0.7)';
                if (item.score >= 60) return 'rgba(109, 200, 94, 0.7)';
                if (item.score >= 40) return 'rgba(255, 185, 0, 0.7)';
                return 'rgba(220, 50, 50, 0.7)';
            }),
            borderColor: 'rgba(0, 0, 0, 0.1)',
            borderWidth: 1
        }];
        
        return new Chart(canvas, {
            type: 'bubble',
            data: {
                datasets: datasets
            },
            options: {
                scales: {
                    x: {
                        min: 0,
                        max: 100,
                        title: {
                            display: true,
                            text: 'Competition Level'
                        }
                    },
                    y: {
                        min: 0,
                        title: {
                            display: true,
                            text: 'Search Volume'
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const keyword = context.raw.keyword;
                                const volume = context.raw.y;
                                const competition = context.raw.x;
                                const score = context.raw.r * 10;
                                return [
                                    `Keyword: ${keyword}`,
                                    `Volume: ${volume}`,
                                    `Competition: ${competition}%`,
                                    `Opportunity Score: ${score}`
                                ];
                            }
                        }
                    }
                },
                responsive: true,
                maintainAspectRatio: false
            }
        });
    }

    /**
     * Create SEO progress timeline
     * 
     * @param {Array} progressData SEO progress data
     * @return {Chart} The Chart.js instance
     */
    function createSEOProgressTimeline(progressData) {
        const canvas = document.getElementById('seo-progress-chart');
        if (!canvas || typeof Chart === 'undefined') return null;
        
        return new Chart(canvas, {
            type: 'line',
            data: {
                labels: progressData.map(item => item.date),
                datasets: [{
                    label: 'SEO Score',
                    data: progressData.map(item => item.score),
                    borderColor: 'rgba(70, 180, 80, 1)',
                    borderWidth: 2,
                    fill: false
                }]
            },
            options: {
                scales: {
                    x: {
                        type: 'time',
                        time: {
                            unit: 'week'
                        },
                        title: {
                            display: true,
                            text: 'Date'
                        }
                    },
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'SEO Score'
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const score = context.parsed.y;
                                return `Score: ${score}`;
                            }
                        }
                    }
                },
                responsive: true,
                maintainAspectRatio: false
            }
        });
    }

    /**
     * Create competitor benchmark chart
     * 
     * @param {Object} benchmarkData Competitor benchmark data
     * @return {Chart} The Chart.js instance
     */
    function createCompetitorBenchmarkChart(benchmarkData) {
        const canvas = document.getElementById('competitor-benchmark-chart');
        if (!canvas || typeof Chart === 'undefined') return null;
        
        const metrics = benchmarkData.metrics;
        const competitors = benchmarkData.competitors;
        
        const chartData = {
            labels: metrics,
            datasets: [{
                label: 'Your Content',
                data: competitors.find(c => c.name === 'Your Content').values,
                borderColor: 'rgba(70, 180, 80, 1)',
                borderWidth: 2,
                fill: false
            }]
        };
        
        competitors.forEach(competitor => {
            if (competitor.name !== 'Your Content') {
                chartData.datasets.push({
                    label: competitor.name,
                    data: competitor.values,
                    borderColor: 'rgba(0, 0, 0, 0.1)',
                    borderWidth: 1,
                    fill: false
                });
            }
        });
        
        return new Chart(canvas, {
            type: 'bar',
            data: chartData,
            options: {
                scales: {
                    x: {
                        title: {
                            display: true,
                            text: 'Metric'
                        }
                    },
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: 'Value'
                        }
                    }
                },
                plugins: {
                    legend: {
                        display: true
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const value = context.parsed.y;
                                return `Value: ${value}`;
                            }
                        }
                    }
                },
                responsive: true,
                maintainAspectRatio: false
            }
        });
    }
})(jQuery);