<script lang="ts">
	import { user, isLoading, isConfigured, login, logout } from '$lib/auth/authStore';
	import { Button } from '$lib/components/ui/button';

	let isOpen = $state(false);

	const name = $derived(
		$user?.profile?.name ??
			$user?.profile?.preferred_username ??
			$user?.profile?.email ??
			$user?.profile?.sub ??
			'User'
	);

	function handleClickOutside(event: MouseEvent) {
		const target = event.target as HTMLElement;
		if (!target.closest('.auth-dropdown')) {
			isOpen = false;
		}
	}

	function toggleDropdown() {
		isOpen = !isOpen;
	}

	async function handleLogout() {
		isOpen = false;
		await logout();
	}
</script>

<svelte:window onclick={handleClickOutside} />

{#if $isLoading}
	<Button variant="outline" disabled>Loading...</Button>
{:else if !isConfigured}
	<span class="text-sm text-yellow-600">Auth not configured</span>
{:else if $user}
	<div class="auth-dropdown relative">
		<Button variant="outline" onclick={toggleDropdown}>
			{name}
		</Button>
		{#if isOpen}
			<div
				class="absolute right-0 z-50 mt-2 w-48 rounded-md bg-white p-2 shadow-lg dark:bg-gray-800"
			>
				<Button variant="ghost" class="w-full justify-start" onclick={handleLogout}>
					Sign out
				</Button>
			</div>
		{/if}
	</div>
{:else}
	<Button onclick={login}>Sign in</Button>
{/if}
