<script lang="ts">
	import type { CalendarDate, DateValue } from '@internationalized/date';
	import Calendar from '$lib/components/ui/calendar/calendar.svelte';

	const {
		date,
		placeholder,
		minValue,
		maxValue,
		isDateUnavailable,
		onchange,
		onPlaceholderChange
	}: {
		date: CalendarDate | undefined;
		placeholder: CalendarDate;
		minValue: CalendarDate;
		maxValue: CalendarDate;
		isDateUnavailable: (date: DateValue) => boolean;
		onchange?: (date: CalendarDate | undefined) => void;
		onPlaceholderChange?: (date: CalendarDate) => void;
	} = $props();
</script>

<div class="flex items-center justify-center p-6">
	<Calendar
		type="single"
		value={date}
		{placeholder}
		// preventDeselect tells bits-ui to never deselect an already-selected date
		// (which would fire onValueChange(undefined) and desync the $bindable() chain)
		preventDeselect={true}
		// Inline wrapper creates a new function reference on every DatePicker render,
		// forcing bits-ui Calendar to re-evaluate availability for each date.
		// Without this the stable isDateUnavailable reference may cause stale availability
		// after workingHours/availableHours are updated (e.g. after month data loading).
		isDateUnavailable={(d) => isDateUnavailable(d)}
		class="bg-transparent p-0 [--cell-size:--spacing(10)] data-unavailable:line-through data-unavailable:opacity-100 md:[--cell-size:--spacing(12)] [&_[data-outside-month]]:pointer-events-none [&_[data-outside-month]]:opacity-0"
		weekdayFormat="short"
		{minValue}
		{maxValue}
		locale="en-GB"
		onValueChange={(v: DateValue | undefined) => {
			// Guard: bits-ui fires onValueChange(undefined) as an intermediate deselect
			// before firing onValueChange(selectedDate). In controlled mode this causes
			// the parent to briefly set selectedDate=undefined, which the Calendar then
			// receives back, effectively canceling the new selection. Only propagate
			// defined values to prevent the first-click-does-nothing issue.
			if (onchange && v) {
				onchange(v as CalendarDate | undefined);
			}
		}}
		onPlaceholderChange={(p: DateValue) => {
			if (onPlaceholderChange) {
				onPlaceholderChange(p as CalendarDate);
			}
		}}
	/>
</div>
