<?php
/**
 * SEO Dashboard Visualization Module
 *
 * This file adds automatic SEO visualizations and scoring to the content editor.
 *
 * @package EasyAIBlogGenerator
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Add SEO visualizations to the dashboard
 */
function easyaibloggen_add_seo_visualizations() {
	?>
	<script>
	jQuery(document).ready(function($) {
		console.log('SEO visualizations script running');
		
		// Function to create the visualization panel
		function createVisualizationsPanel() {
			console.log('Creating visualizations panel');
			
			// Panel HTML from before (unchanged)
			const panelHTML = `
				<div id="easyai-visualizations-panel" class="easyai-seo-visualizations-panel">
					<h3>Easy AI Blog Generator Scorecard</h3>
					<p id="easyai-current-keyword" class="easyai-current-keyword-display">Analyzing your content...</p>
					
					<div class="easyai-scorecard-help">
						<div class="easyai-scorecard-help-header">
							<span class="easyai-help-icon-large">?</span>
							<h4>How to Use This SEO Scorecard</h4>
							<button class="easyai-toggle-help" aria-expanded="false">Show Help</button>
						</div>
						<div class="easyai-scorecard-help-content" style="display: none;">
							<p>This SEO scorecard provides a comprehensive analysis of your content with actionable metrics to improve your search engine rankings. Here's how to use it:</p>
							<ol>
								<li><strong>Analyze your content</strong> by clicking the "Analyze Content" button to get fresh data.</li>
								<li><strong>Review each visualization</strong> to identify areas of strength and opportunities for improvement.</li>
								<li><strong>Hover over the question mark icon</strong> next to each visualization for detailed explanations and improvement tips.</li>
								<li><strong>Make targeted improvements</strong> to your content based on the suggestions.</li>
								<li><strong>Re-analyze after changes</strong> to see your progress.</li>
							</ol>
							<p><strong>Tip:</strong> Focus on improving your lowest-scoring metrics first for the biggest SEO impact.</p>
						</div>
					</div>
					
					<!-- Main SEO Metrics Section -->
					<div class="easyai-visualizations-section">
						<h4 class="easyai-section-heading">Main SEO Metrics</h4>
						<div class="easyai-visualizations-grid">
							<div class="easyai-visualization-item">
								<h4>Keyword Density</h4>
								<div class="easyai-visualization-container">
									<canvas id="keyword-density-gauge"></canvas>
								</div>
							</div>
							<div class="easyai-visualization-item">
								<h4>SEO Score</h4>
								<div class="easyai-visualization-container">
									<canvas id="seo-score-gauge"></canvas>
								</div>
							</div>
						</div>
					</div>
					
					<!-- Content Quality Metrics Section -->
					<div class="easyai-visualizations-section">
						<h4 class="easyai-section-heading">Content Quality Metrics</h4>
						<div class="easyai-visualizations-grid">
							<div class="easyai-visualization-item">
								<h4>Readability Score</h4>
								<div class="easyai-visualization-container">
									<canvas id="readability-score-gauge"></canvas>
								</div>
							</div>
							<div class="easyai-visualization-item">
								<h4>Mobile Readability</h4>
								<div class="easyai-visualization-container">
									<canvas id="mobile-readability-gauge"></canvas>
								</div>
							</div>
							<div class="easyai-visualization-item">
								<h4>Content Freshness</h4>
								<div class="easyai-visualization-container">
									<canvas id="content-freshness-gauge"></canvas>
								</div>
							</div>
							<div class="easyai-visualization-item">
								<h4>Content Completeness</h4>
								<div class="easyai-visualization-container">
									<canvas id="content-completeness-radar"></canvas>
								</div>
							</div>
						</div>
					</div>
					
					<!-- Content Structure Metrics Section -->
					<div class="easyai-visualizations-section">
						<h4 class="easyai-section-heading">Content Structure</h4>
						<div class="easyai-visualizations-grid">
							<div class="easyai-visualization-item">
								<h4>Heading Structure</h4>
								<div class="easyai-visualization-container" id="heading-structure-tree">
									<!-- Heading structure tree will be rendered here -->
								</div>
							</div>
							<div class="easyai-visualization-item">
								<h4>Link Distribution</h4>
								<div class="easyai-visualization-container">
									<canvas id="link-distribution-chart"></canvas>
								</div>
							</div>
							<div class="easyai-visualization-item easyai-visualization-full">
								<h4>Topic Coverage</h4>
								<div class="easyai-visualization-container">
									<canvas id="topic-coverage-chart"></canvas>
								</div>
							</div>
						</div>
					</div>
					
					<!-- Advanced SEO Insights Section -->
					<div class="easyai-visualizations-section">
						<h4 class="easyai-section-heading">Advanced SEO Insights</h4>
						<div class="easyai-visualizations-grid">
							<div class="easyai-visualization-item">
								<h4>Keyword Opportunities</h4>
								<div class="easyai-visualization-container">
									<canvas id="keyword-opportunity-chart"></canvas>
								</div>
							</div>
							<div class="easyai-visualization-item">
								<h4>SEO Progress</h4>
								<div class="easyai-visualization-container">
									<canvas id="seo-progress-chart"></canvas>
								</div>
							</div>
							<div class="easyai-visualization-item easyai-visualization-full">
								<h4>Competitor Benchmark</h4>
								<div class="easyai-visualization-container">
									<canvas id="competitor-benchmark-chart"></canvas>
								</div>
							</div>
						</div>
					</div>
					
					<!-- Content Length Chart Section -->
					<div class="easyai-visualizations-section">
						<h4 class="easyai-section-heading">Content Details</h4>
						<div class="easyai-visualizations-grid">
							<div class="easyai-visualization-item easyai-visualization-full">
								<h4>Content Length Comparison</h4>
								<div class="easyai-visualization-container">
									<canvas id="content-length-chart"></canvas>
								</div>
							</div>
							<div class="easyai-visualization-item easyai-visualization-full">
								<h4>Keyword Distribution</h4>
								<div class="easyai-visualization-container">
									<canvas id="keyword-distribution-chart"></canvas>
								</div>
							</div>
						</div>
					</div>
					
					<!-- SEO Interpretation Guide -->
					<div class="easyai-interpretation-guide">
						<div class="easyai-interpretation-header">
							<h4>SEO Metrics Interpretation Guide</h4>
							<button class="easyai-toggle-guide" aria-expanded="false">Show Guide</button>
						</div>
						<div class="easyai-interpretation-content" style="display: none;">
							<table class="easyai-metrics-table">
								<thead>
									<tr>
										<th>Metric</th>
										<th>Excellent</th>
										<th>Good</th>
										<th>Needs Improvement</th>
									</tr>
								</thead>
								<tbody>
									<tr>
										<td>Keyword Density</td>
										<td>1-2%</td>
										<td>0.5-1% or 2-3%</td>
										<td>&lt;0.5% or &gt;3%</td>
									</tr>
									<tr>
										<td>SEO Score</td>
										<td>80-100</td>
										<td>65-79</td>
										<td>&lt;65</td>
									</tr>
									<tr>
										<td>Readability Score</td>
										<td>70-90</td>
										<td>60-69</td>
										<td>&lt;60 or &gt;90</td>
									</tr>
									<tr>
										<td>Mobile Readability</td>
										<td>80-100</td>
										<td>65-79</td>
										<td>&lt;65</td>
									</tr>
									<tr>
										<td>Content Freshness</td>
										<td>80-100 (Updated recently)</td>
										<td>50-79 (Updated within 6 months)</td>
										<td>&lt;50 (Outdated)</td>
									</tr>
									<tr>
										<td>Content Length</td>
										<td>1000+ words</td>
										<td>600-999 words</td>
										<td>&lt;600 words</td>
									</tr>
									<tr>
										<td>Heading Structure</td>
										<td>Clear hierarchy with H1, H2, H3</td>
										<td>Basic structure with H1, H2</td>
										<td>Missing hierarchy or headings</td>
									</tr>
									<tr>
										<td>Link Distribution</td>
										<td>3-5 internal, 2-3 external</td>
										<td>1-2 internal, 1-2 external</td>
										<td>No links or excessive links</td>
									</tr>
								</tbody>
							</table>
							<div class="easyai-guide-notes">
								<h5>Important Notes:</h5>
								<ul>
									<li>These metrics are guidelines, not strict rules. Different content types may require different optimal values.</li>
									<li>Content quality and relevance to user intent should always be your primary focus.</li>
									<li>Regularly update your content to maintain freshness and accuracy.</li>
									<li>Use the "Analyze Content" button after making changes to see your updated scores.</li>
								</ul>
							</div>
						</div>
					</div>
				</div>
			`;
			
			// Check if panel already exists
			if ($('#easyai-visualizations-panel').length === 0) {
				console.log('Visualization panel not found, creating it now');
				// Find the SEO dashboard container and append the panel
				const $dashboardContainer = $('.easyai-seo-dashboard-wrapper');
				if ($dashboardContainer.length) {
					console.log('Dashboard container found, appending visualization panel');
					$dashboardContainer.append(panelHTML);
					
					// Log all canvas elements to ensure they exist
					setTimeout(function() {
						console.log('Canvas elements after panel creation:');
						$('canvas').each(function() {
							console.log('Canvas ID:', $(this).attr('id'));
						});
					}, 500);
					
					// Initialize visualizations with sample data if no analysis data exists
					setTimeout(function() {
						if (!window.analysisData) {
							console.log('No analysis data found, creating sample data');
							window.analysisData = {
								keyword: 'sample keyword',
								density: 1.5,
								keywordCount: 6,
								wordCount: 550,
								overallScore: 75
							};
						}
						
						ensureChartJsLoaded(function() {
							loadVisualizationsScript(function() {
								console.log('Scripts loaded, initializing visualizations');
								if (typeof window.initSEOVisualizations === 'function') {
									window.initSEOVisualizations(window.analysisData);
								} else {
									console.error('initSEOVisualizations function not found');
								}
							});
						});
					}, 1000);
				} else {
					console.error('Dashboard container not found, cannot create visualization panel');
				}
			} else {
				console.log('Visualization panel already exists');
			}
		}
		
		// Function to ensure Chart.js is loaded
		function ensureChartJsLoaded(callback) {
			console.log('Ensuring Chart.js is loaded');
			if (typeof Chart !== 'undefined') {
				console.log('Chart.js already loaded');
				callback();
				return;
			}
			
			console.log('Chart.js not loaded, loading now');
			const script = document.createElement('script');
			script.src = easyaiSEOVisualizations.pluginUrl + 'lib/chart.min.js';
			script.onload = function() {
				console.log('Chart.js loaded successfully');
				callback();
			};
			script.onerror = function(error) {
				console.error('Failed to load Chart.js:', error);
				// Try alternative loading method
				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);
		}
		
		// Function to load the visualizations script
		function loadVisualizationsScript(callback) {
			console.log('Loading visualizations script');
			if (typeof window.initSEOVisualizations !== 'undefined') {
				console.log('Visualizations script already loaded');
				callback();
				return;
			}
			
			console.log('Visualizations script not loaded, loading now');
			const script = document.createElement('script');
			script.src = easyaiSEOVisualizations.pluginUrl + 'js/easyaibloggen-seo-visualizations.js';
			script.onload = function() {
				console.log('Visualizations script loaded successfully');
				callback();
			};
			script.onerror = function(error) {
				console.error('Failed to load visualizations script:', error);
				// Try alternative loading method
				if (typeof $ !== 'undefined' && $.getScript) {
					$.getScript(easyaiSEOVisualizations.pluginUrl + 'js/easyaibloggen-seo-visualizations.js')
						.done(function() {
							console.log('Visualizations script loaded via jQuery.getScript');
							callback();
						})
						.fail(function(jqxhr, settings, exception) {
							console.error('Failed to load visualizations script via jQuery:', exception);
						});
				}
			};
			document.head.appendChild(script);
		}
		
		// Function to initialize visualizations
		function initializeVisualizations() {
			console.log('Preparing to initialize visualizations');
			
			// Create sample data if none exists
			if (!window.easyaiSEOAnalysisData) {
				console.log('No analysis data found, creating sample data');
				window.easyaiSEOAnalysisData = {
					keyword: 'WordPress plugin',
					density: 1.2,
					keywordCount: 7,
					wordCount: 580,
					overallScore: 78,
					readabilityScore: {
						score: 72,
						grade: 'Grade 8'
					}
				};
			}
			
			// Call the visualization initialization function
			if (typeof window.initSEOVisualizations === 'function') {
				console.log('Calling initSEOVisualizations with data:', window.easyaiSEOAnalysisData);
				window.initSEOVisualizations(window.easyaiSEOAnalysisData);
			} else {
				console.error('initSEOVisualizations function not found!');
			}
		}
		
		// Main initialization function
		function initVisualizations() {
			console.log('Starting visualization initialization process');
			
			// First create the panel
			createVisualizationsPanel();
			
			// Then ensure Chart.js is loaded
			ensureChartJsLoaded(function() {
				// Then load our visualization script
				loadVisualizationsScript(function() {
					// Finally initialize the visualizations
					initializeVisualizations();
				});
			});
		}
		
		// Try multiple approaches to ensure visualizations are initialized
		
		// Approach 1: Use dashboard loaded event
		$(document).on('easyai_dashboard_loaded', function() {
			console.log('Dashboard loaded event fired');
			initVisualizations();
		});
		
		// Approach 2: Direct initialization after a delay to ensure DOM is ready
		setTimeout(function() {
			if (!$('#easyai-visualizations-panel').length) {
				console.log('Visualization panel not found after timeout, initializing directly');
				initVisualizations();
			}
		}, 1000);
		
		// 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>');
				}
			});
			
			// Debug output to console
			console.log('---- DEBUG INFO ----');
			console.log('Visualization panel exists:', $('#easyai-visualizations-panel').length > 0);
			console.log('Chart.js loaded:', typeof Chart !== 'undefined');
			console.log('initSEOVisualizations function exists:', typeof window.initSEOVisualizations !== 'undefined');
			console.log('Analysis data:', window.analysisData);
			console.log('Chart.js path:', easyaiSEOVisualizations.pluginUrl + 'lib/chart.min.js');
			console.log('Canvas elements:', $('canvas').length);
			$('canvas').each(function() {
				console.log('- Canvas ID:', $(this).attr('id'));
			});
			console.log('------------------');
			
			// DIRECT FIX: Immediately create SEO Progress and Competitor Benchmark charts
			// No delays, no conditions, just create them right away
			console.log('DIRECT FIX: Creating charts immediately on click');
			
			// SEO Progress Chart - Fixed dimensions and direct creation
			const seoProgressContainer = $('#seo-progress-chart').parent();
			if (seoProgressContainer.length && typeof Chart !== 'undefined') {
				// First remove any existing canvas to ensure clean state
				$('#seo-progress-chart').remove();
				
				// Create a new canvas with explicit dimensions
				const progressCanvas = $('<canvas id="seo-progress-chart" width="400" height="250" style="display:block; width:100%; height:250px;"></canvas>');
				seoProgressContainer.append(progressCanvas);
				seoProgressContainer.find('.easyai-visualization-loading').remove();
				
				// Create chart directly
				const progressCtx = document.getElementById('seo-progress-chart').getContext('2d');
				if (window.seoProgressChart) {
					window.seoProgressChart.destroy();
				}
				
				window.seoProgressChart = new Chart(progressCtx, {
					type: 'line',
					data: {
						labels: ['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Current'],
						datasets: [{
							label: 'SEO Score',
							data: [45, 55, 62, 68, 75],
							backgroundColor: 'rgba(34, 113, 177, 0.2)',
							borderColor: 'rgba(34, 113, 177, 1)',
							borderWidth: 2,
							pointBackgroundColor: 'rgba(34, 113, 177, 1)',
							pointBorderColor: '#fff',
							pointRadius: 5,
							tension: 0.1
						}]
					},
					options: {
						responsive: true,
						maintainAspectRatio: false,
						scales: {
							y: {
								beginAtZero: true,
								max: 100,
								title: {
									display: true,
									text: 'SEO Score'
								}
							},
							x: {
								title: {
									display: true,
									text: 'Time Period'
								}
							}
						}
					}
				});
				console.log('SEO Progress chart created immediately:', window.seoProgressChart);
			}
			
			// Competitor Benchmark Chart - Fixed dimensions and direct creation
			const competitorContainer = $('#competitor-benchmark-chart').parent();
			if (competitorContainer.length && typeof Chart !== 'undefined') {
				// First remove any existing canvas to ensure clean state
				$('#competitor-benchmark-chart').remove();
				
				// Create a new canvas with explicit dimensions
				const benchmarkCanvas = $('<canvas id="competitor-benchmark-chart" width="400" height="250" style="display:block; width:100%; height:250px;"></canvas>');
				competitorContainer.append(benchmarkCanvas);
				competitorContainer.find('.easyai-visualization-loading').remove();
				
				// Create chart directly
				const benchmarkCtx = document.getElementById('competitor-benchmark-chart').getContext('2d');
				if (window.competitorBenchmarkChart) {
					window.competitorBenchmarkChart.destroy();
				}
				
				window.competitorBenchmarkChart = new Chart(benchmarkCtx, {
					type: 'radar',
					data: {
						labels: ['Word Count', 'Keyword Density', 'Readability', 'Link Count', 'Overall SEO'],
						datasets: [
							{
								label: 'Your Content',
								data: [70, 85, 75, 60, 70],
								backgroundColor: 'rgba(34, 113, 177, 0.2)',
								borderColor: 'rgba(34, 113, 177, 1)',
								borderWidth: 2,
								pointBackgroundColor: 'rgba(34, 113, 177, 1)',
								pointBorderColor: '#fff'
							},
							{
								label: 'Competitor 1',
								data: [90, 65, 80, 75, 85],
								backgroundColor: 'rgba(255, 99, 132, 0.2)',
								borderColor: 'rgba(255, 99, 132, 1)',
								borderWidth: 2,
								pointBackgroundColor: 'rgba(255, 99, 132, 1)',
								pointBorderColor: '#fff'
							},
							{
								label: 'Competitor 2',
								data: [85, 70, 65, 90, 75],
								backgroundColor: 'rgba(75, 192, 192, 0.2)',
								borderColor: 'rgba(75, 192, 192, 1)',
								borderWidth: 2,
								pointBackgroundColor: 'rgba(75, 192, 192, 1)',
								pointBorderColor: '#fff'
							}
						]
					},
					options: {
						responsive: true,
						maintainAspectRatio: false,
						scales: {
							r: {
								angleLines: {
									display: true
								},
								suggestedMin: 0,
								suggestedMax: 100
							}
						}
					}
				});
				console.log('Competitor Benchmark chart created immediately:', window.competitorBenchmarkChart);
			}
			
			// Create specific fallback data for the missing charts
			const specificChartData = {
				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 }
				],
				competitorBenchmark: {
					metrics: ['Word Count', 'Keyword Density', 'Readability', 'Link Count', 'Overall SEO'],
					competitors: [
						{ name: 'Your Content', values: [500, 1.29, 75, 10, 70] },
						{ 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] }
					]
				}
			};
			
			// After a short delay, update just these specific charts
			setTimeout(function() {
				// Ensure Chart.js is loaded
				if (typeof Chart !== 'undefined') {
					console.log('Creating SEO Progress and Competitor Benchmark charts specifically');
					
					// Create SEO Progress chart
					const seoProgressCanvas = document.getElementById('seo-progress-chart');
					if (seoProgressCanvas) {
						// Destroy existing chart if any
						if (window.seoProgressChart) {
							window.seoProgressChart.destroy();
						}
						
						// Clear any loading indicators
						$(seoProgressCanvas).parent().find('.easyai-visualization-loading').remove();
						
						// Create new chart
						window.seoProgressChart = new Chart(seoProgressCanvas, {
							type: 'line',
							data: {
								labels: specificChartData.seoProgress.map(item => item.date),
								datasets: [{
									label: 'SEO Score',
									data: specificChartData.seoProgress.map(item => item.score),
									backgroundColor: 'rgba(34, 113, 177, 0.2)',
									borderColor: 'rgba(34, 113, 177, 1)',
									borderWidth: 2,
									pointBackgroundColor: 'rgba(34, 113, 177, 1)',
									pointBorderColor: '#fff',
									pointRadius: 5,
									tension: 0.1
								}]
							},
							options: {
								responsive: true,
								maintainAspectRatio: false,
								scales: {
									y: {
										beginAtZero: true,
										max: 100,
										title: {
											display: true,
											text: 'SEO Score'
										}
									},
									x: {
										title: {
											display: true,
											text: 'Time Period'
										}
									}
								},
								plugins: {
									tooltip: {
										callbacks: {
											label: function(context) {
												return 'Score: ' + context.parsed.y;
											}
										}
									}
								}
							}
						});
					}
					
					// Create Competitor Benchmark chart
					const competitorBenchmarkCanvas = document.getElementById('competitor-benchmark-chart');
					if (competitorBenchmarkCanvas) {
						// Destroy existing chart if any
						if (window.competitorBenchmarkChart) {
							window.competitorBenchmarkChart.destroy();
						}
						
						// Clear any loading indicators
						$(competitorBenchmarkCanvas).parent().find('.easyai-visualization-loading').remove();
						
						// Create new chart
						window.competitorBenchmarkChart = new Chart(competitorBenchmarkCanvas, {
							type: 'radar',
							data: {
								labels: specificChartData.competitorBenchmark.metrics,
								datasets: specificChartData.competitorBenchmark.competitors.map((competitor, index) => {
									// Different colors for each competitor
									const colors = [
										'rgba(34, 113, 177, 0.7)',  // Blue for your content
										'rgba(255, 99, 132, 0.7)',  // Red
										'rgba(75, 192, 192, 0.7)',  // Green
										'rgba(255, 159, 64, 0.7)'   // Orange
									];
									
									return {
										label: competitor.name,
										data: competitor.values,
										backgroundColor: colors[index].replace('0.7', '0.2'),
										borderColor: colors[index],
										borderWidth: 2,
										pointBackgroundColor: colors[index],
										pointBorderColor: '#fff',
										pointRadius: 4
									};
								})
							},
							options: {
								responsive: true,
								maintainAspectRatio: false,
								scales: {
									r: {
										angleLines: {
											display: true
										},
										suggestedMin: 0,
										suggestedMax: 100
									}
								},
								plugins: {
									tooltip: {
										callbacks: {
											label: function(context) {
												return context.dataset.label + ': ' + context.raw;
											}
										}
									}
								}
							}
						});
					}
				}
			}, 1000);
		});
		
		// Final approach: Force create visualizations after 3 seconds if not present
		setTimeout(function() {
			console.log('Final check - Forcing visualization creation if not already present');
			if (!$('#easyai-visualizations-panel').length) {
				console.log('Forcing visualization panel creation');
				createVisualizationsPanel();
				
				// Create some sample data to ensure visualizations appear
				setTimeout(function() {
					console.log('Creating sample data for visualizations');
					const sampleData = {
						keyword: 'WordPress plugin',
						density: 1.2,
						keywordCount: 5,
						wordCount: 500,
						overallScore: 70,
						checksStatus: {
							title: true,
							firstParagraph: true,
							h2: true,
							meta: false,
							variants: true,
							density: true
						}
					};
					
					if (typeof window.initSEOVisualizations === 'function') {
						window.initSEOVisualizations(sampleData);
					} else {
						console.error('initSEOVisualizations function still not available!');
						// Try loading the visualization script again
						loadVisualizationsScript(function() {
							if (typeof window.initSEOVisualizations === 'function') {
								window.initSEOVisualizations(sampleData);
							}
						});
					}
				}, 1000);
			}
		}, 3000);
		
		// Fix toggle buttons that collapse immediately
		$(document).on('click', '.easyai-toggle-help, .easyai-toggle-guide', function(e) {
			e.preventDefault();
			e.stopPropagation();
			
			const $button = $(this);
			const isHelp = $button.hasClass('easyai-toggle-help');
			const $content = isHelp ? $('.easyai-scorecard-help-content') : $('.easyai-interpretation-content');
			const isExpanded = $button.attr('aria-expanded') === 'true';
			
			// Toggle button state
			$button.attr('aria-expanded', !isExpanded);
			$button.text(isExpanded ? (isHelp ? 'Show Help' : 'Show Guide') : (isHelp ? 'Hide Help' : 'Hide Guide'));
			
			// Toggle content visibility
			if (isExpanded) {
				$content.slideUp(200);
			} else {
				$content.slideDown(200);
			}
			
			// Prevent default click behavior and propagation
			return false;
		});

		// EMERGENCY FIX: Force creation of SEO Progress and Competitor Benchmark charts
		function forceCreateMissingCharts() {
			console.log("EMERGENCY: Force-creating missing charts");
			
			// SEO Progress Chart - Create with fixed dimensions
			const seoProgressContainer = $('#seo-progress-chart').parent();
			if (seoProgressContainer.length) {
				// Remove any existing canvas and create a fresh one
				$('#seo-progress-chart').remove();
				const newCanvas = $('<canvas id="seo-progress-chart" width="400" height="250" style="display:block; width:100%; height:250px;"></canvas>');
				seoProgressContainer.append(newCanvas);
				
				// Remove any loading indicators
				seoProgressContainer.find('.easyai-visualization-loading').remove();
				
				// Create the chart with sample data
				const ctx = document.getElementById('seo-progress-chart').getContext('2d');
				if (window.seoProgressChart) {
					window.seoProgressChart.destroy();
				}
				
				window.seoProgressChart = new Chart(ctx, {
					type: 'line',
					data: {
						labels: ['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Current'],
						datasets: [{
							label: 'SEO Score',
							data: [45, 55, 62, 68, 75],
							backgroundColor: 'rgba(34, 113, 177, 0.2)',
							borderColor: 'rgba(34, 113, 177, 1)',
							borderWidth: 2,
							pointBackgroundColor: 'rgba(34, 113, 177, 1)',
							pointBorderColor: '#fff',
							pointRadius: 5,
							tension: 0.1
						}]
					},
					options: {
						responsive: true,
						maintainAspectRatio: false,
						scales: {
							y: {
								beginAtZero: true,
								max: 100,
								title: {
									display: true,
									text: 'SEO Score'
								}
							},
							x: {
								title: {
									display: true,
									text: 'Time Period'
								}
							}
						}
					}
				});
				console.log("SEO Progress chart created:", window.seoProgressChart);
			}
			
			// Competitor Benchmark Chart - Create with fixed dimensions
			const competitorContainer = $('#competitor-benchmark-chart').parent();
			if (competitorContainer.length) {
				// Remove any existing canvas and create a fresh one
				$('#competitor-benchmark-chart').remove();
				const newCanvas = $('<canvas id="competitor-benchmark-chart" width="400" height="250" style="display:block; width:100%; height:250px;"></canvas>');
				competitorContainer.append(newCanvas);
				
				// Remove any loading indicators
				competitorContainer.find('.easyai-visualization-loading').remove();
				
				// Create the chart with sample data
				const ctx = document.getElementById('competitor-benchmark-chart').getContext('2d');
				if (window.competitorBenchmarkChart) {
					window.competitorBenchmarkChart.destroy();
				}
				
				window.competitorBenchmarkChart = new Chart(ctx, {
					type: 'radar',
					data: {
						labels: ['Word Count', 'Keyword Density', 'Readability', 'Link Count', 'Overall SEO'],
						datasets: [
							{
								label: 'Your Content',
								data: [70, 85, 75, 60, 70],
								backgroundColor: 'rgba(34, 113, 177, 0.2)',
								borderColor: 'rgba(34, 113, 177, 1)',
								borderWidth: 2,
								pointBackgroundColor: 'rgba(34, 113, 177, 1)',
								pointBorderColor: '#fff'
							},
							{
								label: 'Competitor 1',
								data: [90, 65, 80, 75, 85],
								backgroundColor: 'rgba(255, 99, 132, 0.2)',
								borderColor: 'rgba(255, 99, 132, 1)',
								borderWidth: 2,
								pointBackgroundColor: 'rgba(255, 99, 132, 1)',
								pointBorderColor: '#fff'
							},
							{
								label: 'Competitor 2',
								data: [85, 70, 65, 90, 75],
								backgroundColor: 'rgba(75, 192, 192, 0.2)',
								borderColor: 'rgba(75, 192, 192, 1)',
								borderWidth: 2,
								pointBackgroundColor: 'rgba(75, 192, 192, 1)',
								pointBorderColor: '#fff'
							}
						]
					},
					options: {
						responsive: true,
						maintainAspectRatio: false,
						scales: {
							r: {
								angleLines: {
									display: true
								},
								suggestedMin: 0,
								suggestedMax: 100
							}
						}
					}
				});
				console.log("Competitor Benchmark chart created:", window.competitorBenchmarkChart);
			}
		}
		
		// Call our emergency fix after a short delay
		setTimeout(forceCreateMissingCharts, 2000);
		
		// Also attach to analyze button click
		$(document).on('click', '#easyai-analyze-button, #easyai-analyze-content', function() {
			// Wait for the existing code to run and then force create our charts
			setTimeout(forceCreateMissingCharts, 2000);
		});
	});
	</script>
	<?php
}
add_action( 'admin_footer-post.php', 'easyaibloggen_add_seo_visualizations' );
add_action( 'admin_footer-post-new.php', 'easyaibloggen_add_seo_visualizations' );

/**
 * Force direct inclusion of visualization scripts.
 */
function easyaibloggen_force_include_visualizations() {
	// Only run on post edit screen.
	$screen = get_current_screen();
	if ( ! $screen || 'post' !== $screen->base ) {
		return;
	}

	// Directly load Chart.js from local plugin directory (WordPress.org requires local loading).
	wp_enqueue_script(
		'chartjs',
		plugin_dir_url( __FILE__ ) . 'lib/chart.min.js',
		array( 'jquery' ),
		'3.9.1',
		true
	);

	// Ensure visualization CSS is loaded.
	wp_enqueue_style(
		'easyai-seo-visualizations-direct',
		plugin_dir_url( __FILE__ ) . 'css/easyaibloggen-seo-visualizations.css',
		array(),
		time() // Use current time as version to prevent caching.
	);

	// Directly load our visualization script with high priority.
	wp_enqueue_script(
		'easyai-seo-visualizations-direct',
		plugin_dir_url( __FILE__ ) . 'js/easyaibloggen-seo-visualizations.js',
		array( 'jquery', 'chartjs' ),
		time(), // Use current time as version to prevent caching.
		true
	);
}
add_action( 'admin_enqueue_scripts', 'easyaibloggen_force_include_visualizations', 999 ); // Higher priority.
