---
import { readdir, readFile } from 'node:fs/promises';
const { default: Default } = await import('../layouts/Default.astro');

type Frontmatter = Record<string, unknown>;

interface PageProps {
	frontmatter: Frontmatter;
}

const title = 'Table of Contents'
const allPages = await readdir('src/pages');
const pages = allPages.filter((p) => (
	!p.startsWith('index.')
	&& !p.endsWith('.astro')
	&& p.endsWith('.mdx')
));

const pagesContentImported = await Promise.all(
	pages.map(async (p) => {
		const fileBuffer = await readFile(`src/pages/${p}`);
		const file = fileBuffer.toString('utf-8');

		const [, frontmatterRaw] = file.split('---');
		const frontmatterLines = (frontmatterRaw?.split('\n') ?? []) as string[];
		const frontmatter = Object.fromEntries(
			frontmatterLines.map(l => l.split(':').map((s) => s.trim()))
		) as Frontmatter;
		return [
			p.replace('.mdx', '.html'),
			{
				frontmatter,
			},
		] as [string, PageProps];
	})
) as [string, PageProps][];
---
<Default title={title}>
	<ol>
		{pagesContentImported.map(([p, f]) => (
			<li>
				<a href={p.replace('.mdx', '')}>
					{f.frontmatter.title}
				</a>
			</li>
		))}
	</ol>
</Default>
