<script lang="ts">
	import ContentContainer from '$lib/components/layout/ContentContainer.svelte';
	import EventForm from '$lib/components/admin/calendar/EventForm.svelte';
	import MonthSelector from '$lib/components/team/MonthSelector.svelte';
	import WeekView from '$lib/components/admin/calendar/WeekView.svelte';
	import { offCanvas } from '$lib/stores/offCanvas.svelte';
	import { goto, invalidateAll } from '$app/navigation';
	import { getEventColor, calendarService } from '$lib/services/calendar';
	import {SvelteDate, SvelteSet} from 'svelte/reactivity';
	import type { PageData } from './$types';

	let { data }: { data: PageData } = $props();

	let events = $derived(data.events);
	let teamProfiles = $derived(data.teamProfiles);
	let eventsError = $derived(data.eventsError);
	let currentMonth = $derived(data.currentMonth);

	// View mode
	let viewMode = $state<'list' | 'week'>('list');

	// Calculate week start (Monday) for current month - store as timestamp
	let weekStartTimestamp = $derived.by(() => {
		const [year, month] = currentMonth.split('-').map(Number);
		const firstOfMonth = new Date(year, month - 1, 1);
		// Get Monday of the week containing the first of the month
		const dayOfWeek = firstOfMonth.getDay();
		const diff = dayOfWeek === 0 ? -6 : 1 - dayOfWeek; // Adjust for Monday start
		const monday = new SvelteDate(firstOfMonth);
		monday.setDate(monday.getDate() + diff);
		return monday.getTime();
	});

	// Convert to Date for WeekView prop
	function getWeekStart(): Date {
		return new Date(weekStartTimestamp);
	}

	// Bulk selection
	let selectedEvents = new SvelteSet<string>();
	let hasSelection = $derived(selectedEvents.size > 0);
	let bulkDeleting = $state(false);

	function toggleSelect(eventId: string) {
		if (selectedEvents.has(eventId)) {
			selectedEvents.delete(eventId);
		} else {
			selectedEvents.add(eventId);
		}
	}

	function isSelected(eventId: string): boolean {
		return selectedEvents.has(eventId);
	}

	function selectAll() {
		filteredEvents.forEach((e) => selectedEvents.add(e.id));
	}

	function clearSelection() {
		selectedEvents.clear();
	}

	async function bulkDelete() {
		if (!confirm(`Delete ${selectedEvents.size} event${selectedEvents.size !== 1 ? 's' : ''}? This cannot be undone.`)) {
			return;
		}

		bulkDeleting = true;
		try {
			for (const id of selectedEvents) {
				await calendarService.deleteEvent(id);
			}
			selectedEvents.clear();
			await invalidateAll();
		} catch (err) {
			console.error('Bulk delete failed:', err);
		} finally {
			bulkDeleting = false;
		}
	}

	// Search
	let searchQuery = $state('');

	// Time filter
	let timeFilter = $state<'all' | 'upcoming' | 'today' | 'past'>('all');

	// Get event date for filtering
	function getEventDate(event: (typeof events)[number]): Date {
		if (event.start.dateTime) {
			return new Date(event.start.dateTime);
		}
		if (event.start.date) {
			return new Date(event.start.date + 'T00:00:00');
		}
		return new Date();
	}

	// Filter by search query
	let searchFiltered = $derived.by(() => {
		if (!searchQuery.trim()) return events;

		const query = searchQuery.toLowerCase();
		return events.filter(
			(e) =>
				e.summary.toLowerCase().includes(query) ||
				e.description?.toLowerCase().includes(query) ||
				e.location?.toLowerCase().includes(query) ||
				e.attendees?.some(
					(a) =>
						a.email.toLowerCase().includes(query) || a.displayName?.toLowerCase().includes(query)
				)
		);
	});

	// Filter by time
	let filteredEvents = $derived.by(() => {
		if (timeFilter === 'all') return searchFiltered;

		const now = new Date();
		const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
		const todayEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999);

		return searchFiltered.filter((e) => {
			const eventDate = getEventDate(e);
			if (timeFilter === 'today') {
				return eventDate >= todayStart && eventDate <= todayEnd;
			}
			if (timeFilter === 'past') {
				return eventDate < todayStart;
			}
			// upcoming
			return eventDate >= now;
		});
	});

	// Counts for time filter tabs
	let timeCounts = $derived.by(() => {
		const now = new Date();
		const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
		const todayEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999);

		let upcoming = 0;
		let today = 0;
		let past = 0;

		for (const e of searchFiltered) {
			const eventDate = getEventDate(e);
			if (eventDate >= todayStart && eventDate <= todayEnd) {
				today++;
			} else if (eventDate < todayStart) {
				past++;
			} else if (eventDate >= now) {
				upcoming++;
			}
		}

		return { all: searchFiltered.length, upcoming, today, past };
	});

	// Time filter tab definitions
	const timeFilterTabs = [
		{ id: 'all' as const, label: 'All', color: 'accent7' },
		{ id: 'upcoming' as const, label: 'Upcoming', color: 'primary' },
		{ id: 'today' as const, label: 'Today', color: 'accent' },
		{ id: 'past' as const, label: 'Past', color: 'secondary' }
	];

	// Get current tab index for compact navigation
	let currentTabIndex = $derived(timeFilterTabs.findIndex((t) => t.id === timeFilter));
	let currentTab = $derived(timeFilterTabs[currentTabIndex]);

	function navigateTimeFilter(delta: number) {
		const newIndex = (currentTabIndex + delta + timeFilterTabs.length) % timeFilterTabs.length;
		timeFilter = timeFilterTabs[newIndex].id;
	}

	// Group events by date
	let eventsByDate = $derived.by(() => {
		const grouped: Record<string, typeof events> = {};

		for (const event of filteredEvents) {
			const dateKey = getEventDateKey(event);
			if (!grouped[dateKey]) {
				grouped[dateKey] = [];
			}
			grouped[dateKey].push(event);
		}

		// Sort dates and return as entries
		return Object.entries(grouped).sort((a, b) => a[0].localeCompare(b[0]));
	});

	// Get the date key for grouping (YYYY-MM-DD)
	function getEventDateKey(event: (typeof events)[number]): string {
		if (event.start.date) {
			return event.start.date;
		}
		if (event.start.dateTime) {
			return event.start.dateTime.split('T')[0];
		}
		return 'Unknown';
	}

	// Format date for section headers
	function formatDateHeader(dateStr: string): string {
		if (dateStr === 'Unknown') return 'Unknown Date';

		const date = new Date(dateStr + 'T00:00:00');
		const now = Date.now();
		const todayStart = now - (now % 86400000); // Start of today in ms

		const dateTime = date.getTime();
		if (dateTime >= todayStart && dateTime < todayStart + 86400000) {
			return 'Today';
		}
		if (dateTime >= todayStart + 86400000 && dateTime < todayStart + 172800000) {
			return 'Tomorrow';
		}

		return date.toLocaleDateString('en-US', {
			weekday: 'long',
			month: 'long',
			day: 'numeric',
			year: 'numeric'
		});
	}

	// Format time for event display
	function formatEventTime(event: (typeof events)[number]): string {
		if (event.start.date) {
			return 'All day';
		}
		if (event.start.dateTime) {
			const start = new Date(event.start.dateTime);
			const end = event.end?.dateTime ? new Date(event.end.dateTime) : null;

			const startStr = start.toLocaleTimeString('en-US', {
				hour: 'numeric',
				minute: '2-digit',
				hour12: true
			});

			if (end) {
				const endStr = end.toLocaleTimeString('en-US', {
					hour: 'numeric',
					minute: '2-digit',
					hour12: true
				});
				return `${startStr} - ${endStr}`;
			}

			return startStr;
		}
		return '';
	}

	function showCreateForm() {
		offCanvas.showRight({
			title: 'Create Event',
			content: createFormContent
		});
	}

	async function handleSuccess() {
		await invalidateAll();
	}

	function handleEventClick(event: { id: string }) {
		goto(`/admin/calendar/${event.id}`);
	}
</script>

{#snippet createFormContent()}
	<EventForm {teamProfiles} onSuccess={handleSuccess} />
{/snippet}

<svelte:head>
	<title>Calendar - Admin - Nexus</title>
</svelte:head>

<div class="py-8">
	<ContentContainer>
		<!-- Header -->
		<div class="mb-8">
			<div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
				<div class="flex items-start gap-4">
					<a
						href="/admin"
						class="rounded-lg p-1 text-theme-muted hover:bg-black/5 hover:text-theme dark:hover:bg-white/10"
						aria-label="Go back"
					>
						<svg class="h-5 w-5" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
							<path
								stroke-linecap="round"
								stroke-linejoin="round"
								stroke-width="2"
								d="M15 19l-7-7 7-7"
							/>
						</svg>
					</a>
					<div>
						<h1 class="text-2xl font-bold text-accent7-600 md:text-3xl dark:text-accent7-400">
							Calendar
						</h1>
						<p class="mt-2 text-theme-secondary">View and manage scheduled events.</p>
					</div>
				</div>
				<button
					type="button"
					onclick={showCreateForm}
					class="hidden items-center gap-2 rounded-lg bg-accent7-500 px-4 py-2 text-white transition-colors hover:bg-accent7-600 sm:inline-flex"
				>
					<svg class="h-5 w-5" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M12 4v16m8-8H4"
						/>
					</svg>
					<span>Create Event</span>
				</button>
			</div>
		</div>

		<!-- Month Navigation and View Toggle -->
		<div class="mb-6 flex flex-wrap items-center justify-center gap-4">
			<MonthSelector value={currentMonth} />

			<!-- View Toggle (hidden on mobile - week view doesn't work on small screens) -->
			<div class="hidden gap-1 rounded-lg bg-black/5 p-1 sm:flex dark:bg-white/5">
				<button
					type="button"
					onclick={() => (viewMode = 'list')}
					class="flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors
						{viewMode === 'list'
						? 'bg-accent7-500/15 text-accent7-600 dark:text-accent7-400'
						: 'text-theme-secondary hover:bg-black/5 dark:hover:bg-white/5'}"
				>
					<svg class="h-4 w-4" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
						<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16" />
					</svg>
					List
				</button>
				<button
					type="button"
					onclick={() => (viewMode = 'week')}
					class="flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium transition-colors
						{viewMode === 'week'
						? 'bg-accent7-500/15 text-accent7-600 dark:text-accent7-400'
						: 'text-theme-secondary hover:bg-black/5 dark:hover:bg-white/5'}"
				>
					<svg class="h-4 w-4" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
						<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
					</svg>
					Week
				</button>
			</div>
		</div>

		<!-- Error State -->
		{#if eventsError}
			<div class="mb-6 rounded-lg border border-error-500/30 bg-error-500/10 p-4">
				<div class="flex items-center gap-3">
					<svg
						class="h-5 w-5 shrink-0 text-error-600 dark:text-error-400"
						style="fill: none"
						stroke="currentColor"
						viewBox="0 0 24 24"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
						/>
					</svg>
					<div>
						<p class="font-medium text-error-600 dark:text-error-400">
							Failed to load calendar events
						</p>
						<p class="text-sm text-error-600/80 dark:text-error-400/80">
							{eventsError.message}
						</p>
					</div>
				</div>
			</div>
		{/if}

		<!-- Search and Filters -->
		<div class="mb-6 space-y-4">
			<!-- Search -->
			<div class="relative">
				<svg
					class="absolute top-1/2 left-3 h-5 w-5 -translate-y-1/2 text-theme-muted"
					style="fill: none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="2"
						d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
					/>
				</svg>
				<input
					type="text"
					bind:value={searchQuery}
					placeholder="Search events..."
					class="placeholder-theme-muted w-full rounded-lg border border-theme bg-theme-card py-2 pr-4 pl-10 text-theme focus:border-accent7-500 focus:ring-1 focus:ring-accent7-500"
				/>
			</div>

			<!-- Time Filter Tabs - Compact on mobile -->
			<div class="flex items-center justify-center gap-1 rounded-lg bg-black/5 p-1 sm:hidden dark:bg-white/5" role="tablist">
				<button
					type="button"
					onclick={() => navigateTimeFilter(-1)}
					class="interactive rounded-md p-2 text-theme-secondary"
					aria-label="Previous filter"
				>
					<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
						<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
					</svg>
				</button>
				<div
					class="flex-1 rounded-md px-4 py-2 text-center text-sm font-medium
						{currentTab.color === 'accent7'
						? 'bg-accent7-500/15 text-accent7-600 dark:text-accent7-400'
						: currentTab.color === 'primary'
							? 'bg-primary-500/15 text-primary-600 dark:text-primary-400'
							: currentTab.color === 'accent'
								? 'bg-accent-500/15 text-accent-600 dark:text-accent-400'
								: 'bg-secondary-500/15 text-secondary-600 dark:text-secondary-400'}"
					role="tab"
					aria-selected="true"
				>
					{currentTab.label}
					<span
						class="ml-1.5 rounded-full px-1.5 py-0.5 text-xs
							{currentTab.color === 'accent7'
							? 'bg-accent7-500/20'
							: currentTab.color === 'primary'
								? 'bg-primary-500/20'
								: currentTab.color === 'accent'
									? 'bg-accent-500/20'
									: 'bg-secondary-500/20'}"
					>
						{timeCounts[currentTab.id]}
					</span>
				</div>
				<button
					type="button"
					onclick={() => navigateTimeFilter(1)}
					class="interactive rounded-md p-2 text-theme-secondary"
					aria-label="Next filter"
				>
					<svg class="h-4 w-4" style="fill: none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
						<path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
					</svg>
				</button>
			</div>

			<!-- Time Filter Tabs - Full on desktop -->
			<div class="hidden gap-1 rounded-lg bg-black/5 p-1 sm:flex dark:bg-white/5" role="tablist">
				{#each timeFilterTabs as tab (tab.id)}
					{@const isActive = timeFilter === tab.id}
					{@const count = timeCounts[tab.id]}
					<button
						type="button"
						onclick={() => (timeFilter = tab.id)}
						class="flex-1 rounded-md px-3 py-2 text-sm font-medium transition-colors
							{isActive
							? tab.color === 'accent7'
								? 'bg-accent7-500/15 text-accent7-600 dark:text-accent7-400'
								: tab.color === 'primary'
									? 'bg-primary-500/15 text-primary-600 dark:text-primary-400'
									: tab.color === 'accent'
										? 'bg-accent-500/15 text-accent-600 dark:text-accent-400'
										: 'bg-secondary-500/15 text-secondary-600 dark:text-secondary-400'
							: 'text-theme-secondary hover:bg-black/5 hover:text-theme dark:hover:bg-white/5'}"
						role="tab"
						aria-selected={isActive}
					>
						{tab.label}
						<span
							class="ml-1.5 rounded-full px-1.5 py-0.5 text-xs
								{isActive
								? tab.color === 'accent7'
									? 'bg-accent7-500/20'
									: tab.color === 'primary'
										? 'bg-primary-500/20'
										: tab.color === 'accent'
											? 'bg-accent-500/20'
											: 'bg-secondary-500/20'
								: 'bg-black/5 dark:bg-white/5'}"
						>
							{count}
						</span>
					</button>
				{/each}
			</div>

			<!-- Bulk Selection Bar -->
			{#if hasSelection}
				<div class="flex flex-col gap-3 rounded-lg bg-accent7-500/10 p-3 sm:flex-row sm:items-center sm:justify-between">
					<div class="flex flex-wrap items-center justify-center gap-3 sm:justify-start">
						<span class="text-sm font-medium text-accent7-600 dark:text-accent7-400">
							{selectedEvents.size} event{selectedEvents.size !== 1 ? 's' : ''} selected
						</span>
						<button
							type="button"
							onclick={selectAll}
							class="text-sm text-accent7-600 underline hover:no-underline dark:text-accent7-400"
						>
							Select all
						</button>
						<button
							type="button"
							onclick={clearSelection}
							class="text-sm text-theme-secondary underline hover:no-underline"
						>
							Clear
						</button>
					</div>
					<button
						type="button"
						onclick={bulkDelete}
						disabled={bulkDeleting}
						class="flex w-full items-center justify-center gap-2 rounded-lg bg-error-500 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-error-600 disabled:opacity-50 sm:w-auto"
					>
						{#if bulkDeleting}
							<svg class="h-4 w-4 animate-spin" viewBox="0 0 24 24" style="fill: none" stroke="currentColor">
								<circle cx="12" cy="12" r="10" stroke-width="4" class="opacity-25"></circle>
								<path stroke-width="4" d="M4 12a8 8 0 018-8" class="opacity-75"></path>
							</svg>
							Deleting...
						{:else}
							<svg class="h-4 w-4" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
								<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
							</svg>
							Delete
						{/if}
					</button>
				</div>
			{/if}
		</div>

		<!-- Week View -->
		{#if viewMode === 'week'}
			<WeekView events={filteredEvents} weekStart={getWeekStart()} onEventClick={handleEventClick} />
		{:else}
			<!-- List View -->
			{#if eventsByDate.length > 0}
				<div class="space-y-8">
					{#each eventsByDate as [dateKey, dateEvents] (dateKey)}
					<div>
						<!-- Date Header -->
						<div class="mb-4 flex items-center gap-3">
							<div class="h-px flex-1 bg-accent7-500/20"></div>
							<h2 class="text-sm font-semibold text-accent7-600 dark:text-accent7-400">
								{formatDateHeader(dateKey)}
							</h2>
							<div class="h-px flex-1 bg-accent7-500/20"></div>
						</div>

						<!-- Events for this date -->
						<div class="space-y-3">
							{#each dateEvents as event (event.id)}
								{@const eventColor = getEventColor(event.colorId)}
								{@const selected = isSelected(event.id)}
								<div class="flex items-start gap-3">
									<!-- Checkbox -->
									<button
										type="button"
										onclick={() => toggleSelect(event.id)}
										class="mt-4 flex h-5 w-5 shrink-0 items-center justify-center rounded border transition-colors
											{selected
											? 'border-accent7-500 bg-accent7-500 text-white'
											: 'border-theme bg-theme hover:border-accent7-400'}"
										aria-label={selected ? 'Deselect event' : 'Select event'}
									>
										{#if selected}
											<svg class="h-3.5 w-3.5" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
												<path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7" />
											</svg>
										{/if}
									</button>
									<a href="/admin/calendar/{event.id}" class="block flex-1">
										<div class="card-calendar">
											<div class="flex items-start justify-between gap-4">
												<div class="min-w-0 flex-1 space-y-2">
													<!-- Event Title -->
													<div class="flex flex-wrap items-center gap-3">
														{#if eventColor}
															<span
																class="h-3 w-3 shrink-0 rounded-full {eventColor.bg}"
																title={eventColor.name}
															></span>
														{/if}
														<h3 class="text-lg font-semibold text-accent7-600 dark:text-accent7-400">
															{event.summary}
														</h3>
													{#if event.start.date}
														<span
															class="inline-flex items-center rounded-full bg-accent7-500/10 px-2.5 py-0.5 text-xs font-medium text-accent7-600 dark:text-accent7-400"
														>
															All Day
														</span>
													{/if}
												</div>

												<!-- Event Details -->
												<div class="flex flex-wrap items-center gap-4 text-sm text-theme-secondary">
													<!-- Time -->
													<span class="flex items-center gap-1.5">
														<svg
															class="h-4 w-4"
															style="fill: none"
															stroke="currentColor"
															viewBox="0 0 24 24"
														>
															<path
																stroke-linecap="round"
																stroke-linejoin="round"
																stroke-width="2"
																d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
															/>
														</svg>
														{formatEventTime(event)}
													</span>

													<!-- Location -->
													{#if event.location}
														<span class="flex items-center gap-1.5">
															<svg
																class="h-4 w-4"
																style="fill: none"
																stroke="currentColor"
																viewBox="0 0 24 24"
															>
																<path
																	stroke-linecap="round"
																	stroke-linejoin="round"
																	stroke-width="2"
																	d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"
																/>
																<path
																	stroke-linecap="round"
																	stroke-linejoin="round"
																	stroke-width="2"
																	d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"
																/>
															</svg>
															{event.location}
														</span>
													{/if}

													<!-- Attendees count (hidden on mobile) -->
													{#if event.attendees && event.attendees.length > 0}
														<span class="hidden items-center gap-1.5 sm:flex">
															<svg
																class="h-4 w-4"
																style="fill: none"
																stroke="currentColor"
																viewBox="0 0 24 24"
															>
																<path
																	stroke-linecap="round"
																	stroke-linejoin="round"
																	stroke-width="2"
																	d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
																/>
															</svg>
															{event.attendees.length} attendee{event.attendees.length !== 1
																? 's'
																: ''}
														</span>
													{/if}
												</div>

												<!-- Description preview (hidden on mobile) -->
												{#if event.description}
													<p class="hidden line-clamp-2 text-sm text-theme-muted sm:block">
														{event.description}
													</p>
												{/if}
											</div>

											<!-- Chevron -->
											<svg
												class="mt-1 h-5 w-5 shrink-0 text-theme-muted"
												style="fill: none"
												stroke="currentColor"
												viewBox="0 0 24 24"
											>
												<path
													stroke-linecap="round"
													stroke-linejoin="round"
													stroke-width="2"
													d="M9 5l7 7-7 7"
												/>
											</svg>
										</div>
									</div>
								</a>
							</div>
							{/each}
						</div>
					</div>
				{/each}
			</div>
		{:else if searchQuery}
			<div class="empty-state">
				<svg
					class="empty-state-icon text-accent7-400"
					style="fill: none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
					/>
				</svg>
				<h2 class="empty-state-title">No Events Found</h2>
				<p class="empty-state-text">
					No events match "{searchQuery}". Try a different search term.
				</p>
			</div>
		{:else}
			<div class="empty-state">
				<svg
					class="empty-state-icon text-accent7-400"
					style="fill: none"
					stroke="currentColor"
					viewBox="0 0 24 24"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						stroke-width="1.5"
						d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
					/>
				</svg>
				<h2 class="empty-state-title">No Upcoming Events</h2>
				<p class="empty-state-text">
					Get started by creating your first calendar event. Schedule meetings, reminders, and more.
				</p>
				<button
					type="button"
					onclick={showCreateForm}
					class="mt-4 inline-flex items-center gap-2 rounded-lg bg-accent7-500 px-4 py-2 text-white transition-colors hover:bg-accent7-600"
				>
					<svg class="h-5 w-5" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M12 4v16m8-8H4"
						/>
					</svg>
					<span>Create Event</span>
				</button>
			</div>
			{/if}
		{/if}
	</ContentContainer>
</div>

<!-- Mobile FAB -->
<button
	type="button"
	onclick={showCreateForm}
	class="fixed right-4 bottom-20 z-30 flex h-14 w-14 items-center justify-center rounded-full bg-accent7-500 text-white shadow-lg transition-colors hover:bg-accent7-600 sm:hidden"
	aria-label="Create Event"
>
	<svg class="h-6 w-6" style="fill: none" stroke="currentColor" viewBox="0 0 24 24">
		<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
	</svg>
</button>
