(function ($) {
	'use strict';

	$(function () {
		// Só executa se os elementos do gráfico existirem na página
		var $pieChart = $('#wpcm-pie-chart-canvas');
		var $lineChart = $('#wpcm-line-chart-canvas');

		if (!$pieChart.length && !$lineChart.length) {
			return;
		}

		// Pega o ID do site do filtro (se houver)
		var $filter = $('select[name="filter_site_id"]');
		var filter_site_id = $filter.length ? $filter.val() : 0;

		// Busca os dados do nosso novo endpoint AJAX
		$.ajax({
			url: wpcm_hub_dashboard.ajax_url,
			type: 'GET',
			data: {
				action: 'wpcm_hub_get_chart_data',
				_ajax_nonce: wpcm_hub_dashboard.nonce,
				filter_site_id: filter_site_id,
			},
			success: function (response) {
				if (response.success) {
					// Remove os spinners
					$('#wpcm-pie-chart-loading').hide();
					$('#wpcm-line-chart-loading').hide();
					
					// Renderiza os gráficos
					if ($pieChart.length) {
						renderPieChart(response.data.pie_chart);
					}
					if ($lineChart.length) {
						renderLineChart(response.data.line_chart);
					}
				} else {
					// Mostra um erro se o AJAX falhar
					$('#wpcm-pie-chart-loading').text('Error loading chart data.');
					$('#wpcm-line-chart-loading').text('Error loading chart data.');
				}
			},
		});

		/**
		 * Renderiza o Gráfico de Pizza (Donut)
		 */
		function renderPieChart(data) {
			var ctx = $pieChart[0].getContext('2d');
			new Chart(ctx, {
				type: 'doughnut',
				data: {
					labels: data.labels, // Ex: ['Accepted All', 'Rejected', 'Partial']
					datasets: [
						{
							data: data.data, // Ex: [100, 50, 20]
							backgroundColor: [
								'#10b981', // green
								'#ef4444', // red
								'#f59e0b', // amber
								'#3b82f6', // blue
							],
							borderWidth: 0,
						},
					],
				},
				options: {
					responsive: true,
					maintainAspectRatio: false,
					plugins: {
						legend: {
							position: 'bottom',
						},
					},
					cutout: '70%',
				},
			});
		}

		/**
		 * Renderiza o Gráfico de Linha
		 */
		function renderLineChart(data) {
			var ctx = $lineChart[0].getContext('2d');
			new Chart(ctx, {
				type: 'line',
				data: {
					labels: data.labels, // Ex: ['Nov 1', 'Nov 2', 'Nov 3']
					datasets: [
						{
							label: 'Total Interactions',
							data: data.data, // Ex: [5, 10, 8]
							backgroundColor: 'rgba(52, 152, 219, 0.1)',
							borderColor: '#3498db',
							fill: true,
							tension: 0.3,
							pointBackgroundColor: '#3498db',
						},
					],
				},
				options: {
					responsive: true,
					maintainAspectRatio: false,
					scales: {
						y: {
							beginAtZero: true,
							ticks: {
								precision: 0, // Garante que a escala Y seja de números inteiros
							}
						},
					},
					plugins: {
						legend: {
							display: false,
						},
					},
				},
			});
		}
	});
})(jQuery);