/* global Chart */
( function () {
	'use strict';

	/**
	 * This chart intentionally still runs on Chart.js (bundled locally in
	 * admin/js/vendor) rather than WooCommerce Analytics' own @woocommerce/
	 * components <Chart> (which is D3/React-based and only available when
	 * WooCommerce's Analytics report screens are active). What's copied
	 * here is the *visual language* of the WooCommerce Analytics charts -
	 * straight (unsmoothed) lines, a soft area fill, hidden points that
	 * only appear on hover with a white ring, dashed horizontal gridlines
	 * only, a shared vertical crosshair on hover, and a light "card" style
	 * tooltip with circular series swatches - reimplemented with Chart.js's
	 * own config/plugin API so the page keeps working standalone even when
	 * WooCommerce Analytics isn't installed/enabled.
	 */

	document.addEventListener( 'DOMContentLoaded', function () {
		var dataEl = document.getElementById( 'nudgesells-revenue-chart-data' );
		var canvas = document.getElementById( 'nudgesells-revenue-chart' );

		if ( ! dataEl || ! canvas || typeof Chart === 'undefined' ) {
			return;
		}

		var data;
		try {
			data = JSON.parse( dataEl.textContent );
		} catch ( e ) {
			return;
		}

		var rootStyles   = getComputedStyle( document.documentElement );
		var accent       = ( rootStyles.getPropertyValue( '--ns-accent' ).trim() ) || '#1E5F46';
		var secondary    = '#2563eb';
		var gridColor    = ( rootStyles.getPropertyValue( '--ns-border' ).trim() ) || '#e2e2e6';
		var mutedColor   = ( rootStyles.getPropertyValue( '--ns-text-muted' ).trim() ) || '#646970';
		var textColor    = ( rootStyles.getPropertyValue( '--ns-text' ).trim() ) || '#1d2327';
		var surfaceColor = ( rootStyles.getPropertyValue( '--ns-surface' ).trim() ) || '#fff';
		var adminFontStack = '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';

		/**
		 * Convert a `#rrggbb` color to an `rgba()` string at the given alpha,
		 * used for the soft area fill under each line (WC Analytics' charts
		 * fill the area under the primary series at low opacity rather than
		 * leaving it blank).
		 */
		function withAlpha( hex, alpha ) {
			var parsed = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec( hex );
			if ( ! parsed ) {
				return hex;
			}
			var r = parseInt( parsed[ 1 ], 16 );
			var g = parseInt( parsed[ 2 ], 16 );
			var b = parseInt( parsed[ 3 ], 16 );
			return 'rgba(' + r + ', ' + g + ', ' + b + ', ' + alpha + ')';
		}

		var legendMarginPlugin = {
			id: 'legendMargin',
			beforeInit: function ( chart ) {
				var originalFit = chart.legend.fit;
				chart.legend.fit = function () {
					originalFit.bind( chart.legend )();
					this.height += 20;
				};
			}
		};

		var crosshairPlugin = {
			id: 'nudgesellsCrosshair',
			afterDraw: function ( chart ) {
				var active = chart.tooltip && chart.tooltip._active;
				if ( ! active || ! active.length ) {
					return;
				}
				var ctx = chart.ctx;
				var x = active[ 0 ].element.x;
				var area = chart.chartArea;
				ctx.save();
				ctx.beginPath();
				ctx.moveTo( x, area.top );
				ctx.lineTo( x, area.bottom );
				ctx.lineWidth = 1;
				ctx.strokeStyle = gridColor;
				ctx.setLineDash( [ 3, 3 ] );
				ctx.stroke();
				ctx.restore();
			}
		};

		function seriesConfig( label, series, color ) {
			return {
				label: label,
				data: series,
				borderColor: color,
				backgroundColor: withAlpha( color, 0.08 ),
				fill: 'origin',
				tension: 0, // WC Analytics charts connect points with straight segments, not curves.
				pointRadius: 0, // Points stay hidden until hovered, matching WC Analytics' minimal line style.
				pointHitRadius: 8,
				pointHoverRadius: 5,
				pointHoverBackgroundColor: color,
				pointHoverBorderColor: surfaceColor,
				pointHoverBorderWidth: 2,
				borderWidth: 2
			};
		}

		var datasets = [ seriesConfig( data.addonLabel, data.addonSeries, accent ) ];
		if ( data.upgradeSeries ) {
			datasets.push( seriesConfig( data.upgradeLabel, data.upgradeSeries, secondary ) );
		}

		new Chart( canvas.getContext( '2d' ), {
			type: 'line',
			data: {
				labels: data.labels,
				datasets: datasets
			},
			plugins: [ legendMarginPlugin, crosshairPlugin ],
			options: {
				responsive: true,
				maintainAspectRatio: false,
				interaction: { mode: 'index', intersect: false },
				font: { family: adminFontStack },
				plugins: {
					legend: {
						position: 'top',
						align: 'start',
						labels: {
							boxWidth: 8,
							boxHeight: 8,
							usePointStyle: true,
							pointStyle: 'circle',
							font: { family: adminFontStack, size: 13, weight: '600' },
							color: textColor,
							padding: 16
						}
					},
					tooltip: {
						// Light "card" tooltip instead of Chart.js's default
						// dark bubble, with circular swatches -- closer to
						// the tooltip WC Analytics' own charts render.
						backgroundColor: surfaceColor,
						titleColor: textColor,
						bodyColor: textColor,
						borderColor: gridColor,
						borderWidth: 1,
						cornerRadius: 6,
						padding: 10,
						boxPadding: 4,
						usePointStyle: true,
						titleFont: { family: adminFontStack, size: 12, weight: '600' },
						bodyFont: { family: adminFontStack, size: 12 },
						callbacks: {
							label: function ( context ) {
								var value = context.parsed.y;
								return context.dataset.label + ': ' + data.currencySymbol + value.toFixed( 2 );
							}
						}
					}
				},
				scales: {
					y: {
						beginAtZero: true,
						border: { display: false },
						ticks: {
							maxTicksLimit: 5,
							font: { family: adminFontStack, size: 11 },
							color: mutedColor,
							callback: function ( value ) {
								return data.currencySymbol + value;
							}
						},
						// Dashed, horizontal-only gridlines -- WC Analytics
						// charts never draw vertical gridlines.
						grid: { color: gridColor, borderDash: [ 4, 4 ], drawTicks: false }
					},
					x: {
						border: { display: false },
						grid: { display: false },
						ticks: {
							font: { family: adminFontStack, size: 11 },
							color: mutedColor,
							maxRotation: 0,
							autoSkip: true
						}
					}
				}
			}
		} );
	} );
} )();
