<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';
	import { fetchBranding, resetBranding, getLogoUrl } from '$features/branding/brandingStore.svelte';

	let { children } = $props();
	let isLoggingOut = $state(false);
	let accessChecked = $state(false);
	let hasAccess = $state(false);
	let mobileMenuOpen = $state(false);
	let logoUrl = $derived(getLogoUrl());

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

	// Types
	type NavLink = { href: string; label: string };
	type NavCategory = { id: string; label: string; links: NavLink[] };
	type NavEntry = NavLink | NavCategory;

	function isCategory(entry: NavEntry): entry is NavCategory {
		return 'links' in entry;
	}

	const navEntries: NavEntry[] = [
		{ href: '/dashboard', label: 'Tableau de bord' },
		{
			id: 'personnes',
			label: 'Personnes',
			links: [
				{ href: '/admin/users', label: 'Utilisateurs' },
				{ href: '/admin/parent-invitations', label: 'Invitations parents' },
				{ href: '/admin/students', label: 'Élèves' }
			]
		},
		{
			id: 'organisation',
			label: 'Organisation',
			links: [
				{ href: '/admin/classes', label: 'Classes' },
				{ href: '/admin/subjects', label: 'Matières' },
				{ href: '/admin/assignments', label: 'Affectations' },
				{ href: '/admin/replacements', label: 'Remplacements' },
				{ href: '/admin/schedule', label: 'Emploi du temps' }
			]
		},
		{
			id: 'annee',
			label: 'Année scolaire',
			links: [
				{ href: '/admin/academic-year/periods', label: 'Périodes' },
				{ href: '/admin/calendar', label: 'Calendrier' }
			]
		},
		{
			id: 'parametres',
			label: 'Paramètres',
			links: [
				{ href: '/admin/image-rights', label: "Droit à l'image" },
				{ href: '/admin/pedagogy', label: 'Pédagogie' },
				{ href: '/admin/branding', label: 'Identité visuelle' }
			]
		}
	];

	// 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;
		fetchBranding();
	});

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

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

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

	function toggleMobileMenu() {
		mobileMenuOpen = !mobileMenuOpen;
	}

	function closeMobileMenu() {
		mobileMenuOpen = false;
	}

	// Active link detection
	const activeLinkHref = $derived.by(() => {
		const path = page.url.pathname;
		for (const entry of navEntries) {
			if (isCategory(entry)) {
				for (const link of entry.links) {
					if (path.startsWith(link.href)) return link.href;
				}
			} else if (entry.href !== '/dashboard' && path.startsWith(entry.href)) {
				return entry.href;
			}
		}
		return null;
	});

	const activeCategoryId = $derived.by(() => {
		if (!activeLinkHref) return null;
		for (const entry of navEntries) {
			if (isCategory(entry) && entry.links.some((l) => l.href === activeLinkHref)) {
				return entry.id;
			}
		}
		return null;
	});

	const currentSectionLabel = $derived.by(() => {
		const path = page.url.pathname;
		for (const entry of navEntries) {
			if (isCategory(entry)) {
				for (const link of entry.links) {
					if (path.startsWith(link.href)) return link.label;
				}
			}
		}
		return 'Administration';
	});

	// Desktop dropdown state
	let openDesktopCategory = $state<string | null>(null);

	// Mobile accordion state
	let openMobileCategories = $state<Set<string>>(new Set());

	function toggleMobileCategory(id: string) {
		const next = new Set(openMobileCategories);
		if (next.has(id)) {
			next.delete(id);
		} else {
			next.add(id);
		}
		openMobileCategories = next;
	}

	// Auto-expand active category in mobile when drawer opens
	$effect(() => {
		if (mobileMenuOpen && activeCategoryId) {
			openMobileCategories = new Set([activeCategoryId]);
		}
	});

	// Close menus on route change
	$effect(() => {
		void page.url.pathname;
		mobileMenuOpen = false;
		openDesktopCategory = null;
	});

	// Close on Escape key
	$effect(() => {
		if (!mobileMenuOpen && !openDesktopCategory) return;

		function handleKeydown(e: KeyboardEvent) {
			if (e.key === 'Escape') {
				if (openDesktopCategory) openDesktopCategory = null;
				if (mobileMenuOpen) mobileMenuOpen = false;
			}
		}

		document.addEventListener('keydown', handleKeydown);
		return () => document.removeEventListener('keydown', handleKeydown);
	});

	// Lock body scroll when mobile menu is open
	$effect(() => {
		if (mobileMenuOpen) {
			document.body.style.overflow = 'hidden';
		} else {
			document.body.style.overflow = '';
		}

		return () => {
			document.body.style.overflow = '';
		};
	});
</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}>
					{#if logoUrl}
						<img src={logoUrl} alt="Logo de l'établissement" class="header-logo" />
					{/if}
					<span class="logo-text">Classeo</span>
				</button>

				<span class="mobile-section-label">{currentSectionLabel}</span>

				<button
					class="hamburger-button"
					onclick={toggleMobileMenu}
					aria-expanded={mobileMenuOpen}
					aria-label="Ouvrir le menu de navigation"
				>
					<span class="hamburger-line"></span>
					<span class="hamburger-line"></span>
					<span class="hamburger-line"></span>
				</button>

				<nav class="desktop-nav">
					<RoleSwitcher />
					{#each navEntries as entry}
						{#if isCategory(entry)}
							<!-- svelte-ignore a11y_no_static_element_interactions -->
							<div
								class="dropdown-wrapper"
								onmouseenter={() => (openDesktopCategory = entry.id)}
								onmouseleave={() => (openDesktopCategory = null)}
							>
								<button
									class="nav-link dropdown-trigger"
									class:active={activeCategoryId === entry.id}
									aria-expanded={openDesktopCategory === entry.id}
									aria-haspopup="true"
									onclick={() =>
										(openDesktopCategory =
											openDesktopCategory === entry.id ? null : entry.id)}
								>
									{entry.label}
									<span
										class="dropdown-chevron"
										class:open={openDesktopCategory === entry.id}
									>
										&#9662;
									</span>
								</button>
								{#if openDesktopCategory === entry.id}
									<div class="dropdown-panel" role="menu">
										{#each entry.links as link}
											<a
												href={link.href}
												class="dropdown-link"
												class:active={activeLinkHref === link.href}
												role="menuitem"
												onclick={() => (openDesktopCategory = null)}
											>
												{link.label}
											</a>
										{/each}
									</div>
								{/if}
							</div>
						{:else}
							<a href={entry.href} class="nav-link">{entry.label}</a>
						{/if}
					{/each}
					<button class="nav-button" onclick={goSettings}>Réglages</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>

		{#if mobileMenuOpen}
			<div
				class="mobile-overlay"
				onclick={closeMobileMenu}
				onkeydown={(e) => e.key === 'Enter' && closeMobileMenu()}
				role="presentation"
			></div>
			<div
				class="mobile-drawer"
				role="dialog"
				aria-modal="true"
				aria-label="Menu de navigation"
			>
				<div class="mobile-drawer-header">
					{#if logoUrl}
						<img src={logoUrl} alt="Logo de l'établissement" class="header-logo" />
					{/if}
					<span class="logo-text">Classeo</span>
					<button
						class="mobile-close"
						onclick={closeMobileMenu}
						aria-label="Fermer le menu"
					>
						&times;
					</button>
				</div>
				<div class="mobile-drawer-body">
					<div class="mobile-role-switcher">
						<RoleSwitcher />
					</div>
					{#each navEntries as entry}
						{#if isCategory(entry)}
							<div class="mobile-section">
								<button
									class="mobile-section-toggle"
									class:active={activeCategoryId === entry.id}
									aria-expanded={openMobileCategories.has(entry.id)}
									onclick={() => toggleMobileCategory(entry.id)}
								>
									{entry.label}
									<span
										class="accordion-chevron"
										class:open={openMobileCategories.has(entry.id)}
									>
										&#9662;
									</span>
								</button>
								{#if openMobileCategories.has(entry.id)}
									<div class="mobile-section-links">
										{#each entry.links as link}
											<a
												href={link.href}
												class="mobile-nav-link"
												class:active={activeLinkHref === link.href}
											>
												{link.label}
											</a>
										{/each}
									</div>
								{/if}
							</div>
						{:else}
							<a
								href={entry.href}
								class="mobile-nav-link mobile-standalone-link"
							>
								{entry.label}
							</a>
						{/if}
					{/each}
				</div>
				<div class="mobile-drawer-footer">
					<button class="mobile-nav-link" onclick={goSettings}>Réglages</button>
					<button
						class="mobile-nav-link mobile-logout"
						onclick={handleLogout}
						disabled={isLoggingOut}
					>
						{#if isLoggingOut}
							Déconnexion...
						{:else}
							Déconnexion
						{/if}
					</button>
				</div>
			</div>
		{/if}

		<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;
		height: 56px;
		padding: 0;
		gap: 0.75rem;
	}

	.logo-button {
		display: flex;
		align-items: center;
		gap: 0.5rem;
		background: none;
		border: none;
		cursor: pointer;
		padding: 0.5rem 0;
	}

	.header-logo {
		height: 32px;
		width: auto;
		object-fit: contain;
		border-radius: 0.25rem;
	}

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

	/* Mobile section label */
	.mobile-section-label {
		font-size: 0.875rem;
		font-weight: 600;
		color: var(--text-primary, #1f2937);
		flex: 1;
		text-align: center;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	/* Hamburger button */
	.hamburger-button {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		gap: 5px;
		width: 40px;
		height: 40px;
		background: none;
		border: none;
		cursor: pointer;
		padding: 8px;
		border-radius: 0.5rem;
		flex-shrink: 0;
	}

	.hamburger-button:hover {
		background: var(--surface-primary, #f8fafc);
	}

	.hamburger-line {
		display: block;
		width: 20px;
		height: 2px;
		background: var(--text-secondary, #64748b);
		border-radius: 1px;
	}

	/* Desktop nav — hidden on mobile */
	.desktop-nav {
		display: none;
		align-items: center;
		gap: 0.125rem;
	}

	.nav-link {
		padding: 0.375rem 0.625rem;
		font-size: 0.8125rem;
		font-weight: 500;
		color: var(--text-secondary, #64748b);
		text-decoration: none;
		border-radius: 0.5rem;
		transition: all 0.2s;
		white-space: nowrap;
		flex-shrink: 0;
	}

	.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);
	}

	/* Dropdown */
	.dropdown-wrapper {
		position: relative;
	}

	.dropdown-trigger {
		display: inline-flex;
		align-items: center;
		gap: 0.25rem;
		background: none;
		border: none;
		cursor: pointer;
	}

	.dropdown-chevron {
		font-size: 0.625rem;
		transition: transform 0.2s;
		line-height: 1;
	}

	.dropdown-chevron.open {
		transform: rotate(180deg);
	}

	.dropdown-panel {
		position: absolute;
		top: 100%;
		left: 0;
		min-width: 200px;
		background: var(--surface-elevated, #fff);
		border: 1px solid var(--border-subtle, #e2e8f0);
		border-radius: 0.5rem;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
		padding: 0.375rem 0;
		z-index: 150;
		animation: fadeIn 0.15s ease-out;
	}

	.dropdown-link {
		display: block;
		padding: 0.5rem 1rem;
		font-size: 0.8125rem;
		font-weight: 500;
		color: var(--text-secondary, #64748b);
		text-decoration: none;
		transition: all 0.15s;
		white-space: nowrap;
	}

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

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

	.nav-button {
		padding: 0.375rem 0.625rem;
		font-size: 0.8125rem;
		font-weight: 500;
		color: var(--text-secondary, #64748b);
		background: transparent;
		border: none;
		border-radius: 0.5rem;
		cursor: pointer;
		transition: all 0.2s;
		white-space: nowrap;
		flex-shrink: 0;
	}

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

	.logout-button {
		display: inline-flex;
		align-items: center;
		gap: 0.375rem;
		padding: 0.375rem 0.625rem;
		font-size: 0.8125rem;
		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;
		white-space: nowrap;
		flex-shrink: 0;
	}

	.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;
	}

	/* Mobile overlay */
	.mobile-overlay {
		position: fixed;
		inset: 0;
		background: rgba(0, 0, 0, 0.4);
		z-index: 200;
		animation: fadeIn 0.2s ease-out;
	}

	/* Mobile drawer */
	.mobile-drawer {
		position: fixed;
		top: 0;
		left: 0;
		bottom: 0;
		width: min(320px, 85vw);
		background: var(--surface-elevated, #fff);
		z-index: 201;
		display: flex;
		flex-direction: column;
		animation: slideInLeft 0.25s ease-out;
	}

	.mobile-drawer-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 1rem 1.25rem;
		border-bottom: 1px solid var(--border-subtle, #e2e8f0);
	}

	.mobile-close {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 36px;
		height: 36px;
		background: none;
		border: none;
		cursor: pointer;
		font-size: 1.5rem;
		color: var(--text-secondary, #64748b);
		border-radius: 0.5rem;
	}

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

	.mobile-drawer-body {
		flex: 1;
		overflow-y: auto;
		padding: 0.75rem 0;
	}

	.mobile-role-switcher {
		padding: 0.5rem 1.25rem 0.75rem;
		border-bottom: 1px solid var(--border-subtle, #e2e8f0);
		margin-bottom: 0.5rem;
	}

	/* Mobile accordion sections */
	.mobile-section {
		border-bottom: 1px solid var(--border-subtle, #e2e8f0);
	}

	.mobile-section:last-child {
		border-bottom: none;
	}

	.mobile-section-toggle {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 100%;
		padding: 0.75rem 1.25rem;
		font-size: 0.75rem;
		font-weight: 600;
		text-transform: uppercase;
		letter-spacing: 0.05em;
		color: var(--text-secondary, #64748b);
		background: none;
		border: none;
		cursor: pointer;
		transition: all 0.15s;
	}

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

	.mobile-section-toggle.active {
		color: var(--accent-primary, #0ea5e9);
	}

	.accordion-chevron {
		font-size: 0.625rem;
		transition: transform 0.2s;
	}

	.accordion-chevron.open {
		transform: rotate(180deg);
	}

	.mobile-section-links {
		padding-bottom: 0.375rem;
	}

	.mobile-section-links .mobile-nav-link {
		padding-left: 2rem;
		font-size: 0.875rem;
	}

	.mobile-standalone-link {
		border-bottom: 1px solid var(--border-subtle, #e2e8f0);
	}

	.mobile-nav-link {
		display: flex;
		align-items: center;
		width: 100%;
		padding: 0.75rem 1.25rem;
		font-size: 0.9375rem;
		font-weight: 500;
		color: var(--text-secondary, #64748b);
		text-decoration: none;
		border: none;
		background: none;
		cursor: pointer;
		border-left: 3px solid transparent;
		transition: all 0.15s;
	}

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

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

	.mobile-logout {
		color: var(--color-alert, #ef4444);
	}

	.mobile-logout:hover {
		background: #fef2f2;
	}

	.mobile-drawer-footer {
		border-top: 1px solid var(--border-subtle, #e2e8f0);
		padding: 0.5rem 0;
	}

	@keyframes fadeIn {
		from {
			opacity: 0;
		}
		to {
			opacity: 1;
		}
	}

	@keyframes slideInLeft {
		from {
			transform: translateX(-100%);
		}
		to {
			transform: translateX(0);
		}
	}

	.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: 1200px) {
		.header-content {
			height: 64px;
			gap: 0;
		}

		.mobile-section-label {
			display: none;
		}

		.hamburger-button {
			display: none;
		}

		.desktop-nav {
			display: flex;
		}

		.nav-link,
		.nav-button {
			padding: 0.5rem 0.75rem;
			font-size: 0.875rem;
		}

		.logout-button {
			padding: 0.5rem 0.75rem;
			font-size: 0.875rem;
		}

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