<script lang="ts">
	import { onMount } from 'svelte';
	import { goto } from '$app/navigation';
	import { page } from '$app/state';
	import { isAuthenticated, getToken, handleUnauthorized } from './stores/authStore.svelte';
	import '../app.css';

	let { children } = $props();

	let userProfile: { username: string; is_admin: boolean } | null = $state(null);
	let authChecked = $state(false);

	onMount(async () => {
		const currentPath = page.url.pathname;

		if (currentPath === '/login') {
			authChecked = true;
			return;
		}

		if (!isAuthenticated()) {
			await goto('/login');
			authChecked = true;
			return;
		}

		// Validate token by fetching user profile
		try {
			const response = await fetch('/api/auth/me', {
				headers: { Authorization: `Bearer ${getToken()}` }
			});

			if (!response.ok) {
				handleUnauthorized();
				authChecked = true;
				return;
			}

			userProfile = await response.json();
		} catch {
			handleUnauthorized();
		}

		authChecked = true;
	});
</script>

<div class="app">
	{#if authChecked}
		{#if userProfile && page.url.pathname !== '/login'}
			<nav class="top-nav">
				<a href="/" class="nav-link">Apps</a>
				{#if userProfile.is_admin}
					<a href="/admin" class="nav-link">Admin</a>
				{/if}
				<span class="nav-spacer"></span>
				<span class="nav-user">{userProfile.username}</span>
			</nav>
		{/if}

		<main>
			{@render children()}
		</main>
	{/if}
</div>

<style>
	.app {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
	}

	main {
		width: 100%;
		margin: 0 auto;
		box-sizing: border-box;
	}

	.top-nav {
		display: flex;
		align-items: center;
		padding: 0.5rem 1rem;
		background-color: #1a1a2e;
		border-bottom: 1px solid #333;
	}

	.nav-link {
		color: #aaa;
		text-decoration: none;
		padding: 0.4rem 0.8rem;
		border-radius: 4px;
		font-size: 0.9rem;
	}

	.nav-link:hover {
		color: #e0e0e0;
		background-color: #2a2a4e;
		text-decoration: none;
	}

	.nav-spacer {
		flex-grow: 1;
	}

	.nav-user {
		color: #888;
		font-size: 0.85rem;
	}
</style>
