<script lang="ts">
import { enhance } from '$app/forms';
import { m } from '$lib/paraglide/messages.js';
import { clickOutside } from '$lib/shared/actions/clickOutside';

let { userInitials }: { userInitials: string | null } = $props();

let userMenuOpen = $state(false);
</script>

<div
	class="relative"
	use:clickOutside
	onclickoutside={() => (userMenuOpen = false)}
	onkeydown={(e) => {
		if (e.key === 'Escape') userMenuOpen = false;
	}}
	role="none"
>
	{#if userInitials}
		<button
			type="button"
			aria-expanded={userMenuOpen}
			aria-haspopup="true"
			onclick={() => (userMenuOpen = !userMenuOpen)}
			class="flex h-8 w-8 items-center justify-center rounded-full bg-white font-sans text-xs font-bold text-brand-navy transition-opacity hover:opacity-80 focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring"
		>
			{userInitials}
		</button>
	{:else}
		<button
			type="button"
			aria-label={m.nav_profile()}
			aria-expanded={userMenuOpen}
			aria-haspopup="true"
			onclick={() => (userMenuOpen = !userMenuOpen)}
			class="group rounded-sm p-2 transition-colors hover:bg-white/10 focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring"
		>
			<img
				src="/degruyter-icons/Simple/Small-16px/SVG/Action/Account-SM.svg"
				alt=""
				aria-hidden="true"
				class="h-5 w-5 opacity-65 brightness-0 invert transition-opacity group-hover:opacity-100"
			/>
		</button>
	{/if}

	{#if userMenuOpen}
		<div
			class="absolute top-full right-0 z-50 mt-1 min-w-[10rem] rounded-sm border border-line bg-overlay shadow-md"
		>
			<a
				href="/profile"
				onclick={() => (userMenuOpen = false)}
				class="block px-4 py-2.5 font-sans text-xs font-bold tracking-widest text-ink-2 uppercase transition-colors hover:bg-muted hover:text-ink"
			>
				{m.nav_profile()}
			</a>
			<div class="border-t border-line">
				<form action="/logout" method="POST" use:enhance>
					<button
						type="submit"
						class="w-full px-4 py-2.5 text-left font-sans text-xs font-bold tracking-widest text-ink-3 uppercase transition-colors hover:bg-muted hover:text-ink"
					>
						{m.nav_logout()}
					</button>
				</form>
			</div>
		</div>
	{/if}
</div>
