<script lang="ts">
	import { onMount } from 'svelte';
	import { goto } from '$app/navigation';
	import { page } from '$app/state';
	import { logout } from '$lib/auth/auth.svelte';
	import RoleSwitcher from '$lib/components/organisms/RoleSwitcher/RoleSwitcher.svelte';
	import { fetchRoles, getRoles, resetRoleContext } from '$features/roles/roleContext.svelte';

	let { children } = $props();
	let isLoggingOut = $state(false);
	let accessChecked = $state(false);
	let hasAccess = $state(false);

	const ADMIN_ROLES = [
		'ROLE_SUPER_ADMIN',
		'ROLE_ADMIN',
		'ROLE_VIE_SCOLAIRE',
		'ROLE_SECRETARIAT'
	];

	// Load user roles and verify admin access
	onMount(async () => {
		await fetchRoles();
		const userRoles = getRoles();
		const isAdmin = userRoles.some((r) => ADMIN_ROLES.includes(r.value));

		if (!isAdmin) {
			goto('/dashboard');
			return;
		}

		hasAccess = true;
		accessChecked = true;
	});

	async function handleLogout() {
		isLoggingOut = true;
		try {
			resetRoleContext();
			await logout();
		} finally {
			isLoggingOut = false;
		}
	}

	function goHome() {
		goto('/dashboard');
	}

	function goSettings() {
		goto('/settings');
	}

	// Determine which admin section is active
	const isUsersActive = $derived(page.url.pathname.startsWith('/admin/users'));
	const isClassesActive = $derived(page.url.pathname.startsWith('/admin/classes'));
	const isSubjectsActive = $derived(page.url.pathname.startsWith('/admin/subjects'));
	const isPeriodsActive = $derived(page.url.pathname.startsWith('/admin/academic-year/periods'));
	const isAssignmentsActive = $derived(page.url.pathname.startsWith('/admin/assignments'));
	const isPedagogyActive = $derived(page.url.pathname.startsWith('/admin/pedagogy'));
</script>

{#if !accessChecked}
	<div class="loading-guard">
		<div class="spinner"></div>
	</div>
{:else if hasAccess}
	<div class="admin-layout">
		<header class="admin-header">
			<div class="header-content">
				<button class="logo-button" onclick={goHome}>
					<span class="logo-text">Classeo</span>
				</button>
				<nav class="header-nav">
					<RoleSwitcher />
					<a href="/dashboard" class="nav-link">Tableau de bord</a>
					<a href="/admin/users" class="nav-link" class:active={isUsersActive}>Utilisateurs</a>
					<a href="/admin/classes" class="nav-link" class:active={isClassesActive}>Classes</a>
					<a href="/admin/subjects" class="nav-link" class:active={isSubjectsActive}>Matières</a>
					<a href="/admin/assignments" class="nav-link" class:active={isAssignmentsActive}>Affectations</a>
					<a href="/admin/academic-year/periods" class="nav-link" class:active={isPeriodsActive}>Périodes</a>
					<a href="/admin/pedagogy" class="nav-link" class:active={isPedagogyActive}>Pédagogie</a>
					<button class="nav-button" onclick={goSettings}>Paramètres</button>
					<button class="logout-button" onclick={handleLogout} disabled={isLoggingOut}>
						{#if isLoggingOut}
							<span class="spinner"></span>
							Déconnexion...
						{:else}
							Déconnexion
						{/if}
					</button>
				</nav>
			</div>
		</header>

		<main class="admin-main">
			<div class="main-content">
				{@render children()}
			</div>
		</main>
	</div>
{/if}

<style>
	.loading-guard {
		display: flex;
		align-items: center;
		justify-content: center;
		min-height: 100vh;
	}

	.admin-layout {
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		background: var(--surface-primary, #f8fafc);
	}

	.admin-header {
		background: var(--surface-elevated, #fff);
		border-bottom: 1px solid var(--border-subtle, #e2e8f0);
		padding: 0 1.5rem;
		position: sticky;
		top: 0;
		z-index: 100;
	}

	.header-content {
		max-width: 1200px;
		margin: 0 auto;
		display: flex;
		justify-content: space-between;
		align-items: center;
		flex-wrap: wrap;
		height: auto;
		padding: 0.75rem 0;
		gap: 0.75rem;
	}

	.logo-button {
		background: none;
		border: none;
		cursor: pointer;
		padding: 0.5rem 0;
	}

	.logo-text {
		font-size: 1.25rem;
		font-weight: 700;
		color: var(--accent-primary, #0ea5e9);
	}

	.header-nav {
		display: flex;
		align-items: center;
		width: 100%;
		justify-content: flex-end;
		flex-wrap: wrap;
		gap: 0.5rem;
	}

	.nav-link {
		padding: 0.5rem 1rem;
		font-size: 0.875rem;
		font-weight: 500;
		color: var(--text-secondary, #64748b);
		text-decoration: none;
		border-radius: 0.5rem;
		transition: all 0.2s;
	}

	.nav-link:hover {
		color: var(--text-primary, #1f2937);
		background: var(--surface-primary, #f8fafc);
	}

	.nav-link.active {
		color: var(--accent-primary, #0ea5e9);
		background: var(--accent-primary-light, #e0f2fe);
	}

	.nav-button {
		padding: 0.5rem 1rem;
		font-size: 0.875rem;
		font-weight: 500;
		color: var(--text-secondary, #64748b);
		background: transparent;
		border: none;
		border-radius: 0.5rem;
		cursor: pointer;
		transition: all 0.2s;
	}

	.nav-button:hover {
		color: var(--text-primary, #1f2937);
		background: var(--surface-primary, #f8fafc);
	}

	.logout-button {
		display: inline-flex;
		align-items: center;
		gap: 0.5rem;
		padding: 0.5rem 1rem;
		font-size: 0.875rem;
		font-weight: 500;
		color: var(--text-secondary, #64748b);
		background: transparent;
		border: 1px solid var(--border-subtle, #e2e8f0);
		border-radius: 0.5rem;
		cursor: pointer;
		transition: all 0.2s;
	}

	.logout-button:hover:not(:disabled) {
		color: var(--color-alert, #ef4444);
		border-color: var(--color-alert, #ef4444);
	}

	.logout-button:disabled {
		opacity: 0.6;
		cursor: not-allowed;
	}

	.spinner {
		width: 14px;
		height: 14px;
		border: 2px solid var(--border-subtle, #e2e8f0);
		border-top-color: var(--text-secondary, #64748b);
		border-radius: 50%;
		animation: spin 0.8s linear infinite;
	}

	.admin-main {
		flex: 1;
		padding: 1rem;
	}

	.main-content {
		max-width: 1200px;
		margin: 0 auto;
	}

	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}

	@media (min-width: 768px) {
		.header-content {
			flex-wrap: nowrap;
			height: 64px;
			padding: 0;
			gap: 0;
		}

		.header-nav {
			width: auto;
			flex-wrap: nowrap;
			justify-content: flex-start;
		}

		.admin-main {
			padding: 1.5rem;
		}
	}
</style>
