---
import { getLanguageFromURL } from "../../languages";
import { SIDEBAR } from "../../consts";

type Props = {
	currentPage: string;
};

const { currentPage } = Astro.props as Props;
const currentPageMatch = currentPage.endsWith("/")
	? currentPage.slice(1, -1)
	: currentPage.slice(1);
const langCode = getLanguageFromURL(currentPage);
const sidebar = SIDEBAR[langCode];
---

<nav aria-labelledby="grid-left">
	<ul class="nav-groups">
		{
			Object.entries(sidebar).map(([header, children]) => (
				<li class:list={["nav-group"]}>
					<h2 class="nav-group-title">{header}</h2>
					<ul>
						{children.map((child) => {
							const url = Astro.site?.pathname + child.link;
							return (
								<li class="nav-link">
									<a
										href={url}
										aria-current={
											currentPageMatch === child.link ? "page" : false
										}
									>
										{child.text}
									</a>
								</li>
							);
						})}
					</ul>
				</li>
			))
		}
	</ul>
</nav>

<script is:inline>
	window.addEventListener("DOMContentLoaded", () => {
		var target = document.querySelector('[aria-current="page"]');
		if (target && target.offsetTop > window.innerHeight - 100) {
			document.querySelector(".nav-groups").scrollTop = target.offsetTop;
		}
	});
</script>

<style>
	nav {
		width: 100%;
		margin-right: 1rem;
	}

	.nav-groups {
		height: 100%;
		padding: 2rem 0;
		overflow-x: visible;
		overflow-y: auto;
		max-height: 100vh;
	}

	.nav-groups > li + li {
		margin-top: 2rem;
	}

	.nav-groups > :first-child {
		padding-top: var(--doc-padding);
	}

	.nav-groups > :last-child {
		padding-bottom: 2rem;
		margin-bottom: var(--theme-navbar-height);
	}

	.nav-group-title {
		font-size: 1em;
		font-weight: 700;
		margin: 0;
	}

	.nav-link a {
		font-size: 1rem;
		margin: 1px;
		padding: 0.3rem 1rem;
		font: inherit;
		color: var(--color-text-lighter);
		text-decoration: none;
		display: block;
	}

	.nav-link a:hover,
	.nav-link a:focus {
		background-color: var(--theme-bg-accent);
	}

	.nav-link a[aria-current="page"] {
		color: var(--theme-text);
		background-color: var(--theme-bg-accent);
		font-weight: 500;
	}

	@media (min-width: 50em) {
		.nav-groups {
			padding: 0;
		}
		.nav-group-title,
		.nav-link a {
			padding: 0.2rem 1rem;
		}
	}
</style>

<style is:global>
	:root.theme-dark .nav-link a {
		color: hsla(var(--color-gray-70), 1);
	}
	:root.theme-dark .nav-link a[aria-current="page"] {
		color: var(--theme-text);
	}
</style>
