/**
 * Dashboard Charts
 *
 * Renders interactive charts for the usage statistics dashboard
 * using Chart.js. Includes daily activity, weekly comparison,
 * and tool usage distribution charts.
 *
 * @file
 * @since 1.0.0
 * @package AgenticWP
 * @namespace AgenticWPAdmin.dashboardCharts
 */

(function($) {
	'use strict';

	const AgenticWPAdmin = window.AgenticWPAdmin = window.AgenticWPAdmin || {};

	const charts = { daily: null, weekly: null, distribution: null };
	let currentPeriod = '7d';
	let chartsInitialized = false;
	let chartObserver = null;

	// Chart color palette matching design system.
	const colors = {
		primary: 'rgb(99, 102, 241)',
		primaryLight: 'rgba(99, 102, 241, 0.1)',
		secondary: 'rgb(16, 185, 129)',
		tertiary: 'rgb(245, 158, 11)',
		quaternary: 'rgb(239, 68, 68)',
		text: 'rgb(107, 114, 128)',
		grid: 'rgba(107, 114, 128, 0.1)',
		background: 'rgb(255, 255, 255)'
	};

	// Common scale configurations.
	const commonScales = {
		x: { grid: { display: false } },
		y: { beginAtZero: true, grid: { color: colors.grid }, ticks: { precision: 0 } }
	};

	const getAdminData = () => window.agenticwpDashboard || {};

	/**
	 * Makes an AJAX request with common error handling.
	 */
	function ajax(action, data, onSuccess, $btn) {
		const adminData = getAdminData();
		if ($btn) $btn.prop('disabled', true);

		$.ajax({
			url: adminData.ajaxUrl || window.ajaxurl,
			type: 'POST',
			data: { action, ...data },
			success: onSuccess,
			complete: () => $btn && $btn.prop('disabled', false)
		});
	}

	/**
	 * Initializes dashboard charts with lazy loading.
	 */
	function init() {
		const $container = $('#agenticwp-daily-chart').closest('.agenticwp-activity-section');
		if (!$container.length || typeof Chart === 'undefined') {
			return;
		}

		setChartDefaults();
		bindEvents();

		if ('IntersectionObserver' in window) {
			chartObserver = new IntersectionObserver((entries) => {
				if (entries[0].isIntersecting && !chartsInitialized) {
					chartsInitialized = true;
					renderCharts();
					chartObserver.disconnect();
					chartObserver = null;
				}
			}, { rootMargin: '100px', threshold: 0.1 });
			chartObserver.observe($container[0]);
		} else {
			renderCharts();
		}
	}

	function setChartDefaults() {
		Object.assign(Chart.defaults, {
			responsive: true,
			maintainAspectRatio: false,
			animation: false
		});
		Object.assign(Chart.defaults.font, {
			family: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
			size: 12
		});
		Chart.defaults.color = colors.text;
		Object.assign(Chart.defaults.plugins.legend, { display: false });
		Object.assign(Chart.defaults.plugins.tooltip, {
			backgroundColor: 'rgba(17, 24, 39, 0.9)',
			padding: 12,
			cornerRadius: 8,
			titleFont: { weight: '600' }
		});
		Chart.defaults.transitions.active.animation.duration = 0;
	}

	function bindEvents() {
		$(document).on('click', '.agenticwp-chart-toggle button', function(e) {
			e.preventDefault();
			const $btn = $(this), period = $btn.data('period');
			if (period === currentPeriod) return;

			$btn.siblings().removeClass('active');
			$btn.addClass('active');
			currentPeriod = period;
			fetchChartData(period);
		});
	}

	function renderCharts() {
		const data = getAdminData();
		renderDailyChart(data.daily || {});
		renderWeeklyChart(data.weekly || {});
		renderDistributionChart(data.lifetime || {});
	}

	function fetchChartData(period) {
		const adminData = getAdminData();
		ajax('agenticwp_get_chart_data', { nonce: adminData.chartNonce, period }, (response) => {
			if (response?.success) updateCharts(response.data, period);
		});
	}

	function updateCharts(data, period) {
		const showWeekly = period === '12w';
		if (showWeekly) {
			renderWeeklyChart(data.weekly || {});
		} else {
			renderDailyChart(data.daily || {});
		}
		$('#agenticwp-daily-chart').closest('.agenticwp-chart-container').toggle(!showWeekly);
		$('#agenticwp-weekly-chart').closest('.agenticwp-chart-container').toggle(showWeekly);
	}

	/**
	 * Creates a chart, destroying any existing instance first.
	 */
	function createChart(chartKey, canvasId, config) {
		const canvas = document.getElementById(canvasId);
		if (!canvas) return;

		if (charts[chartKey]) charts[chartKey].destroy();
		charts[chartKey] = new Chart(canvas.getContext('2d'), config);
	}

	function renderDailyChart(dailyData) {
		const days = currentPeriod === '30d' ? 30 : 7;
		const { labels, toolCalls, posts } = prepareDailyData(dailyData, days);

		const pointStyle = (color) => ({
			pointRadius: 4,
			pointHoverRadius: 6,
			pointBackgroundColor: colors.background,
			pointBorderColor: color,
			pointBorderWidth: 2
		});

		createChart('daily', 'agenticwp-daily-chart', {
			type: 'line',
			data: {
				labels,
				datasets: [
					{
						label: 'Tasks Completed',
						data: toolCalls,
						borderColor: colors.primary,
						backgroundColor: colors.primaryLight,
						fill: true,
						tension: 0.4,
						...pointStyle(colors.primary)
					},
					{
						label: 'Drafts Created',
						data: posts,
						borderColor: colors.secondary,
						backgroundColor: 'transparent',
						tension: 0.4,
						...pointStyle(colors.secondary)
					}
				]
			},
			options: {
				interaction: { mode: 'index', intersect: false },
				plugins: {
					legend: { display: true, position: 'top', align: 'end', labels: { usePointStyle: true, pointStyle: 'circle', boxWidth: 8 } },
					tooltip: { callbacks: { label: (ctx) => `${ctx.dataset.label}: ${ctx.parsed.y.toLocaleString()}` } }
				},
				scales: { ...commonScales, x: { ...commonScales.x, ticks: { maxRotation: 0 } } }
			}
		});
	}

	function prepareDailyData(dailyData, days) {
		const labels = [], toolCalls = [], posts = [];
		const today = new Date();

		for (let i = days - 1; i >= 0; i--) {
			const date = new Date(today);
			date.setDate(today.getDate() - i);

			const key = date.toISOString().slice(0, 10);
			const opts = days <= 7 ? { weekday: 'short' } : { month: 'short', day: 'numeric' };
			labels.push(date.toLocaleDateString('en-US', opts));

			const stats = dailyData[key] || {};
			toolCalls.push(stats.tool_calls || 0);
			posts.push(stats.posts_created || 0);
		}
		return { labels, toolCalls, posts };
	}

	function renderWeeklyChart(weeklyData) {
		const { labels, toolCalls, posts } = prepareWeeklyData(weeklyData, 12);
		const barDataset = (label, data, color) => ({
			label, data, backgroundColor: color, borderRadius: 4, barPercentage: 0.7
		});

		createChart('weekly', 'agenticwp-weekly-chart', {
			type: 'bar',
			data: {
				labels,
				datasets: [
					barDataset('Tasks Completed', toolCalls, colors.primary),
					barDataset('Drafts Created', posts, colors.secondary)
				]
			},
			options: {
				plugins: {
					legend: { display: true, position: 'top', align: 'end', labels: { usePointStyle: true, pointStyle: 'rect', boxWidth: 12 } }
				},
				scales: commonScales
			}
		});
	}

	function prepareWeeklyData(weeklyData, weeks) {
		const labels = [], toolCalls = [], posts = [];
		const today = new Date();

		for (let i = weeks - 1; i >= 0; i--) {
			const date = new Date(today);
			date.setDate(today.getDate() - i * 7);

			const weekNum = getWeekNumber(date);
			const key = `${date.getFullYear()}-${String(weekNum).padStart(2, '0')}`;
			labels.push(`W${weekNum}`);

			const stats = weeklyData[key] || {};
			toolCalls.push(stats.tool_calls || 0);
			posts.push(stats.posts_created || 0);
		}
		return { labels, toolCalls, posts };
	}

	function getWeekNumber(date) {
		const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
		d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
		const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
		return Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
	}

	function renderDistributionChart(lifetimeData) {
		const canvas = document.getElementById('agenticwp-distribution-chart');
		if (!canvas) return;

		const data = prepareDistributionData(lifetimeData);
		if (data.values.every(v => v === 0)) {
			$(canvas).closest('.agenticwp-chart-container').addClass('agenticwp-chart-empty');
			return;
		}

		createChart('distribution', 'agenticwp-distribution-chart', {
			type: 'bar',
			data: {
				labels: data.labels,
				datasets: [{ data: data.values, backgroundColor: data.colors, borderRadius: 4, barPercentage: 0.7 }]
			},
			options: {
				indexAxis: 'y',
				plugins: {
					legend: { display: false },
					tooltip: { callbacks: { label: (ctx) => ctx.parsed.x.toLocaleString() } }
				},
				scales: { x: commonScales.y, y: { grid: { display: false } } }
			}
		});
	}

	function prepareDistributionData(data) {
		return {
			labels: ['Content Creation', 'Content Editing', 'SEO & Meta', 'Search'],
			values: [
				data.posts_created || 0,
				data.posts_edited || 0,
				data.meta_descriptions || 0,
				data.content_searches || 0
			],
			colors: [colors.primary, colors.secondary, colors.tertiary, colors.quaternary]
		};
	}

	function destroy() {
		if (chartObserver) {
			chartObserver.disconnect();
			chartObserver = null;
		}
		Object.keys(charts).forEach((key) => {
			if (charts[key]) {
				charts[key].destroy();
				charts[key] = null;
			}
		});
		chartsInitialized = false;
	}

	AgenticWPAdmin.dashboardCharts = { init, destroy, refresh: renderCharts };
	$(document).ready(() => AgenticWPAdmin.dashboardCharts.init());

})(jQuery);
