<script lang="ts">
	import { apiFetch } from '$lib/utils/api';
	import { ensureBusinessInfo, getBusinessInfo } from '$lib/stores/businessInfo.svelte';
	import { toast } from 'svelte-sonner';
	import { formatDuration } from '$lib/utils/format';
	import { formatUserName } from '$lib/utils/nameDisplay';
	import { parseWallClockDate } from '$lib/utils/timeSlots';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import { Badge } from '$lib/components/ui/badge';
	import { Skeleton } from '$lib/components/ui/skeleton';
	import PaymentModal from '$lib/components/payments/PaymentModal.svelte';
	import type { Booking as BookingType } from '$lib/types/booking';

	interface Props {
		openEditBookingModal: (bookingId: string, nextAppointmentStart?: string | null) => void;
		openUserModal: (userId: string) => void;
	}

	const { openEditBookingModal, openUserModal }: Props = $props();

	type Booking = {
		id: string;
		start_time: string;
		status: string;
		notes?: string;
		user_id?: string;
		created_at?: string;
		updated_at?: string;
		deposit_required?: boolean;
		deposit_paid?: boolean;
		amount_paid?: number;
		amount_due?: number;
		user?: {
			id: string;
			full_name: string;
			phone?: string;
			profile_pic_url?: string;
			previous_first_name?: string;
			previous_last_name?: string;
		};
		services: Array<{
			service_name?: string;
			service_description?: string;
			price?: number;
			duration_minutes?: number;
			override_price?: number;
			override_duration_minutes?: number;
		}>;
		duration_minutes: number;
		total_amount: number;
	};

	type DailySummary = {
		total_payments_today: number;
		total_tips_today: number;
		amount_due_today: number;
		total_duration_spent: number;
		customers_served: number;
		total_bookings: number;
		new_customers: number;
		returning_customers: number;
		guest_customers: number;
		gift_cards_sold: number;
		last_customer_name?: string;
		last_customer_visits?: number;
		summary_scope: 'day' | 'week';
		summary_start_date: string;
		summary_end_date: string;
		new_booking_services?: Array<{
			service_name: string;
			count: number;
		}>;
	};

	let currentAppointment = $state<Booking | null>(null);
	let nextAppointment = $state<Booking | null>(null);
	let closingTime = $state<string | null>(null);
	let freeTimeAfter = $state(0);
	let freeTimeCapped = $state(false);
	let loading = $state(true);
	let timeRemaining = $state(0);
	let isInProgress = $state(false);
	let showPaymentModal = $state(false);

	// Done-for-the-day state
	let doneForDay = $state(false);
	let summary = $state<DailySummary | null>(null);
	let weekSummary = $state<DailySummary | null>(null);

	// VAT registration status from public business info (via shared store)
	const vatRegistered = $derived(getBusinessInfo()?.is_vat_registered ?? false);

	// Data diffing — only update UI when payload actually changes
	let prevDataJson = $state('');

	function formatRemainingTime(minutes: number): string {
		const hours = Math.floor(minutes / 60);
		const mins = minutes % 60;
		if (hours === 0) return `${mins} minutes`;
		if (mins === 0) return `${hours} hour`;
		if (hours === 1) return `1 hour ${mins} minutes`;
		return `${hours} hours ${mins} minutes`;
	}

	const minutesUntilClosing = $derived.by(() => {
		if (!closingTime) return 0;
		const [ch, cm] = closingTime.split(':').map(Number);
		const now = new Date();
		const closing = new Date(now.getFullYear(), now.getMonth(), now.getDate(), ch, cm);
		return Math.max(0, Math.floor((closing.getTime() - now.getTime()) / 60000));
	});

	function calculateTimes() {
		const now = new Date();

		if (currentAppointment) {
			isInProgress = currentAppointment.status === 'in_progress';
			const startTime = parseWallClockDate(currentAppointment.start_time);

			const endTime = new Date(
				startTime.getTime() + currentAppointment.duration_minutes * 60 * 1000
			);

			if (isInProgress) {
				if (now.getTime() < startTime.getTime()) {
					const timeUntilMs = startTime.getTime() - now.getTime();
					timeRemaining = Math.max(0, Math.floor(timeUntilMs / 60000));
				} else {
					const remainingMs = endTime.getTime() - now.getTime();
					timeRemaining = Math.max(0, Math.floor(remainingMs / 60000));
				}
			} else {
				const timeUntilMs = startTime.getTime() - now.getTime();
				timeRemaining = Math.max(0, Math.floor(timeUntilMs / 60000));
			}

			let rawFreeMinutes = 0;
			if (nextAppointment) {
				const nextStart = parseWallClockDate(nextAppointment.start_time);
				const gapMs = nextStart.getTime() - endTime.getTime();
				rawFreeMinutes = Math.max(0, Math.floor(gapMs / 60000));
			}

			if (closingTime) {
				const [ch, cm] = closingTime.split(':').map(Number);
				const today = new Date();
				const closing = new Date(
					today.getFullYear(),
					today.getMonth(),
					today.getDate(),
					ch,
					cm,
					0
				);
				const minutesToClosing = Math.max(
					0,
					Math.floor((closing.getTime() - endTime.getTime()) / 60000)
				);

				if (!nextAppointment) {
					freeTimeAfter = minutesToClosing;
					freeTimeCapped = true;
				} else if (rawFreeMinutes > minutesToClosing) {
					freeTimeAfter = minutesToClosing;
					freeTimeCapped = true;
				} else {
					freeTimeAfter = rawFreeMinutes;
					freeTimeCapped = false;
				}
			} else {
				freeTimeAfter = nextAppointment ? rawFreeMinutes : 0;
				freeTimeCapped = false;
			}
		}
	}

	async function fetchCurrentAndNext() {
		loading = true;
		try {
			const response = await apiFetch('/api/admin/today/current-next', {
				headers: { 'Content-Type': 'application/json' }
			});

			if (response.ok) {
				const data = await response.json();
				const newJson = JSON.stringify({
					current: data.current || null,
					next: data.next || null,
					closingTime: data.closing_time || null,
					doneForDay: !!data.done_for_day,
					summary: data.summary || null,
					weekSummary: data.week_summary || null
				});
				if (newJson === prevDataJson) {
					loading = false;
					return;
				}
				prevDataJson = newJson;

				currentAppointment = data.current || null;
				nextAppointment = data.next || null;
				closingTime = data.closing_time || null;

				if (data.done_for_day) {
					doneForDay = true;
					summary = data.summary || null;
					weekSummary = data.week_summary || null;
				} else {
					doneForDay = false;
					summary = null;
					weekSummary = null;
				}

				calculateTimes();
			} else {
				toast.error('Failed to load current appointment');
			}
		} catch (err) {
			console.error('Error fetching current appointment:', err);
			toast.error('Network error loading appointment');
		} finally {
			loading = false;
		}
	}

	$effect(() => {
		ensureBusinessInfo();
		fetchCurrentAndNext();

		// Recalculate time display every 15s (no data fetch)
		const timeInterval = setInterval(() => {
			calculateTimes();
		}, 15000);

		// Poll for new data every 30s so new bookings appear automatically
		const dataInterval = setInterval(() => {
			fetchCurrentAndNext();
		}, 30_000);

		// Immediate refresh when a booking is created/approved
		function handleBookingApproved() {
			fetchCurrentAndNext();
		}
		window.addEventListener('bookingApproved', handleBookingApproved);

		return () => {
			clearInterval(timeInterval);
			clearInterval(dataInterval);
			window.removeEventListener('bookingApproved', handleBookingApproved);
		};
	});

	function handleBegin() {
		toast.info('Begin appointment - Coming soon');
	}

	function handleEdit() {
		if (currentAppointment) {
			openEditBookingModal(currentAppointment.id, nextAppointment?.start_time ?? null);
		}
	}

	function handleExtend() {
		toast.info('Extend appointment - Coming soon');
	}

	function handleTakePayment() {
		showPaymentModal = true;
	}

	function handlePaymentComplete() {
		toast.success('Payment completed');
		showPaymentModal = false;
	}

	function handleCancel() {
		toast.info('Cancel appointment - Coming soon');
	}

	function isMilestone(visits: number): boolean {
		if (visits < 5) return false;
		const early = [5, 10, 15, 20, 25, 50, 75, 100, 150];
		if (visits <= 150) return early.includes(visits);
		return visits % 50 === 0;
	}

	const activeAppointment = $derived(currentAppointment || nextAppointment);

	// The backend only accepts payments for bookings that have started or are
	// already complete — hide the button entirely before the booking starts.
	const canTakePayment = $derived(
		['in_progress', 'completed'].includes(activeAppointment?.status ?? '')
	);
</script>

<Card.Root
	class="border-2 {doneForDay ? 'border-teal-200 bg-teal-50' : 'border-blue-200 bg-blue-50'}"
>
	<Card.Header>
		{#if doneForDay}
			<div class="flex flex-col gap-1">
				<Card.Title class="flex items-center gap-2 text-xl md:text-2xl">
					<svg
						xmlns="http://www.w3.org/2000/svg"
						class="h-7 w-7 text-teal-600"
						fill="none"
						viewBox="0 0 24 24"
						stroke="currentColor"
						stroke-width="2"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
						/>
					</svg>
					{summary?.summary_scope === 'week' ? 'Closed today' : 'All done for today!'}
				</Card.Title>
				<Card.Description class="text-base">
					{summary?.summary_scope === 'week'
						? 'Showing summary from the last working period'
						: 'No more customers booked for today'}
				</Card.Description>
			</div>
		{:else}
			<div class="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
				<div class="min-w-0">
					<Card.Title class="text-xl md:text-2xl">
						{isInProgress ? 'Current Appointment' : 'Next Appointment'}
					</Card.Title>
					{#if activeAppointment}
						<Card.Description class="text-base">
							{parseWallClockDate(activeAppointment.start_time).toLocaleTimeString('en-US', {
								hour: 'numeric',
								minute: '2-digit',
								hour12: true
							})}
							-
							{new Date(
								parseWallClockDate(activeAppointment.start_time).getTime() +
									activeAppointment.duration_minutes * 60 * 1000
							).toLocaleTimeString('en-US', {
								hour: 'numeric',
								minute: '2-digit',
								hour12: true
							})}
						</Card.Description>
					{/if}
				</div>

				{#if activeAppointment}
					{#if isInProgress}
						<div class="flex flex-row flex-wrap gap-2 sm:flex-col sm:items-end">
							<Badge class="bg-blue-100 px-3 py-1 text-sm whitespace-nowrap text-blue-800">
								<span class="relative mr-2 flex h-2 w-2">
									<span
										class="absolute inline-flex h-full w-full animate-ping rounded-full bg-blue-400 opacity-75"
									></span>
									<span class="relative inline-flex h-2 w-2 rounded-full bg-blue-600"></span>
								</span>
								In Progress • {timeRemaining} min remaining
							</Badge>
							{#if timeRemaining > 29}
								{#if freeTimeCapped && freeTimeAfter === 0}
									<Badge class="bg-blue-100 px-3 py-1 text-sm whitespace-nowrap text-blue-800">
										closing after
									</Badge>
								{:else if freeTimeAfter > 0}
									<Badge class="bg-blue-100 px-3 py-1 text-sm whitespace-nowrap text-blue-800">
										{freeTimeAfter} min free afterwards{#if freeTimeCapped}
											(closing after){/if}
									</Badge>
								{/if}
							{/if}
						</div>
					{:else}
						<Badge class="bg-amber-100 px-3 py-1 text-sm whitespace-nowrap text-amber-800">
							Starts in {timeRemaining} min
						</Badge>
					{/if}
				{/if}
			</div>
		{/if}
	</Card.Header>

	{#if loading}
		<Card.Content class="space-y-4">
			<div class="flex gap-4">
				<Skeleton class="h-16 w-16 rounded-full md:h-20 md:w-20" />
				<div class="flex-1 space-y-2">
					<Skeleton class="h-6 w-48" />
					<Skeleton class="h-4 w-32" />
					<Skeleton class="h-4 w-40" />
				</div>
			</div>
			<Skeleton class="h-32 w-full" />
		</Card.Content>
	{:else if doneForDay && summary}
		<Card.Content>
			<div class="space-y-5">
				<!-- Conditional messages -->
				{#if minutesUntilClosing >= 75}
					<div
						class="flex items-start gap-2.5 rounded-md border border-teal-200 bg-teal-50/60 p-3 text-sm text-teal-800"
					>
						<svg
							class="mt-0.5 h-4 w-4 shrink-0"
							viewBox="0 0 24 24"
							fill="none"
							stroke="currentColor"
							stroke-width="2"
						>
							<circle cx="12" cy="12" r="10" />
							<path d="M12 16v-4M12 8h.01" />
						</svg>
						<div>
							<p class="font-medium">Online booking still open</p>
							<p class="mt-0.5 text-teal-700">Users booking online still have time to book in</p>
						</div>
					</div>
				{/if}
				{#if minutesUntilClosing >= 30}
					<div
						class="flex items-start gap-2.5 rounded-md border border-amber-200 bg-amber-50/60 p-3 text-sm text-amber-800"
					>
						<svg
							class="mt-0.5 h-4 w-4 shrink-0"
							viewBox="0 0 24 24"
							fill="none"
							stroke="currentColor"
							stroke-width="2"
						>
							<circle cx="12" cy="12" r="10" />
							<path d="M12 6v6l4 2" />
						</svg>
						<div>
							<p class="font-medium">Walk-ins closing soon</p>
							<p class="mt-0.5 text-amber-700">
								There is {formatRemainingTime(minutesUntilClosing)} left to accept walk-in bookings
							</p>
						</div>
					</div>
				{/if}

				{#if summary.summary_scope === 'week'}
					<div class="text-xs text-gray-500">
						Summary: {parseWallClockDate(summary.summary_start_date).toLocaleDateString('en-US', {
							weekday: 'short',
							month: 'short',
							day: 'numeric'
						})}
						&ndash;
						{parseWallClockDate(summary.summary_end_date).toLocaleDateString('en-US', {
							weekday: 'short',
							month: 'short',
							day: 'numeric'
						})}
					</div>
				{/if}

				<!-- Stats grid -->
				<div class="grid grid-cols-2 gap-3 sm:grid-cols-3">
					<div class="rounded-md border border-teal-100 bg-white p-3">
						<div class="text-xs font-medium text-gray-500">Payments Taken</div>
						<div class="mt-1 text-lg font-bold text-gray-900">
							£{summary.total_payments_today.toFixed(2)}
						</div>
						{#if vatRegistered}<div class="text-[10px] text-gray-400">incl. VAT</div>{/if}
					</div>

					<div class="rounded-md border border-teal-100 bg-white p-3">
						<div class="text-xs font-medium text-gray-500">Tips</div>
						<div class="mt-1 text-lg font-bold text-gray-900">
							£{summary.total_tips_today.toFixed(2)}
						</div>
					</div>

					<div class="rounded-md border border-teal-100 bg-white p-3">
						<div class="text-xs font-medium text-gray-500">Time in Appointments</div>
						<div class="mt-1 text-lg font-bold text-gray-900">
							{formatDuration(summary.total_duration_spent)}
						</div>
					</div>

					{#if summary.amount_due_today > 0}
						<div class="rounded-md border border-amber-200 bg-amber-50 p-3">
							<div class="text-xs font-medium text-amber-700">Still Due</div>
							<div class="mt-1 text-lg font-bold text-amber-900">
								£{summary.amount_due_today.toFixed(2)}
							</div>
							{#if summary.last_customer_name}
								<div class="text-xs text-amber-600">
									— {summary.last_customer_name}
								</div>
							{/if}
						</div>
					{/if}

					<div class="rounded-md border border-teal-100 bg-white p-3">
						<div class="text-xs font-medium text-gray-500">Customers Served</div>
						<div class="mt-1 text-lg font-bold text-gray-900">
							{summary.customers_served}
							{#if summary.total_bookings !== summary.customers_served}
								<span class="text-sm font-normal text-gray-500">
									across {summary.total_bookings} booking{summary.total_bookings !== 1 ? 's' : ''}
								</span>
							{/if}
						</div>
					</div>

					<div class="rounded-md border border-teal-100 bg-white p-3">
						<div class="text-xs font-medium text-gray-500">Customers</div>
						<div class="mt-1 space-y-0.5">
							{#if summary.new_customers > 0}
								<div class="flex items-baseline justify-between gap-2">
									<span class="text-lg font-bold text-gray-900">{summary.new_customers}</span>
									<span class="text-xs text-gray-500">new</span>
								</div>
							{/if}
							{#if summary.returning_customers > 0}
								<div class="flex items-baseline justify-between gap-2">
									<span class="text-lg font-bold text-gray-900">{summary.returning_customers}</span>
									<span class="text-xs text-gray-500">returning</span>
								</div>
							{/if}
							{#if summary.guest_customers > 0}
								<div class="flex items-baseline justify-between gap-2">
									<span class="text-lg font-bold text-gray-900">{summary.guest_customers}</span>
									<span class="text-xs text-gray-500">guest</span>
								</div>
							{/if}
						</div>
					</div>

					{#if summary.gift_cards_sold > 0}
						<div class="rounded-md border border-teal-100 bg-white p-3">
							<div class="text-xs font-medium text-gray-500">Gift Cards Sold</div>
							<div class="mt-1 text-lg font-bold text-gray-900">{summary.gift_cards_sold}</div>
						</div>
					{/if}
				</div>

				{#if summary.last_customer_name && isMilestone(summary.last_customer_visits ?? 0)}
					<div class="rounded-md border border-gray-200 bg-white p-3">
						<div class="flex items-center gap-2">
							<div>
								<span class="font-medium text-gray-900">{summary.last_customer_name}</span>
								<span class="text-gray-700">
									has visited {summary.last_customer_visits} times now!
								</span>
							</div>
						</div>
					</div>
				{/if}

				{#if summary.new_booking_services && summary.new_booking_services.length > 0}
					<div>
						<h4 class="mb-2 text-sm font-semibold text-gray-700">
							New bookings made since{summary.summary_scope === 'week'
								? ` opening ${parseWallClockDate(summary.summary_start_date).toLocaleDateString('en-US', { weekday: 'long' })}`
								: ' closing yesterday'}
						</h4>
						<div class="flex flex-wrap gap-2">
							{#each summary.new_booking_services as svc (svc.service_name)}
								<div class="rounded-md border border-gray-200 bg-white px-2.5 py-1.5 text-sm">
									<span class="font-semibold text-gray-900">{svc.count}</span>
									<span class="ml-1 text-gray-600">{svc.service_name}</span>
								</div>
							{/each}
						</div>
					</div>
				{/if}

				<!-- Week summary (shown alongside daily summary when tomorrow is closed) -->
				{#if weekSummary}
					<hr class="border-gray-200" />
					<div class="space-y-4">
						<div>
							<h4 class="text-sm font-semibold text-gray-700">This week so far</h4>
							<div class="text-xs text-gray-500">
								{parseWallClockDate(weekSummary.summary_start_date).toLocaleDateString('en-US', {
									weekday: 'short',
									month: 'short',
									day: 'numeric'
								})}
								&ndash;
								{parseWallClockDate(weekSummary.summary_end_date).toLocaleDateString('en-US', {
									weekday: 'short',
									month: 'short',
									day: 'numeric'
								})}
							</div>
						</div>

						<div class="grid grid-cols-2 gap-3 sm:grid-cols-3">
							<div class="rounded-md border border-gray-200 bg-white p-3">
								<div class="text-xs font-medium text-gray-500">Payments Taken</div>
								<div class="mt-1 text-lg font-bold text-gray-900">
									£{weekSummary.total_payments_today.toFixed(2)}
								</div>
								{#if vatRegistered}<div class="text-[10px] text-gray-400">incl. VAT</div>{/if}
							</div>

							<div class="rounded-md border border-gray-200 bg-white p-3">
								<div class="text-xs font-medium text-gray-500">Tips</div>
								<div class="mt-1 text-lg font-bold text-gray-900">
									£{weekSummary.total_tips_today.toFixed(2)}
								</div>
							</div>

							{#if weekSummary.amount_due_today > 0}
								<div class="rounded-md border border-amber-200 bg-amber-50 p-3">
									<div class="text-xs font-medium text-amber-700">Still Due</div>
									<div class="mt-1 text-lg font-bold text-amber-900">
										£{weekSummary.amount_due_today.toFixed(2)}
									</div>
								</div>
							{/if}

							<div class="rounded-md border border-gray-200 bg-white p-3">
								<div class="text-xs font-medium text-gray-500">Time in Appointments</div>
								<div class="mt-1 text-lg font-bold text-gray-900">
									{formatDuration(weekSummary.total_duration_spent)}
								</div>
							</div>

							<div class="rounded-md border border-gray-200 bg-white p-3">
								<div class="text-xs font-medium text-gray-500">Customers Served</div>
								<div class="mt-1 text-lg font-bold text-gray-900">
									{weekSummary.customers_served}
								</div>
							</div>

							{#if weekSummary.gift_cards_sold > 0}
								<div class="rounded-md border border-gray-200 bg-white p-3">
									<div class="text-xs font-medium text-gray-500">Gift Cards Sold</div>
									<div class="mt-1 text-lg font-bold text-gray-900">
										{weekSummary.gift_cards_sold}
									</div>
								</div>
							{/if}
						</div>
					</div>
				{/if}
			</div>
		</Card.Content>
	{:else if !activeAppointment}
		<Card.Content>
			<div class="py-12 text-center">
				<svg
					xmlns="http://www.w3.org/2000/svg"
					class="mx-auto mb-4 h-16 w-16 text-gray-300"
					fill="none"
					viewBox="0 0 24 24"
					stroke="currentColor"
					stroke-width="1.5"
				>
					<path
						stroke-linecap="round"
						stroke-linejoin="round"
						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>
				<p class="text-lg font-medium text-gray-600">No appointments right now</p>
				<p class="text-sm text-gray-500">Enjoy the break or check tomorrow's schedule</p>
			</div>
		</Card.Content>
	{:else}
		<Card.Content>
			<div class="grid gap-6 md:grid-cols-3">
				<!-- Customer Info -->
				<div class="flex min-w-0 items-center gap-3 sm:gap-4">
					{#if activeAppointment.user?.profile_pic_url}
						<img
							src={activeAppointment.user.profile_pic_url}
							alt={formatUserName(
								activeAppointment.user.full_name,
								activeAppointment.user.previous_first_name,
								activeAppointment.user.previous_last_name
							)}
							class="h-14 w-14 shrink-0 rounded-full object-cover ring-2 ring-blue-200 sm:h-16 sm:w-16 sm:ring-4 md:h-20 md:w-20"
						/>
					{:else}
						{@const initials =
							activeAppointment.user?.full_name
								?.split(' ')
								.map((n) => n[0])
								.join('') || '?'}
						<div
							class="flex h-14 w-14 shrink-0 items-center justify-center rounded-full bg-gray-200 text-xl font-bold text-gray-600 ring-2 ring-blue-200 sm:h-16 sm:w-16 sm:text-2xl sm:ring-4 md:h-20 md:w-20"
						>
							{initials}
						</div>
					{/if}
					<div class="min-w-0">
						<div class="truncate text-lg font-semibold">
							{formatUserName(
								activeAppointment.user?.full_name || 'Guest',
								activeAppointment.user?.previous_first_name,
								activeAppointment.user?.previous_last_name
							)}
						</div>
						<div class="truncate text-sm text-gray-600">{activeAppointment.user?.phone || '—'}</div>
						{#if activeAppointment.user}
							<button
								type="button"
								class="mt-1 text-xs text-blue-600 hover:underline"
								onclick={() => openUserModal(activeAppointment.user!.id)}
							>
								View customer details →
							</button>
						{/if}
					</div>
				</div>

				<!-- Services List -->
				<div>
					<div class="mb-2 text-sm font-semibold text-gray-700">Services</div>
					<div class="space-y-2">
						{#each activeAppointment.services as service, index (index)}
							<div class="rounded-md border border-gray-200 bg-white p-2 text-sm">
								<div class="font-medium">{service.service_name || 'Unknown Service'}</div>
								{#if service.service_description}
									<div class="text-xs text-gray-600">{service.service_description}</div>
								{/if}
								<div class="mt-1 flex items-center justify-between text-xs text-gray-500">
									<span
										>{formatDuration(
											service.override_duration_minutes ?? service.duration_minutes ?? 0
										)}</span
									>
								</div>
							</div>
						{/each}
					</div>
				</div>

				<!-- Notes & Actions -->
				<div class="space-y-3">
					{#if activeAppointment.notes}
						<div class="rounded-md border border-amber-200 bg-amber-50 p-3">
							<div class="mb-1 flex items-center gap-2 text-xs font-semibold text-amber-800">
								<svg
									xmlns="http://www.w3.org/2000/svg"
									class="h-4 w-4"
									viewBox="0 0 20 20"
									fill="currentColor"
								>
									<path
										fill-rule="evenodd"
										d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z"
										clip-rule="evenodd"
									/>
								</svg>
								Notes
							</div>
							<div class="text-sm text-amber-900">{activeAppointment.notes}</div>
						</div>
					{/if}
					<div class="grid grid-cols-2 gap-2">
						{#if !isInProgress}
							<Button size="sm" onclick={handleBegin} class="col-span-2">
								<svg
									xmlns="http://www.w3.org/2000/svg"
									class="mr-2 h-4 w-4"
									viewBox="0 0 20 20"
									fill="currentColor"
								>
									<path
										fill-rule="evenodd"
										d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z"
										clip-rule="evenodd"
									/>
								</svg>
								Begin
							</Button>
						{/if}
						<Button size="sm" variant="outline" onclick={handleEdit}>
							<svg
								xmlns="http://www.w3.org/2000/svg"
								class="mr-2 h-4 w-4"
								viewBox="0 0 20 20"
								fill="currentColor"
							>
								<path
									d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z"
								/>
							</svg>
							Edit
						</Button>
						{#if isInProgress}
							<Button size="sm" variant="outline" onclick={handleExtend}>
								<svg
									xmlns="http://www.w3.org/2000/svg"
									class="mr-2 h-4 w-4"
									viewBox="0 0 20 20"
									fill="currentColor"
								>
									<path
										fill-rule="evenodd"
										d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z"
										clip-rule="evenodd"
									/>
								</svg>
								Extend
							</Button>
						{/if}
						<Button size="sm" variant="destructive" onclick={handleCancel}>
							<svg
								xmlns="http://www.w3.org/2000/svg"
								class="mr-2 h-4 w-4"
								viewBox="0 0 20 20"
								fill="currentColor"
							>
								<path
									fill-rule="evenodd"
									d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
									clip-rule="evenodd"
								/>
							</svg>
							Cancel
						</Button>
						{#if canTakePayment}
							<Button
								size="sm"
								onclick={handleTakePayment}
								class="col-span-2 bg-green-600 hover:bg-green-700"
							>
								<svg
									xmlns="http://www.w3.org/2000/svg"
									class="mr-2 h-4 w-4"
									viewBox="0 0 20 20"
									fill="currentColor"
								>
									<path d="M4 4a2 2 0 00-2 2v1h16V6a2 2 0 00-2-2H4z" />
									<path
										fill-rule="evenodd"
										d="M18 9H2v5a2 2 0 002 2h12a2 2 0 002-2V9zM4 13a1 1 0 011-1h1a1 1 0 110 2H5a1 1 0 01-1-1zm5-1a1 1 0 100 2h1a1 1 0 100-2H9z"
										clip-rule="evenodd"
									/>
								</svg>
								Payment
							</Button>
						{/if}
					</div>
				</div>
			</div>
		</Card.Content>
	{/if}
</Card.Root>

{#if showPaymentModal && activeAppointment}
	<PaymentModal
		booking={activeAppointment as BookingType}
		onClose={() => (showPaymentModal = false)}
		onComplete={handlePaymentComplete}
	/>
{/if}
