/**
 * TrustLens Command Center charts.
 *
 * Renders the Trust Trend visuals as Chart.js line charts (replacing the old
 * inline-SVG sparklines), themed via the shared TrustLensChartTheme so they
 * read as one product. Each <canvas.tlcc-chart> carries its series in a
 * data-tlcc-trend attribute and a data-tlcc-mode of "full" or "spark".
 *
 * The line colours itself to the store's current health segment, the tooltip
 * shows the day-over-day delta, the full chart draws a hover crosshair, each
 * canvas gets an accessible label, and animation is suppressed for users who
 * prefer reduced motion.
 *
 * @package TrustLens
 * @since   1.2.7
 */

/* global Chart, TrustLensChartTheme */

(function () {
	'use strict';

	if (typeof Chart === 'undefined' || typeof TrustLensChartTheme === 'undefined') {
		return;
	}

	var COLORS  = TrustLensChartTheme.COLORS;
	var REDUCED = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;

	/**
	 * The Command Center accent (var --tlcc-blue), used when the health segment
	 * is "normal" or unknown. Falls back to the literal token.
	 */
	function accentColor() {
		var root = document.querySelector('.tlcc');
		if (root) {
			var v = getComputedStyle(root).getPropertyValue('--tlcc-blue');
			if (v && v.trim()) {
				return v.trim();
			}
		}
		return '#3377EE';
	}

	/**
	 * Map the store's health segment to a line colour so the trend reads at a
	 * glance and matches the gauge: red = at-risk, amber = caution, green =
	 * trusted, blue = normal.
	 */
	function segmentColor(segment) {
		switch (segment) {
			case 'critical':
			case 'risk':
				return COLORS.risk;
			case 'caution':
				return COLORS.warn;
			case 'trusted':
			case 'vip':
				return COLORS.emerald;
			default:
				return accentColor();
		}
	}

	/**
	 * "2026-06-19" → "Jun 19". Leaves non-date labels untouched.
	 */
	function shortDate(label) {
		if (typeof label !== 'string' || !/^\d{4}-\d{2}-\d{2}/.test(label)) {
			return label || '';
		}
		var parts = label.slice(0, 10).split('-');
		var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
		var m = parseInt(parts[1], 10) - 1;
		return (months[m] || parts[1]) + ' ' + parseInt(parts[2], 10);
	}

	// Subtle vertical guide line under the hovered point (full chart only).
	var crosshairPlugin = {
		id: 'tlccCrosshair',
		afterDraw: function (chart) {
			var active = chart.tooltip && typeof chart.tooltip.getActiveElements === 'function'
				? chart.tooltip.getActiveElements()
				: [];
			if (!active.length || !chart.chartArea) {
				return;
			}
			var x   = active[0].element.x;
			var ctx = chart.ctx;
			ctx.save();
			ctx.beginPath();
			ctx.moveTo(x, chart.chartArea.top);
			ctx.lineTo(x, chart.chartArea.bottom);
			ctx.lineWidth   = 1;
			ctx.strokeStyle = 'rgba(15, 23, 42, 0.16)';
			ctx.stroke();
			ctx.restore();
		}
	};

	function render(canvas) {
		var payload;
		try {
			payload = JSON.parse(canvas.getAttribute('data-tlcc-trend') || '{}');
		} catch (e) {
			return;
		}

		var values = Array.isArray(payload.values) ? payload.values : [];
		var labels = Array.isArray(payload.labels) ? payload.labels : [];
		if (values.length < 2) {
			return;
		}

		TrustLensChartTheme.applyDefaults();

		var isSpark = canvas.getAttribute('data-tlcc-mode') === 'spark';
		var color   = segmentColor(payload.segment);
		var ctx     = canvas.getContext('2d');
		var lastIdx = values.length - 1;

		// Accessible summary — canvases are opaque to assistive tech otherwise.
		var current = (typeof payload.score === 'number') ? payload.score : Math.round(values[lastIdx]);
		var dir     = values[lastIdx] > values[0] ? 'trending up'
			: (values[lastIdx] < values[0] ? 'trending down' : 'flat');
		canvas.setAttribute('role', 'img');
		canvas.setAttribute('aria-label',
			'Trust score trend over ' + values.length + ' points. Current average ' + current + ' of 100, ' + dir + '.');

		var dataset = TrustLensChartTheme.lineDataset({
			label:    'Trust score',
			data:     values,
			color:    color,
			ctx:      ctx,
			fill:     true,
			topAlpha: isSpark ? 0.16 : 0.20
		});
		// Re-create the old end-point dot — only the latest point shows a marker.
		dataset.pointRadius = values.map(function (_, i) { return i === lastIdx ? 3 : 0; });
		dataset.pointBackgroundColor = color;
		dataset.pointBorderColor = '#fff';
		dataset.pointBorderWidth = 1.5;

		var options = {
			responsive: true,
			maintainAspectRatio: false,
			layout: { padding: isSpark ? 2 : 4 },
			interaction: { mode: 'index', intersect: false },
			plugins: {
				legend: { display: false },
				tooltip: {
					enabled: true,
					callbacks: {
						title: function (items) {
							return items.length ? shortDate(items[0].label) : '';
						},
						label: function (item) {
							var i    = item.dataIndex;
							var cur  = Math.round(item.parsed.y);
							var text = 'Trust score: ' + cur;
							if (i > 0) {
								var d = cur - Math.round(values[i - 1]);
								text += d > 0 ? '  (▲ +' + d + ')'
									: (d < 0 ? '  (▼ ' + d + ')' : '  (no change)');
							}
							return text;
						}
					}
				}
			},
			scales: {
				// Minimal by design — the panels are compact, so exact values live
				// in the tooltip rather than crowding axes into 90px.
				x: { display: false },
				y: { display: false, grace: '8%' }
			},
			elements: { line: { tension: 0.35 } }
		};

		if (REDUCED) {
			options.animation = false;
		}

		new Chart(ctx, {
			type: 'line',
			data: {
				labels: labels.length === values.length ? labels : values.map(function (_, i) { return i; }),
				datasets: [dataset]
			},
			options: options,
			// Crosshair only on the larger Trust Trend chart, not the mini spark.
			plugins: isSpark ? [] : [crosshairPlugin]
		});
	}


	/**
	 * Per-card 24h mini strip — hourly counts as a self-scaled bar chart, so
	 * each card's chart fits its own data and never gets flattened by another
	 * card's magnitude. Colour + unit come from data attributes.
	 */
	function renderStrip(canvas) {
		var data;
		try {
			data = JSON.parse(canvas.getAttribute('data-tlcc-strip') || '[]');
		} catch (e) {
			return;
		}
		if (!Array.isArray(data) || data.length < 2) {
			return;
		}

		TrustLensChartTheme.applyDefaults();

		var color = canvas.getAttribute('data-tlcc-color') || accentColor();
		var unit  = canvas.getAttribute('data-tlcc-unit') || '';
		var ctx   = canvas.getContext('2d');
		var ds    = TrustLensChartTheme.barDataset({
			label: unit || 'count', data: data, backgroundColor: color, borderRadius: 3, maxBarThickness: 9
		});

		var options = {
			responsive: true,
			maintainAspectRatio: false,
			layout: { padding: 0 },
			plugins: {
				legend: { display: false },
				tooltip: {
					callbacks: {
						title: function (items) {
							if (!items.length) { return ''; }
							var ago = (data.length - 1) - items[0].dataIndex;
							return ago === 0 ? 'This hour' : ago + 'h ago';
						},
						label: function (item) {
							var n = item.parsed.y;
							return unit ? (n + ' ' + unit) : ('' + n);
						}
					}
				}
			},
			scales: {
				x: { display: false, grid: { display: false } },
				y: { display: false, beginAtZero: true, grace: '12%' }
			}
		};
		if (REDUCED) { options.animation = false; }

		new Chart(ctx, {
			type: 'bar',
			data: { labels: data.map(function (_, i) { return i; }), datasets: [ds] },
			options: options
		});
	}

	/**
	 * Chargeback card 12-month ratio trend: blended dispute ratio (%) as an area
	 * line, with a dashed reference line at the network fine threshold so the
	 * trajectory toward it is obvious.
	 */
	function renderCbTrend(canvas) {
		var payload;
		try {
			payload = JSON.parse(canvas.getAttribute('data-tlcc-cbtrend') || '{}');
		} catch (e) {
			return;
		}
		var labels = Array.isArray(payload.labels) ? payload.labels : [];
		var values = Array.isArray(payload.values) ? payload.values : [];
		var thr    = (typeof payload.threshold === 'number') ? payload.threshold : null;
		if (labels.length < 2) {
			return;
		}

		TrustLensChartTheme.applyDefaults();
		var ctx = canvas.getContext('2d');

		var ds = TrustLensChartTheme.lineDataset({
			label: 'Blended', data: values, color: '#635bff', ctx: ctx, fill: true, topAlpha: 0.18
		});
		ds.borderWidth = 1.75;
		ds.pointRadius = 0;
		ds.pointHoverRadius = 4;

		var datasets = [ds];
		var maxv = Math.max.apply(null, values);
		if (null !== thr && thr > 0) {
			datasets.push({
				label: 'Visa line', data: values.map(function () { return thr; }),
				borderColor: '#b23a48', borderDash: [5, 4], borderWidth: 1.25,
				pointRadius: 0, pointHoverRadius: 0, fill: false, tension: 0
			});
			maxv = Math.max(maxv, thr);
		}

		var options = {
			responsive: true,
			maintainAspectRatio: false,
			interaction: { mode: 'index', intersect: false },
			plugins: {
				legend: { display: false },
				tooltip: {
					callbacks: {
						title: function (items) { return items.length ? items[0].label : ''; },
						label: function (item) { return item.dataset.label + ': ' + item.parsed.y.toFixed(2) + '%'; }
					}
				}
			},
			scales: {
				x: { display: false },
				y: { display: false, beginAtZero: true, suggestedMax: maxv * 1.15 }
			}
		};
		if (REDUCED) { options.animation = false; }

		new Chart(ctx, {
			type: 'line',
			data: { labels: labels, datasets: datasets },
			options: options
		});
	}

	function init() {
		var canvases = document.querySelectorAll('canvas.tlcc-chart[data-tlcc-trend]');
		for (var i = 0; i < canvases.length; i++) {
			render(canvases[i]);
		}
		var strips = document.querySelectorAll('canvas.tlcc-stripchart[data-tlcc-strip]');
		for (var j = 0; j < strips.length; j++) {
			renderStrip(strips[j]);
		}
		var cb = document.querySelectorAll('canvas.tlcc-cbtrend[data-tlcc-cbtrend]');
		for (var k = 0; k < cb.length; k++) {
			renderCbTrend(cb[k]);
		}
	}

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