<script lang="ts">
	import { page } from '$app/state';
	import { resolve } from '$app/paths';
	import { onMount } from 'svelte';
	import { alternatePath, type Bundle, type Locale } from '$lib/i18n';

	let { t, locale }: { t: Bundle; locale: Locale } = $props();

	let menuOpen = $state(false);
	let openDropdown = $state<string | null>(null);
	let activeSection = $state('');

	const altLocale: Locale = $derived(locale === 'fr' ? 'en' : 'fr');
	const altHref = $derived(alternatePath(page.url.pathname, altLocale));

	/** Extrait l'ancre d'une URL de nav (`/#solutions` → `solutions`). */
	function anchorOf(url: string): string {
		const i = url.indexOf('#');
		return i >= 0 ? url.slice(i + 1) : '';
	}

	// Section courante surlignée : la bande médiane du viewport désigne l'actif
	onMount(() => {
		const sections = [...document.querySelectorAll('section[id]')];
		if (sections.length === 0) return;
		const io = new IntersectionObserver(
			(entries) => {
				for (const entry of entries) {
					if (entry.isIntersecting) activeSection = entry.target.id;
				}
			},
			{ rootMargin: '-40% 0px -55% 0px' }
		);
		for (const section of sections) io.observe(section);
		return () => io.disconnect();
	});

	function rememberLangChoice() {
		localStorage.setItem('oki-lang-pref', altLocale);
	}

	function toggleTheme() {
		const isLight = document.documentElement.classList.toggle('light-theme');
		localStorage.setItem('oki-theme', isLight ? 'light' : 'dark');
	}

	function toggleDropdown(text: string) {
		openDropdown = openDropdown === text ? null : text;
	}

	function onKeydown(event: KeyboardEvent) {
		if (event.key === 'Escape') {
			openDropdown = null;
			menuOpen = false;
		}
	}

	function closeMenu() {
		menuOpen = false;
		openDropdown = null;
	}
</script>

<svelte:window onkeydown={onKeydown} />

<nav aria-label={t.ui?.nav_label ?? 'Navigation principale'}>
	<div class="nav-container">
		<a href={resolve(locale === 'en' ? '/en/' : '/')} class="logo" onclick={closeMenu}>
			<img src="/images/logo-512x512.png" alt="{t.site.shortName} Logo" class="logo-image" width="40" height="40" />
			<span>{t.site.shortName}</span>
		</a>

		<ul class="nav-links" id="nav-links" class:mobile-open={menuOpen}>
			{#each t.navigation as item (item.text)}
				{#if item.children}
					<li class="has-dropdown" class:open={openDropdown === item.text}>
						<button
							type="button"
							class="nav-dropdown-trigger"
							aria-haspopup="true"
							aria-expanded={openDropdown === item.text}
							onclick={() => toggleDropdown(item.text)}
						>
							{item.text} <span class="dropdown-caret" aria-hidden="true">▾</span>
						</button>
						<ul class="nav-dropdown">
							{#each item.children as child (child.text)}
								<li>
									{#if child.external}
										<a
											href={child.url}
											target="_blank"
											rel="external noopener noreferrer"
											onclick={closeMenu}>{child.text}</a
										>
									{:else}
										<a href={resolve(child.url)} onclick={closeMenu}>{child.text}</a>
									{/if}
								</li>
							{/each}
						</ul>
					</li>
				{:else}
					<li>
						<a
							href={resolve(item.url)}
							class:active={anchorOf(item.url) !== '' && anchorOf(item.url) === activeSection}
							aria-current={anchorOf(item.url) === activeSection ? 'true' : undefined}
							onclick={closeMenu}>{item.text}</a
						>
					</li>
				{/if}
			{/each}
		</ul>

		<a href={resolve(altHref)} class="lang-switch" hreflang={altLocale} onclick={rememberLangChoice}>
			{t.ui.lang_switch_label}
		</a>

		<button
			type="button"
			class="theme-toggle"
			aria-label={t.ui.theme_toggle}
			title={t.ui.theme_toggle}
			onclick={toggleTheme}
		>
			<svg class="theme-icon theme-icon-dark" viewBox="0 0 24 24" aria-hidden="true">
				<path d="M20 14.5A8.5 8.5 0 0 1 9.5 4 8.5 8.5 0 1 0 20 14.5Z" />
			</svg>
			<svg class="theme-icon theme-icon-light" viewBox="0 0 24 24" aria-hidden="true">
				<circle cx="12" cy="12" r="4.5" />
				<path d="M12 2v3M12 19v3M2 12h3M19 12h3M4.5 4.5l2 2M17.5 17.5l2 2M19.5 4.5l-2 2M6.5 17.5l-2 2" />
			</svg>
		</button>

		<button
			type="button"
			class="menu-toggle"
			class:open={menuOpen}
			aria-expanded={menuOpen}
			aria-controls="nav-links"
			aria-label="Menu"
			onclick={() => (menuOpen = !menuOpen)}
		>
			<span></span>
			<span></span>
			<span></span>
		</button>
	</div>
	<div class="flag-bar" aria-hidden="true"></div>
</nav>

<style>
	nav {
		position: fixed;
		top: 0;
		width: 100%;
		padding: 1rem 2rem 0.85rem;
		background: var(--noir-oki);
		z-index: 1000;
		transition: background var(--dur-mesure) var(--ease-ka);
	}

	nav .flag-bar {
		position: absolute;
		bottom: 0;
		left: 0;
	}

	:global(html.light-theme) nav {
		box-shadow: 0 1px 0 var(--line);
	}

	.nav-container {
		max-width: var(--container);
		margin: 0 auto;
		display: flex;
		justify-content: space-between;
		align-items: center;
		gap: 1rem;
	}

	.logo {
		display: flex;
		align-items: center;
		gap: 0.6rem;
		font-family: var(--font-display);
		font-size: 1.4rem;
		font-weight: 700;
		color: var(--or-oki);
		letter-spacing: 0.02em;
	}

	.logo-image {
		height: 2.5rem;
		width: auto;
		background: #fff;
		padding: 0.25rem;
		border-radius: var(--radius-md);
	}

	.nav-links {
		display: flex;
		gap: 2rem;
		list-style: none;
	}

	.nav-links a {
		position: relative;
		color: var(--blanc-creme);
		font-weight: 500;
		font-size: 0.95rem;
	}

	/* Souligné or qui se dessine depuis la gauche (hover + section active) */
	.nav-links a::after {
		content: '';
		position: absolute;
		left: 0;
		bottom: -6px;
		width: 100%;
		height: 2px;
		background: var(--or-oki);
		transform: scaleX(0);
		transform-origin: left center;
		transition: transform var(--dur-tanbou) var(--ease-syncope);
	}

	.nav-links a:hover,
	.nav-links a.active {
		color: var(--or-oki);
	}

	.nav-links a:hover::after,
	.nav-links a.active::after {
		transform: scaleX(1);
	}

	.lang-switch {
		border: 1px solid var(--line);
		border-radius: var(--radius-sm);
		padding: 0.5rem 0.7rem;
		color: var(--blanc-creme);
		font-weight: 700;
		font-size: 0.8rem;
		letter-spacing: 0.04em;
		transition:
			border-color var(--dur-tanbou) var(--ease-ka),
			color var(--dur-tanbou) var(--ease-ka);
	}

	.lang-switch:hover {
		border-color: var(--or-oki);
		color: var(--or-oki);
	}

	.theme-toggle {
		background: transparent;
		border: 1px solid var(--line);
		border-radius: var(--radius-sm);
		padding: 0.5rem 0.7rem;
		cursor: pointer;
		display: flex;
		align-items: center;
		color: var(--blanc-creme);
		transition: border-color var(--dur-tanbou) var(--ease-ka);
	}

	.theme-toggle:hover {
		border-color: var(--or-oki);
	}

	.theme-icon {
		width: 1.1rem;
		height: 1.1rem;
		fill: none;
		stroke: currentColor;
		stroke-width: 2;
		stroke-linecap: square;
	}

	.theme-icon-light {
		display: none;
	}

	:global(html.light-theme) .theme-icon-dark {
		display: none;
	}

	:global(html.light-theme) .theme-icon-light {
		display: block;
	}

	.menu-toggle {
		display: none;
		flex-direction: column;
		gap: 5px;
		background: none;
		border: none;
		cursor: pointer;
		padding: 0.25rem;
	}

	.menu-toggle span {
		width: 24px;
		height: 2px;
		background: var(--or-oki);
		transition: transform var(--dur-tanbou) var(--ease-ka), opacity var(--dur-tanbou) var(--ease-ka);
	}

	.has-dropdown {
		position: relative;
	}

	.nav-dropdown-trigger {
		display: flex;
		align-items: center;
		gap: 0.3rem;
		background: none;
		border: none;
		padding: 0;
		font-family: inherit;
		font-weight: 500;
		font-size: 0.95rem;
		color: var(--blanc-creme);
		cursor: pointer;
	}

	.nav-dropdown-trigger:hover {
		color: var(--or-oki);
	}

	.dropdown-caret {
		font-size: 0.7em;
		transition: transform var(--dur-tanbou) var(--ease-ka);
	}

	.nav-dropdown {
		position: absolute;
		top: 100%;
		left: 0;
		margin-top: 1rem;
		min-width: 200px;
		list-style: none;
		background: var(--noir-oki);
		border: 1px solid var(--line);
		border-radius: var(--radius-sm);
		padding: 0.4rem 0;
		opacity: 0;
		visibility: hidden;
		transform: translateY(-6px);
		transition:
			opacity var(--dur-tanbou) var(--ease-ka),
			transform var(--dur-tanbou) var(--ease-ka),
			visibility var(--dur-tanbou);
	}

	.has-dropdown:hover .nav-dropdown,
	.has-dropdown.open .nav-dropdown,
	.nav-dropdown-trigger:focus-visible + .nav-dropdown {
		opacity: 1;
		visibility: visible;
		transform: translateY(0);
	}

	.has-dropdown:hover .dropdown-caret,
	.has-dropdown.open .dropdown-caret {
		transform: rotate(180deg);
	}

	.nav-dropdown a {
		display: block;
		padding: 0.55rem 1.1rem;
		white-space: nowrap;
		font-size: 0.9rem;
	}

	@media (max-width: 1100px) {
		.nav-links {
			display: none;
		}

		.nav-links.mobile-open {
			display: flex;
			position: absolute;
			top: 100%;
			left: 0;
			right: 0;
			flex-direction: column;
			padding: 1rem;
			border-top: 2px solid var(--or-oki);
			background: var(--noir-oki);
		}

		.menu-toggle {
			display: flex;
		}

		.menu-toggle.open span:nth-child(1) {
			transform: rotate(45deg) translateY(8px);
		}

		.menu-toggle.open span:nth-child(2) {
			opacity: 0;
		}

		.menu-toggle.open span:nth-child(3) {
			transform: rotate(-45deg) translateY(-8px);
		}

		.nav-dropdown-trigger {
			pointer-events: none;
			opacity: 0.7;
		}

		.dropdown-caret {
			display: none;
		}

		.nav-dropdown {
			position: static;
			opacity: 1;
			visibility: visible;
			transform: none;
			margin: 0.25rem 0 0.5rem 1rem;
			border: none;
			background: none;
			padding: 0;
		}

		.nav-dropdown a {
			padding: 0.4rem 0;
			font-size: 0.9rem;
		}
	}
</style>
