<template>
	<section class="simplestats-chart-card">
		<header class="simplestats-chart-card__header">
			<h3 class="simplestats-chart-card__title">{{ text_title }}</h3>
			<div class="simplestats-chart-card__tabs" role="tablist">
				<button
					v-for="t in tabs"
					:key="t.key"
					type="button"
					role="tab"
					:aria-selected="activeTab === t.key"
					:class="['simplestats-chart-card__tab', { 'is-active': activeTab === t.key }]"
					@click="activeTab = t.key"
				>
					{{ t.label }}
				</button>
			</div>
		</header>

		<div v-if="hasData" class="simplestats-chart-card__body">
			<apex-chart type="area" height="320" :options="options" :series="series" />
		</div>
		<div v-else class="simplestats-chart-card__empty">{{ text_no_data }}</div>
	</section>
</template>

<script setup>
	import { computed, ref } from 'vue';
	import { useStore } from '@/dashboard/store.js';

	const store     = useStore();
	const activeTab = ref( 'visitors' );

	const text_title    = wp.i18n.__( 'Analytics Overview', 'simplestats-friendly-website-analytics' );
	const text_visitors = wp.i18n.__( 'Visitors',  'simplestats-friendly-website-analytics' );
	const text_pages    = wp.i18n.__( 'Pageviews', 'simplestats-friendly-website-analytics' );
	const text_no_data  = wp.i18n.__( 'No activity in this range.', 'simplestats-friendly-website-analytics' );

	const tabs = [
		{ key: 'visitors',  label: text_visitors },
		{ key: 'pageviews', label: text_pages    },
	];

	const data    = computed( () => store.chartSeries( activeTab.value ) );
	const hasData = computed( () => data.value.some( ( p ) => Number( p.value ) > 0 ) );

	const series  = computed( () => [ {
		name: activeTab.value === 'visitors' ? text_visitors : text_pages,
		data: data.value.map( ( p ) => p.value ),
	} ] );

	function formatDate( iso ) {
		const d  = new Date( `${ iso }T00:00:00` );
		const dd = d.getDate();
		const suffix = ( () => {
			const j = dd % 10, k = dd % 100;
			if ( j === 1 && k !== 11 ) return 'st';
			if ( j === 2 && k !== 12 ) return 'nd';
			if ( j === 3 && k !== 13 ) return 'rd';
			return 'th';
		} )();
		const m  = d.toLocaleDateString( undefined, { month: 'long' } );
		const yy = String( d.getFullYear() ).slice( -2 );
		return `${ dd }${ suffix } ${ m } ${ yy }`;
	}

	// ApexCharts injects an accessibility `<title>` ("area chart with N data series")
	// inside the root SVG. Browsers surface it as a hover tooltip — strip it.
	function stripApexSvgTitle( chartContext ) {
		const svg = chartContext?.el?.querySelector( 'svg' );
		if ( ! svg ) return;
		svg.querySelectorAll( ':scope > title' ).forEach( ( el ) => el.remove() );
	}

	const options = computed( () => ( {
		// Disable zoom + toolbar per request.
		chart: {
			toolbar: { show: false },
			zoom:    { enabled: false },
			animations: { enabled: false },
			fontFamily: 'inherit',
			events: {
				mounted: stripApexSvgTitle,
				updated: stripApexSvgTitle,
			},
		},
		stroke: { curve: 'smooth', width: 2.5, colors: [ '#FACC15' ] },   // brand/400
		fill:   {
			type: 'gradient',
			gradient: {
				shadeIntensity: 1,
				type: 'vertical',
				colorStops: [
					{ offset: 0,   color: '#FACC15', opacity: 0.45 },
					{ offset: 100, color: '#FACC15', opacity: 0    },
				],
			},
		},
		colors: [ '#FACC15' ],                      // brand/400
		dataLabels: { enabled: false },
		grid: {
			borderColor: '#D0CEBC',                 // Light Stroke colour
			strokeDashArray: 0,
			xaxis: { lines: { show: false } },
			yaxis: { lines: { show: true } },
			padding: { top: 0, right: 0, bottom: 0, left: 0 },
		},
		markers: {
			size:        0,
			strokeWidth: 0,
			hover: {
				size: 6,
				sizeOffset: 0,
			},
			colors:      [ '#FACC15' ],             // brand/400
			strokeColors:[ 'rgba(250, 204, 21, 0.25)' ],
		},
		xaxis: {
			categories: data.value.map( ( p, i ) => data.value.length <= 7
				? wp.i18n.sprintf( wp.i18n.__( 'DAY %d', 'simplestats-friendly-website-analytics' ), i + 1 )
				: new Date( `${ p.date }T00:00:00` ).toLocaleDateString( undefined, { month: 'short', day: 'numeric' } )
			),
			labels: {
				style: { colors: '#7A7660', fontSize: '14px', fontWeight: 400 },   // neutral/500
				offsetY: 4,
			},
			axisBorder: { show: false },
			axisTicks:  { show: false },
			tooltip:    { enabled: false },
			crosshairs: {
				show: true,
				stroke: { color: '#FACC15', width: 1, dashArray: 0 },               // brand/400
			},
		},
		yaxis: {
			labels: {
				style: { colors: '#7A7660', fontSize: '14px', fontWeight: 400 },   // neutral/500
				formatter: ( v ) => Math.round( v ),
			},
		},
		tooltip: {
			enabled: true,
			fixed: { enabled: false },
			marker: { show: false },
			custom: ( { dataPointIndex } ) => {
				const point = data.value[ dataPointIndex ];
				if ( ! point ) return '';
				const label = activeTab.value === 'visitors' ? text_visitors : text_pages;
				const date  = formatDate( point.date );

				// Best-effort delta (server-side gives KPI-level deltas only; tooltip
				// shows day-over-day vs the previous point in the series).
				const prev    = data.value[ dataPointIndex - 1 ];
				let deltaHtml = '';
				if ( prev ) {
					const cur = Number( point.value ) || 0;
					const p   = Number( prev.value )  || 0;
					if ( p === 0 && cur > 0 ) {
						deltaHtml = renderDelta( 100, 'up' );
					} else if ( p > 0 ) {
						const pct = Math.round( ( ( cur - p ) / p ) * 1000 ) / 10;
						deltaHtml = renderDelta( pct, pct >= 0 ? 'up' : 'down' );
					}
				}

				return `<div class="simplestats-chart-tooltip">
					<div class="simplestats-chart-tooltip__row">
						<div class="simplestats-chart-tooltip__text">
							<div class="simplestats-chart-tooltip__label">${ escapeHtml( label ) }</div>
							<div class="simplestats-chart-tooltip__value">${ formatNumber( point.value ) }</div>
						</div>
						${ deltaHtml }
					</div>
					<div class="simplestats-chart-tooltip__date">${ escapeHtml( date ) }</div>
					<span class="simplestats-chart-tooltip__arrow"></span>
				</div>`;
			},
		},
	} ) );

	function renderDelta( pct, dir ) {
		const sign = pct > 0 ? '+' : ( pct < 0 ? '-' : '' );
		const abs  = Math.abs( pct );
		const num  = Number.isInteger( abs ) ? String( abs ) : abs.toFixed( 1 );
		return `<span class="simplestats-chart-tooltip__delta simplestats-chart-tooltip__delta--${ dir }">${ sign }${ num }%</span>`;
	}

	function formatNumber( v ) {
		return new Intl.NumberFormat().format( Number( v ) || 0 );
	}

	function escapeHtml( s ) {
		return String( s ).replace( /[&<>"']/g, ( c ) => ( {
			'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
		}[ c ] ) );
	}
</script>
