<script lang="ts">
	import '../app.css';
	import Navbar from '$lib/components/Navbar.svelte';
	import { get, hasToken } from '$lib/api/client.ts';
	import type { User } from '$lib/api/types.ts';
	import { page } from '$app/state';

	let { children } = $props();
	let user = $state<User | null>(null);

	let currentPage = $derived(
		page.url.pathname === '/' ? 'dashboard' :
		page.url.pathname.startsWith('/foods') ? 'foods' :
		page.url.pathname.startsWith('/goals') ? 'goals' :
		page.url.pathname.startsWith('/templates') ? 'templates' :
		page.url.pathname.startsWith('/admin') ? 'admin' : ''
	);

	$effect(() => {
		if (typeof window !== 'undefined' && hasToken() && !page.url.pathname.startsWith('/login')) {
			get<User>('/api/user').then(u => user = u).catch(() => {});
		}
	});
</script>

<svelte:head>
	<title>Calorie Tracker</title>
</svelte:head>

<div class="min-h-screen bg-base-100 flex flex-col">
	{#if !page.url.pathname.startsWith('/login')}
		<Navbar {user} {currentPage} />
	{/if}
	<main class="flex-1">
		{@render children()}
	</main>
</div>
