<script lang="ts">
	import { onMount } from 'svelte';
	import { Calendar, MapPin, Clock } from 'lucide-svelte';
	import type { CalendarWidgetConfig } from '$lib/types/widget.js';

	interface Props {
		config: CalendarWidgetConfig;
	}

	let { config }: Props = $props();

	interface CalendarEvent {
		summary: string;
		start: string;
		end: string;
		location?: string;
		calendarLabel?: string;
		calendarColor?: string;
	}

	let events: CalendarEvent[] = $state([]);
	let loading = $state(true);
	let error = $state(false);

	function groupLabel(dateStr: string): string {
		const date = new Date(dateStr);
		 
		const today = new Date();
		const tomorrow = new Date();
		 
		tomorrow.setDate(today.getDate() + 1);

		if (date.toDateString() === today.toDateString()) return 'Today';
		if (date.toDateString() === tomorrow.toDateString()) return 'Tomorrow';
		return date.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' });
	}

	function formatTimeRange(start: string, end: string): string {
		const s = new Date(start);
		const e = new Date(end);
		// Check if all-day (midnight to midnight or close to it)
		if (s.getHours() === 0 && s.getMinutes() === 0 && e.getHours() === 0 && e.getMinutes() === 0) {
			return 'All day';
		}
		const fmt = new Intl.DateTimeFormat('en-US', { hour: 'numeric', minute: '2-digit' });
		return `${fmt.format(s)} - ${fmt.format(e)}`;
	}

	interface GroupedEvents {
		label: string;
		events: CalendarEvent[];
	}

	const grouped = $derived.by((): GroupedEvents[] => {
		 
		const groups: Map<string, CalendarEvent[]> = new Map();
		for (const evt of events) {
			const key = new Date(evt.start).toDateString();
			const existing = groups.get(key);
			if (existing) {
				existing.push(evt);
			} else {
				groups.set(key, [evt]);
			}
		}
		const result: GroupedEvents[] = [];
		for (const [, evts] of groups) {
			result.push({
				label: groupLabel(evts[0].start),
				events: evts
			});
		}
		return result;
	});

	async function fetchEvents() {
		error = false;
		try {
			const res = await fetch('/api/widgets/calendar', {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({
					icalUrls: config.icalUrls,
					daysAhead: config.daysAhead ?? 7
				})
			});
			if (res.ok) {
				const json = await res.json();
				if (json.success && json.data) {
					events = json.data;
				}
			} else {
				error = true;
			}
		} catch {
			error = true;
		} finally {
			loading = false;
		}
	}

	onMount(() => {
		fetchEvents();
	});

	// Refresh every 30 minutes
	$effect(() => {
		const interval = setInterval(fetchEvents, 30 * 60 * 1000);
		return () => clearInterval(interval);
	});
</script>

<div class="flex h-full flex-col rounded-[1.4rem] border border-border bg-card shadow-[var(--shadow-soft)] p-4">
	<div class="mb-3 flex items-center gap-2">
		<Calendar class="h-4 w-4 text-muted-foreground" />
		<span class="text-sm font-medium text-foreground">Calendar</span>
	</div>

	{#if loading}
		<div class="space-y-3">
			{#each [1, 2, 3] as _n (_n)}
				<div class="space-y-1">
					<div class="h-3 w-16 animate-pulse rounded bg-muted"></div>
					<div class="h-4 w-3/4 animate-pulse rounded bg-muted"></div>
					<div class="h-3 w-1/3 animate-pulse rounded bg-muted"></div>
				</div>
			{/each}
		</div>
	{:else if error}
		<div class="flex flex-1 items-center justify-center">
			<span class="text-xs text-muted-foreground">Failed to load events</span>
		</div>
	{:else if events.length === 0}
		<div class="flex flex-1 items-center justify-center text-center">
			<div>
				<Calendar class="mx-auto mb-2 h-8 w-8 text-muted-foreground/50" />
				<span class="text-xs text-muted-foreground">No upcoming events</span>
			</div>
		</div>
	{:else}
		<div class="flex-1 space-y-3 overflow-y-auto">
			{#each grouped as group (group.label)}
				<div>
					<p class="mb-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
						{group.label}
					</p>
					<div class="space-y-1.5">
						{#each group.events as evt (evt.summary + evt.start)}
							<div class="flex items-start gap-2 rounded-lg px-2 py-1.5 transition-colors hover:bg-muted/50">
								<!-- Color dot -->
								<span
									class="mt-1.5 inline-block h-2 w-2 flex-shrink-0 rounded-full"
									style="background-color: {evt.calendarColor || 'hsl(var(--primary))'}"
								></span>
								<div class="min-w-0 flex-1">
									<p class="text-sm leading-tight text-foreground">{evt.summary}</p>
									<div class="mt-0.5 flex flex-wrap items-center gap-x-3 gap-y-0.5">
										<span class="flex items-center gap-1 text-xs text-muted-foreground">
											<Clock class="h-3 w-3" />
											{formatTimeRange(evt.start, evt.end)}
										</span>
										{#if evt.location}
											<span class="flex items-center gap-1 text-xs text-muted-foreground">
												<MapPin class="h-3 w-3" />
												<span class="truncate">{evt.location}</span>
											</span>
										{/if}
									</div>
								</div>
							</div>
						{/each}
					</div>
				</div>
			{/each}
		</div>
	{/if}
</div>
