---
import type { GetStaticPaths } from "astro";
import BasicLayout from "@/layouts/BasicLayout.astro";
import { getRelativeLocaleUrl } from "astro:i18n";
import { getCollection } from "astro:content";

export const getStaticPaths = (async () => {
	const docs = await getCollection("distroGuide");

	const langs = docs.reduce((prev, curr) => {
		const lang = curr.id.split("/")[0];
		prev.add(lang);
		return prev;
	}, new Set<string>());

	return Array.from(langs).map((v) => ({
		params: {
			lang: v,
		},
	}));
}) satisfies GetStaticPaths;

const { lang } = Astro.params;

const docs = await getCollection("distroGuide");
const distroQuiz =
	(await getCollection("distroQuiz")).find((v) => v.id === lang)?.data
		.dialogs ?? [];

type Tree = { [key: string]: Tree | string };

const tree: Tree = {};

// Inspired from https://stackoverflow.com/a/62740661/14512055
function buildTree(list: any[]) {
	for (const doc of list) {
		let ptr = tree;
		const [docLang, ...slug] = doc.id.split("/");

		if (docLang !== lang) continue;

		const last = slug.pop() ?? "";

		for (const part of slug) {
			ptr = ptr[part] = (ptr[part] as Tree) || {};
		}

		ptr[last] = /[0-9]+/.test(last) ? doc.data.title : {};
	}
}

buildTree(docs);

tree["distroquiz"] = {};
for (let i = 0; i < distroQuiz.length; i++) {
	tree["distroquiz"][i.toString()] = distroQuiz[i].title;
}

function visualizeTree(tree: Tree, key: string | null, prefix: string): string {
	const subcategories = [];
	const children = [];

	for (const key in tree) {
		const value = tree[key];

		if (typeof value === "string") {
			children.push(`<li>
                <a href="${`/${lang}/distro/${prefix}${key}`}">${value}</a>    
            </li>`);
		} else {
			subcategories.push(visualizeTree(value, key, `${prefix}${key}/`));
		}
	}

	if (key === null) {
		return `<div>
            ${subcategories.join("")}
            <ul>${children.join("")}</ul>
        </div>`;
	}

	return `<details>
        <summary>${key}</summary>
        ${subcategories.join("")}
        <ul>${children.join("")}</ul>
    </details>`;
}

const visualization = visualizeTree(tree, null, "");
---

<BasicLayout title="Table of Contents">
	<main class="mx-16 my-8">
		<Fragment set:html={visualization} />
	</main>
</BasicLayout>

<style>
	@reference "@/styles/global.css";

	:global(ul) {
		@apply list-disc ps-8;
	}

	:global(a) {
		@apply border-b border-b-gray-400 dark:border-b-slate-400 no-underline!;
	}

	:global(details) {
		@apply px-4 py-2 my-2 border dark:border-slate-700 border-gray-300 rounded;
	}
</style>
