<script>
	import { page } from '$app/stores';
	import profile from '$lib/images/profile.png';
	import { authentication } from '../routes/store.js';
	import { onMount } from 'svelte';

	let username = '';
	let profileTitle = 'Login';

	const unsubscribe = authentication.subscribe((value) => {
		username = value?.username || '';
		profileTitle = username ? `You are logged in as ${username}` : 'Login';
	});

	onMount(() => {
		const storedAuth = localStorage.getItem('authentication');
		if (storedAuth) {
			try {
				authentication.set(JSON.parse(storedAuth));
			} catch (e) {
				console.error('Failed to parse auth from localStorage', e);
			}
		}

		return () => unsubscribe();
	});
</script>

<header class="bg-white dark:bg-gray-900 shadow-md">
	<div class="max-w-7xl mx-auto flex items-center justify-between px-4 py-3">
		<!-- Left: logo / placeholder -->
		<div class="flex items-center">
			<!-- Insert logo or branding here -->
			<span class="text-lg font-bold text-theme-light dark:text-theme-dark"
				><a
					href="/stocks"
					class="hover:text-theme-light dark:hover:text-theme-dark transition-colors">Stocks</a
				></span
			>
		</div>

		<!-- Center: navigation -->
		<nav>
			<ul class="flex gap-6 text-sm font-medium text-gray-700 dark:text-gray-300">
				{#if username}
					<li aria-current={$page.url.pathname === '/stocks' ? 'page' : undefined}>
						<a
							href="/stocks"
							class="hover:text-theme-light dark:hover:text-theme-dark transition-colors">Stocks</a
						>
					</li>
					<li aria-current={$page.url.pathname === '/portfolio' ? 'page' : undefined}>
						<a
							href="/portfolio"
							class="hover:text-theme-light dark:hover:text-theme-dark transition-colors"
							>Portfolio</a
						>
					</li>
					<li aria-current={$page.url.pathname === '/insights' ? 'page' : undefined}>
						<a
							href="/insights"
							class="hover:text-theme-light dark:hover:text-theme-dark transition-colors"
							>Insights</a
						>
					</li>
				{/if}
			</ul>
		</nav>

		<!-- Right: user profile -->
		<div class="flex items-center gap-3">
			<a href="/profile" class="flex items-center gap-2 group">
				<span
					class="text-sm text-gray-600 dark:text-gray-300 group-hover:text-theme-light dark:group-hover:text-theme-dark"
				>
					{username}
				</span>
				<img
					src={profile}
					alt="Profile"
					class="w-6 h-6 rounded-full border border-gray-300 dark:border-gray-700"
					title={profileTitle}
				/>
			</a>
		</div>
	</div>
</header>
