<script lang="ts">
	import { onMount, onDestroy } from 'svelte';
	import { slide, fly } from 'svelte/transition';
	import { navigating, page } from '$app/stores';
	import { resolve } from '$app/paths';
	import { authStore } from '$lib/stores/auth.svelte';
	import { apiFetch } from '$lib/utils/api';
	import { Button } from '$lib/components/ui/button';
	import { Skeleton } from '$lib/components/ui/skeleton';

	// Centralized link definition
	const links = [
		{ href: '/', label: 'Home', showWhen: 'non-admin', width: 'w-12' },
		{ href: '/today', label: 'Today', showWhen: 'admin', width: 'w-28' },
		{ href: '/admin/schedule', label: 'Schedule', showWhen: 'admin', width: 'w-20' },
		{ href: '/prices', label: 'Price List', showWhen: 'guest', width: 'w-20' },
		{ href: '/schedule', label: 'My Schedule', showWhen: 'auth-not-admin', width: 'w-24' },
		{ href: '/book', label: 'Book an appointment', showWhen: 'non-admin', width: 'w-36' },
		{ href: '/portfolio', label: 'Portfolio', showWhen: 'always', width: 'w-20' },
		{ href: '/admin', label: 'Admin Dashboard', showWhen: 'admin', width: 'w-28' },
		{ href: '/contact', label: 'Contact', showWhen: 'non-admin', width: 'w-16' },
		{ href: '/account', label: 'My Account', showWhen: 'auth', width: 'w-24' }
	];

	let mobileMenuOpen = $state(false);
	function toggleMenu() {
		mobileMenuOpen = !mobileMenuOpen;
	}

	// Close mobile menu when navigation starts
	$effect(() => {
		if ($navigating) {
			mobileMenuOpen = false;
		}
	});

	// Helper to decide visibility - use $derived for reactivity
	const canShow = (link: { href: string; label: string; showWhen: string; width: string }) => {
		if (authStore.isLoading) return true;

		if (link.showWhen === 'always') return true;
		if (link.showWhen === 'non-admin' && authStore.currentUser?.role !== 'admin') return true;
		if (link.showWhen === 'guest' && !authStore.isAuthenticated) return true;
		if (link.showWhen === 'auth' && authStore.isAuthenticated) return true;
		if (
			link.showWhen === 'auth-not-admin' &&
			authStore.isAuthenticated &&
			authStore.currentUser?.role !== 'admin'
		)
			return true;
		if (link.showWhen === 'admin' && authStore.currentUser?.role === 'admin') return true;
		return false;
	};

	// Derived values for auth state - ensures reactivity
	const isAuthenticated = $derived(authStore.isAuthenticated);
	const isLoading = $derived(authStore.isLoading);

	// Notification bell state
	let unreadCount = $state(0);
	let pollInterval: ReturnType<typeof setInterval> | null = null;

	async function fetchUnreadCount() {
		if (!authStore.isAuthenticated || !authStore.currentToken) return;
		try {
			const res = await apiFetch('/api/admin/notifications/unread-count');
			if (res.ok) {
				const data = await res.json();
				unreadCount = data.count;
			}
		} catch {
			// Silently fail - bell is non-critical
		}
	}

	onMount(() => {
		if (authStore.isAuthenticated) {
			fetchUnreadCount();
			if (authStore.currentUser?.role === 'admin') {
				pollInterval = setInterval(fetchUnreadCount, 60000);
			}
		}
	});

	onDestroy(() => {
		if (pollInterval) {
			clearInterval(pollInterval);
		}
	});
</script>

<nav
	class="fixed top-0 left-0 z-50 w-full border-b border-gray-200"
	class:frosty-nav={!mobileMenuOpen}
	class:bg-background={mobileMenuOpen}
>
	<div class="mx-auto max-w-7xl px-4 md:px-6 lg:px-8">
		<div class="flex h-16 items-center justify-between">
			<!-- Left: Social Icons -->
			<div class="flex items-center space-x-4">
				<a
					href="https://instagram.com"
					target="_blank"
					rel="noopener"
					class="text-gray-600 hover:text-primary"
					aria-label="Instagram"
				>
					<svg
						xmlns="http://www.w3.org/2000/svg"
						width="24"
						height="24"
						viewBox="0 0 24 24"
						fill="none"
						stroke="currentColor"
						stroke-width="2"
						stroke-linecap="round"
						stroke-linejoin="round"
					>
						<rect x="2" y="2" width="20" height="20" rx="5" ry="5"></rect>
						<path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"></path>
						<line x1="17.5" y1="6.5" x2="17.51" y2="6.5"></line>
					</svg>
				</a>
			</div>

			<!-- Center: Desktop Links -->
			<div class="hidden space-x-8 md:flex">
				{#each links as link (link.href)}
					{#if canShow(link)}
						{#if isLoading}
							<Skeleton class={`h-4 ${link.width} rounded`} />
						{:else}
							<!-- eslint-disable svelte/no-navigation-without-resolve -->
							<a href={link.href} class="font-medium text-gray-800 hover:text-primary"
								>{link.label}</a
							><!-- eslint-enable svelte/no-navigation-without-resolve -->
						{/if}
					{/if}
				{/each}
			</div>

			<div class="hidden items-center gap-4 md:flex">
				{#if isAuthenticated}
					<a
						href={resolve('/admin/notifications')}
						class="relative text-gray-600 hover:text-primary"
						aria-label="Notifications"
					>
						<svg
							xmlns="http://www.w3.org/2000/svg"
							width="24"
							height="24"
							viewBox="0 0 24 24"
							fill="none"
							stroke="currentColor"
							stroke-width="2"
							stroke-linecap="round"
							stroke-linejoin="round"
						>
							<path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9" />
							<path d="M10.3 21a1.94 1.94 0 0 0 3.4 0" />
						</svg>
						{#if unreadCount > 0}
							<span
								class="absolute -top-1 -right-1 flex h-4 w-4 items-center justify-center rounded-full bg-red-500 text-[10px] font-bold text-white"
							>
								{unreadCount > 9 ? '9+' : unreadCount}
							</span>
						{/if}
					</a>
				{/if}
				{#if !isLoading && !isAuthenticated && $page.url.pathname !== '/login'}
					<Button href={resolve('/login')}>Login</Button>
				{/if}
				{#if isLoading}
					<Skeleton class="h-8 w-16 rounded" />
				{/if}
			</div>

			<!-- Mobile: Burger -->
			<div class="flex items-center md:hidden">
				<button
					onclick={toggleMenu}
					class="relative h-6 w-6 focus:outline-none"
					aria-label="Toggle menu"
					class:open={mobileMenuOpen}
				>
					<span class="hamburger-line"></span>
					<span class="hamburger-line"></span>
					<span class="hamburger-line"></span>
					<span class="hamburger-line"></span>
					{#if unreadCount > 0}
						<span
							class="notification-badge absolute -top-1 -right-1.5 flex h-4 w-4 items-center justify-center rounded-full bg-red-500 text-[10px] font-bold text-white"
						>
							{unreadCount > 9 ? '9+' : unreadCount}
						</span>
					{/if}
				</button>
			</div>
		</div>
	</div>

	{#if mobileMenuOpen}
		<div
			class="fixed inset-0 top-16 bg-black/30 backdrop-blur-[1px] md:hidden"
			role="button"
			tabindex="0"
			aria-label="Close menu"
			onclick={toggleMenu}
			onkeydown={(e) => {
				if (e.key === 'Enter' || e.key === ' ') {
					e.preventDefault();
					toggleMenu();
				}
			}}
		></div>
	{/if}

	<!-- Mobile Menu -->
	{#if mobileMenuOpen}
		<div
			transition:slide={{ duration: 100 }}
			class="relative z-50 border-b border-gray-200 bg-background md:hidden"
		>
			<div class="space-y-1 px-2 pt-2 pb-3">
				{#each links as link (link.href)}
					{#if canShow(link)}
						{#if isLoading}
							<!-- eslint-disable svelte/no-navigation-without-resolve -->
							<Skeleton class="h-4 w-full rounded" />
						{:else}
							<!-- eslint-disable-next-line svelte/no-navigation-without-resolve -->
							<a
								href={link.href}
								class="block rounded px-3 py-2 text-center text-primary hover:text-gray-800"
							>
								{link.label}
							</a>
							<!-- eslint-enable svelte/no-navigation-without-resolve -->
						{/if}
					{/if}
				{/each}

				{#if isAuthenticated}
					<a
						href={resolve('/admin/notifications')}
						class="flex items-center justify-center gap-2 rounded px-3 py-2 text-primary hover:text-gray-800"
					>
						<span>Notifications</span>
						{#if unreadCount > 0}
							<span
								in:fly={{ y: -8, duration: 200, delay: 50 }}
								class="flex h-5 w-5 items-center justify-center rounded-full bg-red-500 text-[10px] font-bold text-white"
							>
								{unreadCount > 9 ? '9+' : unreadCount}
							</span>
						{/if}
					</a>
				{/if}

				{#if isLoading}
					<Skeleton class="mt-2 h-8 w-full rounded" />
				{:else if !isAuthenticated}
					<Button href={resolve('/login')} class="mt-2 w-full text-center">Login</Button>
				{/if}
			</div>
		</div>
	{/if}
</nav>

<style>
	.frosty-nav {
		backdrop-filter: saturate(180%) blur(10px);
	}

	/* Hamburger animation - 4 lines, middle two overlap when closed */
	.hamburger-line {
		display: block;
		position: absolute;
		height: 2px;
		width: 100%;
		background: #374151;
		border-radius: 2px;
		opacity: 1;
		left: 0;
		transform: rotate(0deg);
		transition: 0.125s ease-in-out;
	}

	.hamburger-line:nth-child(1) {
		top: 3px;
	}

	/* Spans 2 and 3 overlap at same position, span 3 hidden when closed */
	.hamburger-line:nth-child(2) {
		top: 10px;
	}

	.hamburger-line:nth-child(3) {
		top: 10px;
		opacity: 0;
	}

	.hamburger-line:nth-child(4) {
		top: 17px;
	}

	/* Open state - transform to X */
	.open .hamburger-line:nth-child(1) {
		top: 10px;
		width: 0%;
		left: 50%;
	}

	.open .hamburger-line:nth-child(2) {
		transform: rotate(45deg);
	}

	.open .hamburger-line:nth-child(3) {
		opacity: 1;
		transform: rotate(-45deg);
	}

	.open .hamburger-line:nth-child(4) {
		top: 10px;
		width: 0%;
		left: 50%;
	}

	/* Badge animations */
	.notification-badge {
		opacity: 1;
		transform: translateY(0);
		transition:
			opacity 0.2s ease,
			transform 0.2s ease;
	}

	.open .notification-badge {
		opacity: 0;
		transform: translateY(8px);
	}
</style>
