<script lang="ts">
	import PumpkinHead from '$lib/assets/pumpkin_head.png';
	import LazyLoadingImg from './LazyLoadingImg.svelte';
	import { page } from '$app/stores'; // 1. Import the page store

	type NavItem = {
		name: string;
		href?: string;
		children?: { name: string; href: string }[];
	};

	const navigation: NavItem[] = [
		{ name: 'Home', href: '/#home' },
		{ name: 'Projects', href: '/#projects' },
		{ name: 'Writings', href: '/#writings' },
		{ name: 'As Seen On', href: '/#as-seen-on' },
		{
			name: 'Free Time',
			href: '/#freetime',
			children: [
				{ name: 'Currently', href: '/#freetime' },
				{ name: 'Music', href: '/history/music' },
				{ name: 'Books', href: '/history/books' }
			]
		},
		{ name: 'Sponsors', href: '/#sponsors' }
	];

	let headSizes = $state([
		'w-12',
		'w-16',
		'w-20',
		'w-24',
		'w-28',
		'w-32',
		'w-36',
		'w-40',
		'w-48',
		'w-56',
		'w-64',
		'w-72',
		'w-80'
	]);

	let currentHeadSize = $state(headSizes[0]);

	const increaseHeadSize = () => {
		const index = headSizes.indexOf(currentHeadSize);
		currentHeadSize = headSizes[(index + 1) % headSizes.length];
	};

	let active = $derived.by(() => {
		const path = `${$page.url.pathname}${$page.url.hash}`;
		return path === '/' || path === '' ? '/#home' : path;
	});

	function onActivate(href: string | undefined) {
		if (href) active = href;
	}

	// A nav item is active when its own href matches, or — for dropdown parents like
	// "Free Time" — when any of its children (e.g. the history pages) is active.
	function isActive(item: NavItem): boolean {
		if (item.href && active === item.href) return true;
		return item.children?.some((child) => active === child.href) ?? false;
	}

	// onMount(() => {
	// 	const sections = navigation
	// 		.map((item) => document.getElementById(item.href.slice(1)))
	// 		.filter((el): el is HTMLElement => el !== null);

	// 	// Track which sections currently cross the activation band so we can
	// 	// always pick the topmost one even when several overlap it.
	// 	const intersecting = new Set<string>();

	// 	const updateActive = () => {
	// 		const next = navigation.find((item) => intersecting.has(item.href));
	// 		if (!next || next.href === active) return;
	// 		active = next.href;
	// 		// Use SvelteKit's replaceState (not the native history.replaceState):
	// 		// it updates the URL without scrolling *and* preserves the router's
	// 		// internal history.state. Calling native history.replaceState(null, …)
	// 		// here wipes SvelteKit's `sveltekit:history`/`sveltekit:navigation`
	// 		// state, which corrupts the router's scroll handling and makes anchor
	// 		// links intermittently fail to scroll.
	// 		replaceState(next.href, {});
	// 	};

	// 	const observer = new IntersectionObserver(
	// 		(entries) => {
	// 			for (const entry of entries) {
	// 				const hash = `#${entry.target.id}`;
	// 				if (entry.isIntersecting) intersecting.add(hash);
	// 				else intersecting.delete(hash);
	// 			}
	// 			updateActive();
	// 		},
	// 		// Thin band ~45% down the viewport: a section becomes active as it
	// 		// crosses that line.
	// 		{ rootMargin: '-45% 0px -50% 0px', threshold: 0 }
	// 	);

	// 	sections.forEach((section) => observer.observe(section));
	// 	return () => observer.disconnect();
	// });
</script>

<div class="sticky top-0 z-50 flex justify-center py-4">
	<div
		class="navbar max-w-xs rounded-full bg-base-100/90 py-0 shadow-2xl outline outline-base-content/5 backdrop-blur md:max-w-4xl"
	>
		<div class="navbar-start">
			<div class="dropdown">
				<div tabindex="0" role="button" class="btn btn-circle btn-ghost lg:hidden">
					<svg
						xmlns="http://www.w3.org/2000/svg"
						class="h-5 w-5"
						fill="none"
						viewBox="0 0 24 24"
						stroke="currentColor"
					>
						<path
							stroke-linecap="round"
							stroke-linejoin="round"
							stroke-width="2"
							d="M4 6h16M4 12h8m-8 6h16"
						/>
					</svg>
				</div>
				<ul
					class="dropdown-content menu z-[1] mt-3 w-52 gap-2 menu-md rounded-box bg-base-100 p-2 shadow"
				>
					{#each navigation as item (item.name)}
						{#if item.children}
							<li>
								<details>
									<summary class="font-urbanist {isActive(item) ? 'bg-base-300' : ''}">
										{item.name}
									</summary>
									<ul>
										{#each item.children as child (child.name)}
											<li>
												<a
													href={child.href}
													class="font-urbanist {active === child.href ? 'bg-base-300' : ''}"
												>
													{child.name}
												</a>
											</li>
										{/each}
									</ul>
								</details>
							</li>
						{:else}
							<li>
								<a href={item.href} class="font-urbanist {isActive(item) ? 'bg-base-300' : ''}">
									{item.name}
								</a>
							</li>
						{/if}
					{/each}
				</ul>
			</div>
			<a href="/" class="btn rounded-full font-urbanist text-lg font-semibold btn-ghost">
				Bailey Townsend
			</a>
		</div>
		<div class="ml-10 navbar-center hidden lg:flex">
			{#each navigation as item (item.name)}
				<nav class="menu menu-horizontal px-1">
					{#if item.children}
						<div class="dropdown-hover dropdown">
							<a
								href={item.href}
								tabindex="0"
								class="btn rounded-full font-urbanist text-sm font-light btn-ghost {isActive(item)
									? 'bg-base-300'
									: ''}"
								onclick={() => onActivate(item.href)}
							>
								{item.name}
							</a>
							<!-- mt-0! removes daisyUI's default 8px margin so there's no hover
							     dead-gap between the trigger and the menu; p-2 keeps inner spacing. -->
							<ul
								tabindex="-1"
								class="dropdown-content menu z-[1] mt-0! w-40 gap-1 rounded-box bg-base-100 p-2 shadow"
							>
								{#each item.children as child (child.name)}
									<li>
										<a
											href={child.href}
											class="font-urbanist text-sm"
											onclick={() => (active = child.href)}
										>
											{child.name}
										</a>
									</li>
								{/each}
							</ul>
						</div>
					{:else}
						<a
							href={item.href}
							class="btn rounded-full font-urbanist text-sm font-light btn-ghost {isActive(item)
								? 'bg-base-300'
								: ''}"
							onclick={() => onActivate(item.href)}
						>
							{item.name}
						</a>
					{/if}
				</nav>
			{/each}
		</div>

		<div class="navbar-end h-10 scale-75">
			<div class="avatar">
				<button
					title="Easter egg"
					onclick={increaseHeadSize}
					class={['rounded-full', 'cursor-pointer', currentHeadSize]}
				>
					<LazyLoadingImg
						class="w-full"
						imgClass="block w-full"
						alt="A cartoon Jack-o'-lantern "
						src={PumpkinHead}
					/>
				</button>
			</div>
			<!-- <ThemeToggle /> -->
		</div>
	</div>
</div>
