/**
 * Dashboard monthly revenue chart (Chart.js).
 */
(function () {
	'use strict';

	function init() {
		if (typeof Chart === 'undefined' || typeof easyInvoiceDashboard === 'undefined') {
			return;
		}

		var cfg = easyInvoiceDashboard;
		if (!cfg.hasData || !cfg.monthlyRevenue) {
			return;
		}

		var el = document.getElementById('revenue-chart');
		if (!el) {
			return;
		}

		var monthly = cfg.monthlyRevenue;
		var months = Object.keys(monthly);
		if (!months.length) {
			return;
		}

		var currencySet = {};
		months.forEach(function (m) {
			var row = monthly[m];
			if (!row || typeof row !== 'object') {
				return;
			}
			Object.keys(row).forEach(function (code) {
				currencySet[code] = true;
			});
		});

		var currencies = Object.keys(currencySet);
		if (!currencies.length) {
			return;
		}

		var palette = [
			'rgba(79, 70, 229, 0.85)',
			'rgba(34, 197, 94, 0.85)',
			'rgba(239, 68, 68, 0.85)',
			'rgba(245, 158, 11, 0.85)',
			'rgba(139, 92, 246, 0.85)',
		];

		var datasets = currencies.map(function (currency, idx) {
			return {
				label: currency,
				data: months.map(function (m) {
					var cell = monthly[m] && monthly[m][currency];
					if (!cell || cell.amount === undefined || cell.amount === null) {
						return 0;
					}
					var n = parseFloat(cell.amount);
					return isNaN(n) ? 0 : n;
				}),
				backgroundColor: palette[idx % palette.length],
				borderColor: palette[idx % palette.length].replace('0.85', '1'),
				borderWidth: 1,
			};
		});

		var ctx = el.getContext('2d');
		if (!ctx) {
			return;
		}

		if (window.easyInvoiceDashboardChart) {
			window.easyInvoiceDashboardChart.destroy();
		}

		window.easyInvoiceDashboardChart = new Chart(ctx, {
			type: 'bar',
			data: {
				labels: months,
				datasets: datasets,
			},
			options: {
				responsive: true,
				maintainAspectRatio: false,
				scales: {
					y: {
						beginAtZero: true,
						ticks: {
							precision: 0,
						},
					},
					x: {
						grid: {
							display: false,
						},
					},
				},
				plugins: {
					legend: {
						display: currencies.length > 1,
						position: 'top',
					},
					tooltip: {
						mode: 'index',
						intersect: false,
					},
				},
			},
		});
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', init);
	} else {
		init();
	}
})();
