<script lang="ts">
	import { type CalendarEvent, getEventColor } from '$lib/services/calendar';
	import {SvelteDate} from "svelte/reactivity";

	interface Props {
		events: CalendarEvent[];
		weekStart: Date;
		onEventClick?: (event: CalendarEvent) => void;
	}

	let { events, weekStart, onEventClick }: Props = $props();

	// Generate 7 days starting from weekStart (store as timestamps to avoid mutable Date in derived)
	let dayTimestamps = $derived.by(() => {
		return Array.from({ length: 7 }, (_, i) => {
			const date = new SvelteDate(weekStart);
			date.setDate(date.getDate() + i);
			return date.getTime();
		});
	});

	// Convert timestamps to Date objects for display
	function getDateFromTimestamp(ts: number): Date {
		return new Date(ts);
	}

	// Format date for grouping (YYYY-MM-DD)
	function formatDateKey(date: Date): string {
		return date.toISOString().split('T')[0];
	}

	// Get event date key
	function getEventDateKey(event: CalendarEvent): string {
		if (event.start.date) {
			return event.start.date;
		}
		if (event.start.dateTime) {
			return event.start.dateTime.split('T')[0];
		}
		return '';
	}

	// Format time for display
	function formatEventTime(event: CalendarEvent): string {
		if (event.start.date) {
			return 'All day';
		}
		if (event.start.dateTime) {
			const start = new Date(event.start.dateTime);
			return start.toLocaleTimeString('en-US', {
				hour: 'numeric',
				minute: '2-digit',
				hour12: true
			});
		}
		return '';
	}

	// Group events by day (use plain object instead of Map for reactivity)
	let eventsByDay = $derived.by(() => {
		const grouped: Record<string, CalendarEvent[]> = {};

		// Initialize each day with empty array
		for (const ts of dayTimestamps) {
			grouped[formatDateKey(getDateFromTimestamp(ts))] = [];
		}

		// Add events to their respective days
		for (const event of events) {
			const dateKey = getEventDateKey(event);
			if (grouped[dateKey]) {
				grouped[dateKey].push(event);
			}
		}

		// Sort events within each day by time
		for (const dayEvents of Object.values(grouped)) {
			dayEvents.sort((a, b) => {
				const aTime = a.start.dateTime || a.start.date || '';
				const bTime = b.start.dateTime || b.start.date || '';
				return aTime.localeCompare(bTime);
			});
		}

		return grouped;
	});

	// Check if a date is today
	function isToday(date: Date): boolean {
		const today = new Date();
		return (
			date.getDate() === today.getDate() &&
			date.getMonth() === today.getMonth() &&
			date.getFullYear() === today.getFullYear()
		);
	}
</script>

<div class="grid grid-cols-7 gap-2">
	{#each dayTimestamps as ts (ts)}
		{@const day = getDateFromTimestamp(ts)}
		{@const dateKey = formatDateKey(day)}
		{@const dayEvents = eventsByDay[dateKey] ?? []}
		{@const today = isToday(day)}
		<div
			class="min-h-[200px] rounded-lg border p-2
				{today ? 'border-accent7-500 bg-accent7-500/5' : 'border-theme bg-theme-card'}"
		>
			<!-- Day Header -->
			<div class="mb-2 text-center">
				<span class="block text-xs font-medium uppercase text-theme-muted">
					{day.toLocaleDateString('en-US', { weekday: 'short' })}
				</span>
				<span
					class="block text-lg font-semibold
						{today ? 'text-accent7-600 dark:text-accent7-400' : 'text-theme'}"
				>
					{day.getDate()}
				</span>
			</div>

			<!-- Events -->
			<div class="space-y-1">
				{#each dayEvents as event (event.id)}
					{@const eventColor = getEventColor(event.colorId)}
					<button
						type="button"
						onclick={() => onEventClick?.(event)}
						class="w-full rounded px-2 py-1 text-left text-xs transition-colors
							{eventColor
							? `${eventColor.bg} ${eventColor.text}`
							: 'bg-accent7-500/20 text-accent7-700 dark:text-accent7-300'}
							hover:opacity-80"
					>
						<span class="block truncate font-medium">{event.summary}</span>
						<span class="block truncate opacity-75">{formatEventTime(event)}</span>
					</button>
				{/each}
				{#if dayEvents.length === 0}
					<div class="py-4 text-center text-xs text-theme-muted">No events</div>
				{/if}
			</div>
		</div>
	{/each}
</div>
