<script lang="ts">
	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import { pb } from '$lib/pb';
	import logo from '$lib/assets/checkflo-logo.png';

	let { children } = $props();

	const isLoginPage = $derived($page.url.pathname === '/admin/login');

	function logout() {
		pb.authStore.clear();
		goto('/admin/login');
	}

	const navItems = [
		{ href: '/admin/dashboard', label: 'Dashboard', icon: '◈' },
		{ href: '/admin/logs',      label: 'Protokoll',  icon: '≡' },
		{ href: '/admin/stations',  label: 'Stationen',  icon: '⊞' }
	];
</script>

{#if isLoginPage}
	{@render children()}
{:else}
	<div class="shell">
		<aside>
			<a href="/admin/dashboard" class="logo-link">
				<img src={logo} alt="checkflo" height="30" />
			</a>
			<nav>
				{#each navItems as item}
					<a
						href={item.href}
						class="nav-item"
						class:active={$page.url.pathname.startsWith(item.href)}
					>
						<span class="nav-icon">{item.icon}</span>
						<span>{item.label}</span>
					</a>
				{/each}
			</nav>
			<button class="logout" onclick={logout}>Abmelden</button>
		</aside>

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

<style>
	.shell {
		display: flex;
		min-height: 100dvh;
		background: #F5F7FA;
	}

	aside {
		width: 220px;
		background: #0B1023;
		color: #fff;
		display: flex;
		flex-direction: column;
		padding: 1.5rem 1rem;
		flex-shrink: 0;
	}

	.logo-link { display: block; margin-bottom: 2rem; padding: 0 0.5rem; }
	.logo-link img { filter: brightness(0) invert(1); }

	nav { display: flex; flex-direction: column; gap: 0.25rem; flex: 1; }

	.nav-item {
		display: flex;
		align-items: center;
		gap: 0.75rem;
		padding: 0.7rem 0.75rem;
		border-radius: 8px;
		color: #8892a4;
		font-size: 0.9rem;
		font-weight: 500;
		transition: all 0.15s;
	}
	.nav-item:hover { background: rgba(255,255,255,0.06); color: #fff; }
	.nav-item.active { background: rgba(249,115,22,0.15); color: #F97316; }
	.nav-icon { font-size: 1.1rem; }

	.logout {
		background: none;
		border: 1px solid #2a3347;
		color: #8892a4;
		padding: 0.6rem;
		border-radius: 8px;
		cursor: pointer;
		font-size: 0.85rem;
		transition: all 0.15s;
		margin-top: 1rem;
	}
	.logout:hover { border-color: #F97316; color: #F97316; }

	main {
		flex: 1;
		overflow: auto;
		padding: 2rem;
	}

	@media (max-width: 640px) {
		.shell { flex-direction: column; }
		aside {
			width: 100%;
			flex-direction: row;
			align-items: center;
			padding: 0.75rem 1rem;
		}
		.logo-link { margin-bottom: 0; margin-right: auto; }
		nav { flex-direction: row; flex: 0; gap: 0.5rem; }
		.nav-item span:last-child { display: none; }
		.logout { margin-top: 0; padding: 0.5rem 0.75rem; }
		main { padding: 1rem; }
	}
</style>
