<script lang="ts">
	import '../app.css';
	import { auth } from '$lib/stores/auth';
	import { goto } from '$app/navigation';
	import { page } from '$app/stores';
	import { onMount } from 'svelte';

	const publicRoutes = ['/'];

	let isAuthenticated = false;
	let currentPath = '/';
	let userRole = '';

	auth.subscribe((state) => {
		isAuthenticated = !!state.token;
		userRole = state.user?.role || '';
	});

	page.subscribe(($page) => {
		currentPath = $page.url.pathname;
	});

	onMount(() => {
		const unsubscribe = page.subscribe(($page) => {
			const path = $page.url.pathname;
			const isPublic = publicRoutes.includes(path);
			
			if (!isPublic && !isAuthenticated) {
				goto('/');
			}
		});

		return unsubscribe;
	});

	function logout() {
		auth.logout();
		goto('/');
	}
</script>

<div class="min-h-screen flex flex-col">
	{#if isAuthenticated && currentPath !== '/'}
		<header class="bg-ohmj-primary text-white shadow-lg">
			<div class="container mx-auto px-4 py-3 flex justify-between items-center">
				<a href="/scores" class="flex items-center gap-3">
					<img src="/logo.png" alt="OHMJ" class="h-10" />
					<span class="text-xl font-bold text-ohmj-secondary hidden md:inline">
						Partitions
					</span>
				</a>
				<nav class="flex items-center gap-4">
					{#if userRole === 'admin'}
						<a href="/admin" class="text-white hover:text-ohmj-secondary text-sm">
							Admin
						</a>
					{/if}
					<button
						onclick={logout}
						class="bg-red-600 hover:bg-red-700 px-3 py-1 rounded text-sm transition-colors"
					>
						Déconnexion
					</button>
				</nav>
			</div>
		</header>
	{/if}

	<main class="flex-1">
		<slot />
	</main>

	{#if isAuthenticated && currentPath !== '/'}
		<footer class="bg-ohmj-dark text-gray-400 py-4 text-center text-sm">
			<p>© {new Date().getFullYear()} Harmonie de Montpellier-Jacou</p>
		</footer>
	{/if}
</div>
