/**
 * Chart.js bootstrapping for dashboard and statistics admin screens.
 */
(function () {
	'use strict';

	function buildBarChart(el, cfg) {
		if (!window.Chart || !el || !cfg || !cfg.series) {
			return;
		}
		var s = cfg.series || [];
		var labels = cfg.labels || {};
		new window.Chart(el.getContext('2d'), {
			type: 'bar',
			data: {
				labels: s.map(function (r) { return r.d; }),
				datasets: [
					{ label: labels.impressions || 'Impressions', backgroundColor: 'rgba(42,178,229,0.6)', data: s.map(function (r) { return Number(r.impressions || 0); }) },
					{ label: labels.clicks || 'Clicks', backgroundColor: 'rgba(16,185,129,0.6)', data: s.map(function (r) { return Number(r.clicks || 0); }) },
					{ label: labels.opens || 'Opens', backgroundColor: 'rgba(245,158,11,0.6)', data: s.map(function (r) { return Number(r.opens || 0); }) },
					{ label: labels.conversions || 'Conversions', backgroundColor: 'rgba(239,68,68,0.6)', data: s.map(function (r) { return Number(r.conversions || 0); }) }
				]
			},
			options: { responsive: true, maintainAspectRatio: false, scales: { x: { stacked: false }, y: { beginAtZero: true } } }
		});
	}

	function buildLineChart(el, cfg) {
		if (!window.Chart || !el || !cfg || !cfg.series) {
			return;
		}
		var s = cfg.series || [];
		var labels = cfg.labels || {};
		new window.Chart(el.getContext('2d'), {
			type: 'line',
			data: {
				labels: s.map(function (r) { return r.d; }),
				datasets: [
					{ label: labels.impressions || 'Impressions', data: s.map(function (r) { return Number(r.impressions || 0); }), borderColor: '#2AB2E5', backgroundColor: 'rgba(42,178,229,0.1)', tension: 0.35, fill: true },
					{ label: labels.clicks || 'Clicks', data: s.map(function (r) { return Number(r.clicks || 0); }), borderColor: '#10B981', backgroundColor: 'rgba(16,185,129,0.1)', tension: 0.35 },
					{ label: labels.opens || 'Opens', data: s.map(function (r) { return Number(r.opens || 0); }), borderColor: '#F59E0B', backgroundColor: 'rgba(245,158,11,0.1)', tension: 0.35 },
					{ label: labels.conversions || 'Conversions', data: s.map(function (r) { return Number(r.conversions || 0); }), borderColor: '#EF4444', backgroundColor: 'rgba(239,68,68,0.1)', tension: 0.35 }
				]
			},
			options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { labels: { boxWidth: 14, font: { size: 12 } } } }, scales: { x: { grid: { display: false } } } }
		});
	}

	document.addEventListener('DOMContentLoaded', function () {
		var dash = window.SuiteMkt3kDashboard;
		if (dash) {
			buildLineChart(document.getElementById('wmk-chart-overview'), dash);
		}
		var stats = window.SuiteMkt3kStats;
		if (stats) {
			buildBarChart(document.getElementById('wmk-stats-chart'), stats);
		}
	});
})();
