<script lang="ts">
	import { browser } from '$app/environment';
	import { fetchGuests, ApiError, type GuestList } from '$lib/api';

	let status = $state<'loading' | 'done' | 'error'>('loading');
	let errorMessage = $state('');
	let guestList = $state<GuestList>({ guests: [], total: 0, adults: 0, children: 0 });

	$effect(() => {
		if (!browser) return;
		fetchGuests()
			.then((list) => {
				guestList = list;
				status = 'done';
			})
			.catch((err) => {
				status = 'error';
				errorMessage = err instanceof ApiError ? err.message : 'Something went wrong. Please try again.';
			});
	});
</script>

<section class="flex flex-1 items-center justify-center px-4 py-16">
	<div class="w-full max-w-md">
		<h1 class="font-serif text-4xl">Who's coming</h1>
		<p class="text-surface-600-400 mt-2 mb-8 text-2xl">
			{#if status === 'done'}
				{guestList.total}
				{guestList.total === 1 ? 'guest has' : 'guests have'} RSVP'd
				{#if guestList.children > 0}
					&mdash; {guestList.adults} adults, {guestList.children} children
				{/if}
			{:else}
				Everyone who has RSVP'd so far.
			{/if}
		</p>

		{#if status === 'loading'}
			<p class="text-surface-600-400 text-2xl">Loading…</p>
		{:else if status === 'error'}
			<p class="text-error-500 text-2xl">{errorMessage}</p>
		{:else if guestList.total === 0}
			<p class="text-surface-600-400 text-2xl">No RSVPs yet.</p>
		{:else}
			<ul class="flex flex-col gap-2">
				{#each guestList.guests as guest, i (i)}
					<li class="border-surface-300 dark:border-surface-700 flex items-center justify-between border-b py-2">
						<span class="text-2xl">{guest.name}</span>
						{#if guest.isChild}
							<span class="preset-tonal-secondary rounded-base px-2 text-lg font-medium">Child</span>
						{/if}
					</li>
				{/each}
			</ul>
		{/if}
	</div>
</section>
