---
import type { CollectionEntry } from 'astro:content';
import { type Locale, SITE } from '~/consts';
import {
	aboutSegment,
	categoryIndexSegment,
	entryHref,
	findTagBySlug,
	findTranslation,
	tagHref,
	tagIndexSegment,
	tagSegment,
} from '~/i18n/posts';
import { getLocaleFromUrl, localizePath, switchLocalePath, t } from '~/i18n/ui';
import HeaderLink from '~/components/HeaderLink.astro';

interface Props {
	locale?: Locale;
	/** The current page's content entry, if any — used to resolve a translated language-switch link. */
	entry?: CollectionEntry<'posts' | 'categories'>;
}

const { entry } = Astro.props;
const locale: Locale = Astro.props.locale ?? getLocaleFromUrl(Astro.url);
const otherLocale: Locale = locale === 'de' ? 'en' : 'de';
const homeHref = localizePath('/', locale);
const aboutHref = localizePath(`/${aboutSegment(locale)}`, locale);
const categoriesHref = localizePath(`/${categoryIndexSegment(locale)}`, locale);
const tagsHref = localizePath(`/${tagIndexSegment(locale)}`, locale);

const translated = entry ? await findTranslation(entry, otherLocale) : undefined;

// If we're on a tag detail page, verify the tag exists in the target locale —
// otherwise the switched URL would 404. Fall back to the target tags index.
async function resolveSwitchHref(): Promise<string> {
	if (translated) return entryHref(translated);
	if (entry) return localizePath('/', otherLocale);
	const parts = Astro.url.pathname.split('/').filter(Boolean);
	const localePrefix = parts[0] === locale ? 1 : 0;
	const first = parts[localePrefix];
	const slug = parts[localePrefix + 1];
	if (first === tagSegment(locale) && slug) {
		const target = await findTagBySlug(otherLocale, slug);
		return target
			? tagHref(otherLocale, target)
			: localizePath(`/${tagIndexSegment(otherLocale)}`, otherLocale);
	}
	return switchLocalePath(Astro.url.pathname, otherLocale);
}
const switchHref = await resolveSwitchHref();
---

<header>
	<nav>
		<h2><a href={homeHref}>{SITE[locale].title}</a></h2>
		<div class="internal-links" id="mobile-menu">
			<HeaderLink href={homeHref}>{t(locale, 'nav.home')}</HeaderLink>
			<HeaderLink href={aboutHref}>{t(locale, 'nav.about')}</HeaderLink>
			<HeaderLink href={categoriesHref}>{t(locale, 'nav.categories')}</HeaderLink>
			<HeaderLink href={tagsHref}>{t(locale, 'nav.tags')}</HeaderLink>
		</div>
		<div class="toolbar">
		<a
			class={`lang-toggle lang-toggle--${locale}`}
			href={switchHref}
			hreflang={otherLocale}
			lang={otherLocale}
			aria-label={t(locale, `lang.${otherLocale}`)}
		>
			<span class="lang-toggle__thumb" aria-hidden="true"></span>
			<span class={`lang-toggle__label${locale === 'de' ? ' is-active' : ''}`}>DE</span>
			<span class={`lang-toggle__label${locale === 'en' ? ' is-active' : ''}`}>EN</span>
		</a>
		<button class="menu-toggle" type="button" aria-label="Menu" aria-controls="mobile-menu" aria-expanded="false">
			<span class="menu-toggle__bar"></span>
			<span class="menu-toggle__bar"></span>
			<span class="menu-toggle__bar"></span>
		</button>
		</div>
	</nav>
</header>

<script>
	import { navigate } from 'astro:transitions/client';
	function wireLangToggle() {
		const toggle = document.querySelector<HTMLAnchorElement>('.lang-toggle');
		if (!toggle || toggle.dataset.wired) return;
		toggle.dataset.wired = '1';
		toggle.addEventListener('click', (e) => {
			if (e.metaKey || e.ctrlKey || e.shiftKey || (e as MouseEvent).button === 1) return;
			const href = toggle.getAttribute('href');
			if (!href) return;
			e.preventDefault();
			toggle.classList.add('is-switching');
			window.setTimeout(() => navigate(href), 280);
		});
	}
	function wireMenuToggle() {
		const btn = document.querySelector<HTMLButtonElement>('.menu-toggle');
		const menu = document.getElementById('mobile-menu');
		const header = document.querySelector<HTMLElement>('header');
		if (!btn || !menu || !header || btn.dataset.wired) return;
		btn.dataset.wired = '1';
		const nav = header.querySelector('nav');
		const mq = window.matchMedia('(max-width: 960px)');
		const syncLocation = () => {
			if (mq.matches) {
				if (menu.parentElement !== document.body) document.body.appendChild(menu);
			} else {
				if (menu.parentElement !== nav) nav!.insertBefore(menu, nav!.children[1] ?? null);
			}
		};
		syncLocation();
		mq.addEventListener('change', syncLocation);
		const setScrollbarCompensation = (on: boolean) => {
			if (on) {
				const sbw = window.innerWidth - document.documentElement.clientWidth;
				document.documentElement.style.setProperty('--scrollbar-width', `${sbw}px`);
			} else {
				document.documentElement.style.removeProperty('--scrollbar-width');
			}
		};
		const close = () => {
			header.classList.remove('is-menu-open');
			menu.classList.remove('is-open');
			btn.setAttribute('aria-expanded', 'false');
			setScrollbarCompensation(false);
		};
		btn.addEventListener('click', () => {
			const willOpen = !header.classList.contains('is-menu-open');
			if (willOpen) setScrollbarCompensation(true);
			const open = header.classList.toggle('is-menu-open');
			menu.classList.toggle('is-open', open);
			btn.setAttribute('aria-expanded', String(open));
			if (!open) setScrollbarCompensation(false);
		});
		menu.querySelectorAll('a').forEach((a) => a.addEventListener('click', close));
		document.addEventListener('astro:after-swap', close);
	}
	wireLangToggle();
	wireMenuToggle();
	document.addEventListener('astro:page-load', () => {
		wireLangToggle();
		wireMenuToggle();
	});
</script>
<style>
	header {
		position: relative;
		z-index: 50;
		margin: 0;
		padding: 0 1em;
		background: rgb(var(--surface));
		box-shadow: 0 2px 8px rgba(var(--black), 5%);
	}
	h2 {
		margin: 0;
		font-size: 1em;
		text-align: left;
	}
	nav > h2 a {
		display: block;
		padding: 1em 0;
		text-align: left;
	}

	h2 a,
	h2 a.active {
		text-decoration: none;
	}
	nav {
		display: grid;
		grid-template-columns: auto 1fr auto;
		align-items: center;
		gap: 1em;
	}
	nav > h2 {
		justify-self: start;
		position: relative;
		z-index: 50;
	}
	nav > .internal-links {
		justify-self: center;
	}
	nav > .toolbar {
		justify-self: end;
		position: relative;
		z-index: 50;
	}
	nav a {
		padding: 1em 0.5em;
		color: var(--black);
		border-bottom: 4px solid transparent;
		text-decoration: none;
	}
	nav a.active {
		text-decoration: none;
		border-bottom-color: var(--accent);
	}
	nav a.lang-toggle {
		position: relative;
		display: inline-flex;
		align-items: stretch;
		padding: 3px;
		margin: 0;
		background: rgba(var(--gray-light), 0.7);
		border: 0;
		border-radius: 999px;
		font-size: 0.75em;
		font-weight: 700;
		line-height: 1;
		font-variant-numeric: tabular-nums;
		font-feature-settings: 'tnum';
		user-select: none;
	}
	nav a.lang-toggle:hover {
		background: rgba(var(--gray-light), 1);
	}
	.lang-toggle__thumb {
		position: absolute;
		top: 3px;
		bottom: 3px;
		left: 3px;
		width: calc(50% - 3px);
		border-radius: 999px;
		background: var(--accent);
		box-shadow: 0 1px 3px rgba(var(--black), 0.18);
		transition: transform 280ms cubic-bezier(0.4, 0, 0.2, 1);
	}
	.lang-toggle--en .lang-toggle__thumb {
		transform: translateX(100%);
	}
	.lang-toggle--de.is-switching .lang-toggle__thumb {
		transform: translateX(100%);
	}
	.lang-toggle--en.is-switching .lang-toggle__thumb {
		transform: translateX(0);
	}
	.lang-toggle__label {
		position: relative;
		z-index: 1;
		display: block;
		flex: 1;
		width: 2.2em;
		padding: 0.6em 0 0.5em;
		text-align: center;
		color: rgb(var(--gray));
		transition: color 280ms ease;
	}
	.lang-toggle__label.is-active {
		color: white;
	}
	.lang-toggle.is-switching .lang-toggle__label.is-active {
		color: rgb(var(--gray));
	}
	.lang-toggle.is-switching .lang-toggle__label:not(.is-active) {
		color: white;
	}
	@media (prefers-reduced-motion: reduce) {
		.lang-toggle__thumb,
		.lang-toggle__label {
			transition: none;
		}
	}
	.toolbar {
		display: flex;
		align-items: center;
		gap: 0.6em;
	}
	.menu-toggle {
		display: none;
		margin-left: 0.8em;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		gap: 4px;
		width: 2.1em;
		height: 2.1em;
		padding: 0;
		border: 0;
		background: rgba(var(--gray-light), 0.7);
		border-radius: 999px;
		cursor: pointer;
	}
	.menu-toggle:hover {
		background: rgba(var(--gray-light), 1);
	}
	.menu-toggle__bar {
		display: block;
		width: 1em;
		height: 2px;
		background: rgb(var(--gray-dark));
		border-radius: 1px;
		transition:
			transform 260ms cubic-bezier(0.4, 0, 0.2, 1),
			opacity 180ms ease;
	}
	header.is-menu-open .menu-toggle__bar:nth-child(1) {
		transform: translateY(6px) rotate(45deg);
	}
	header.is-menu-open .menu-toggle__bar:nth-child(2) {
		opacity: 0;
	}
	header.is-menu-open .menu-toggle__bar:nth-child(3) {
		transform: translateY(-6px) rotate(-45deg);
	}
	@media (max-width: 960px) {
		.menu-toggle {
			display: inline-flex;
		}
		nav {
			grid-template-columns: auto 1fr;
		}
		.internal-links {
			position: fixed;
			top: 0;
			left: 0;
			right: var(--scrollbar-width, 0px);
			bottom: 0;
			box-sizing: border-box;
			z-index: 40;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			gap: 0.5em;
			background: rgb(var(--surface));
			padding: 2em;
			opacity: 0;
			pointer-events: none;
			transition: opacity 220ms ease;
		}
		.internal-links a {
			padding: 0.5em 0;
			border-bottom: none;
			font-size: 1.5em;
			text-align: center;
			color: var(--black);
			text-decoration: none;
		}
		.internal-links.is-open {
			opacity: 1;
			pointer-events: auto;
		}
		body:has(header.is-menu-open) {
			overflow: hidden;
			padding-right: var(--scrollbar-width, 0px);
		}
	}
</style>
