<template>
	<div class="simplestats-date-range" v-click-outside="close">
		<button type="button" class="simplestats-date-range__button" @click="toggle">
			<svg class="simplestats-date-range__button-cal-icon" viewBox="0 0 16 16" width="16" height="16" fill="none" aria-hidden="true">
				<rect x="2" y="3" width="12" height="11" rx="1.5" stroke="currentColor" stroke-width="1.3" />
				<path d="M2 6.5h12M5.5 1.5v3M10.5 1.5v3" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" />
			</svg>
			<span class="simplestats-date-range__button-label-prefix">{{ labelPrefix }}</span>
			<span class="simplestats-date-range__button-label-range">{{ labelRange }}</span>
			<svg class="simplestats-date-range__button-chevron" viewBox="0 0 12 12" width="12" height="12" fill="none" aria-hidden="true">
				<path d="M2 4l4 4 4-4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
			</svg>
		</button>

		<div v-if="open" class="simplestats-date-range__popover" role="menu">
			<div v-if="mode === 'presets'" class="simplestats-date-range__presets">
				<button
					v-for="p in presets"
					:key="p.key"
					type="button"
					class="simplestats-date-range__preset"
					:class="{ 'is-active': store.range.preset === p.key }"
					@click="choosePreset( p.key )"
				>
					{{ p.label }}
				</button>
				<button type="button" class="simplestats-date-range__custom-trigger" @click="mode = 'custom'">
					{{ text_custom }}
				</button>
			</div>

			<div v-else class="simplestats-date-range__calendar">
				<div class="simplestats-date-range__cal-nav">
					<button type="button" class="simplestats-date-range__cal-nav-btn" @click="navMonth(-1)" aria-label="Previous month">‹</button>
					<span class="simplestats-date-range__cal-nav-label">{{ monthLabel( leftMonth ) }} — {{ monthLabel( rightMonth ) }}</span>
					<button type="button" class="simplestats-date-range__cal-nav-btn" @click="navMonth(1)" aria-label="Next month">›</button>
				</div>
				<div class="simplestats-date-range__cal-grids">
					<CalendarGrid :month="leftMonth"  :start="custom.start" :end="custom.end" @pick="onPick" />
					<CalendarGrid :month="rightMonth" :start="custom.start" :end="custom.end" @pick="onPick" />
				</div>
				<div class="simplestats-date-range__cal-actions">
					<button type="button" class="simplestats-date-range__btn-secondary" @click="mode = 'presets'">{{ text_cancel }}</button>
					<button
						type="button"
						class="simplestats-date-range__btn-primary"
						:disabled="! ( custom.start && custom.end )"
						@click="applyCustom"
					>
						{{ text_apply }}
					</button>
				</div>
			</div>
		</div>
	</div>
</template>

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

	const store = useStore();

	const open = ref( false );
	const mode = ref( 'presets' );

	const text_custom = wp.i18n.__( 'Custom range', 'simplestats-friendly-website-analytics' );
	const text_apply  = wp.i18n.__( 'Apply',        'simplestats-friendly-website-analytics' );
	const text_cancel = wp.i18n.__( 'Cancel',       'simplestats-friendly-website-analytics' );

	const presets = [
		{ key: '7d',  label: wp.i18n.__( 'Last 7 Days',  'simplestats-friendly-website-analytics' ) },
		{ key: '14d', label: wp.i18n.__( 'Last 14 Days', 'simplestats-friendly-website-analytics' ) },
		{ key: '30d', label: wp.i18n.__( 'Last 30 Days', 'simplestats-friendly-website-analytics' ) },
		{ key: '60d', label: wp.i18n.__( 'Last 60 Days', 'simplestats-friendly-website-analytics' ) },
		{ key: '90d', label: wp.i18n.__( 'Last 90 Days', 'simplestats-friendly-website-analytics' ) },
	];

	const labelPrefix = computed( () => {
		const found = presets.find( ( p ) => p.key === store.range.preset );
		return `${ found ? found.label : wp.i18n.__( 'Custom', 'simplestats-friendly-website-analytics' ) }:`;
	} );

	function ordinalSuffix( n ) {
		const j = n % 10, k = n % 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 labelRange = computed( () => {
		// Format matches Figma 240:861 dropdown sample: "12 April - 18th April 2026".
		// End day carries an ordinal suffix; start day does not.
		const { from, to } = store.currentRange;
		const a = new Date( `${ from }T00:00:00` );
		const b = new Date( `${ to }T00:00:00` );
		const month = ( d ) => d.toLocaleDateString( undefined, { month: 'long' } );
		const bDay  = b.getDate();
		return `${ a.getDate() } ${ month( a ) } - ${ bDay }${ ordinalSuffix( bDay ) } ${ month( b ) } ${ b.getFullYear() }`;
	} );

	function toggle() {
		open.value = ! open.value;
		if ( ! open.value ) mode.value = 'presets';
	}

	function choosePreset( key ) {
		store.setRange( key );
		open.value = false;
		mode.value = 'presets';
	}

	function close() {
		open.value = false;
		mode.value = 'presets';
	}

	function handleEsc( e ) {
		if ( e.key === 'Escape' ) close();
	}

	onMounted( () => document.addEventListener( 'keydown', handleEsc ) );
	onBeforeUnmount( () => document.removeEventListener( 'keydown', handleEsc ) );

	// Custom calendar state ----------------------------------------------------

	const today      = new Date( ( SimpleStatsVue.todayIso || new Date().toISOString().slice( 0, 10 ) ) + 'T00:00:00' );
	const leftMonth  = ref( new Date( today.getFullYear(), today.getMonth() - 1, 1 ) );
	const rightMonth = computed( () => new Date( leftMonth.value.getFullYear(), leftMonth.value.getMonth() + 1, 1 ) );
	const custom     = reactive( { start: null, end: null } );

	function navMonth( dir ) {
		leftMonth.value = new Date( leftMonth.value.getFullYear(), leftMonth.value.getMonth() + dir, 1 );
	}

	function monthLabel( d ) {
		return d.toLocaleDateString( undefined, { month: 'long', year: 'numeric' } );
	}

	function onPick( iso ) {
		if ( ! custom.start || ( custom.start && custom.end ) ) {
			custom.start = iso;
			custom.end   = null;
		} else if ( iso < custom.start ) {
			custom.start = iso;
		} else {
			custom.end = iso;
		}
	}

	function applyCustom() {
		if ( ! custom.start || ! custom.end ) return;
		store.setRange( 'custom', { from: custom.start, to: custom.end } );
		open.value = false;
		mode.value = 'presets';
	}

	// Inline calendar grid ------------------------------------------------------

	const weekdayLabels = [ 'S', 'M', 'T', 'W', 'T', 'F', 'S' ];

	const CalendarGrid = {
		props: [ 'month', 'start', 'end' ],
		emits: [ 'pick' ],
		setup( gridProps, { emit } ) {
			const days = computed( () => {
				const first  = new Date( gridProps.month );
				const offset = first.getDay();
				const last   = new Date( first.getFullYear(), first.getMonth() + 1, 0 ).getDate();
				const cells  = [];
				for ( let i = 0; i < offset; i++ ) cells.push( null );
				for ( let d = 1; d <= last; d++ ) {
					const dt = new Date( first.getFullYear(), first.getMonth(), d );
					cells.push( {
						iso: `${ dt.getFullYear() }-${ String( dt.getMonth() + 1 ).padStart( 2, '0' ) }-${ String( d ).padStart( 2, '0' ) }`,
						day: d,
					} );
				}
				return cells;
			} );

			const isInRange = ( iso ) => gridProps.start && gridProps.end && iso > gridProps.start && iso < gridProps.end;

			return () => h( 'div', { class: 'simplestats-cal-grid' }, [
				...weekdayLabels.map( ( l, i ) => h( 'span', { class: 'simplestats-cal-grid__hdr', key: `h-${ i }` }, l ) ),
				...days.value.map( ( c, i ) => c
					? h( 'button', {
						type: 'button',
						key: c.iso,
						class: [
							'simplestats-cal-grid__cell',
							c.iso === gridProps.start && 'is-start',
							c.iso === gridProps.end && 'is-end',
							isInRange( c.iso ) && 'is-mid',
						].filter( Boolean ).join( ' ' ),
						onClick: () => emit( 'pick', c.iso ),
					}, c.day )
					: h( 'span', { class: 'simplestats-cal-grid__cell is-blank', key: `b-${ i }` } )
				),
			] );
		},
	};
</script>
