---
import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
import ChangelogEntries from '@components/ChangelogEntries.astro';
import { getCollection } from 'astro:content';
import { sidebar } from '../../../astro.config.mjs';

export const prerender = true;

const entries = await getCollection('changelog');

// Sort by version descending, with non-semver entries (e.g. "Unreleased") always first
entries.sort((a, b) => {
	const aIsVersion = a.data.version.startsWith("v");
	const bIsVersion = b.data.version.startsWith("v");
	if (!aIsVersion && bIsVersion) return -1;
	if (aIsVersion && !bIsVersion) return 1;
	return b.data.version.localeCompare(a.data.version, undefined, { numeric: true });
});

// Build TOC headings: version (H2) + categories (H3) for each entry
const headings: { depth: number; slug: string; text: string }[] = [];

for (const entry of entries) {
	const version = entry.data.version;
	headings.push({ depth: 2, slug: version, text: version });

	// Extract ### headings (categories) from the body
	const categoryLines = entry.body?.match(/^### .+/gm) ?? [];
	for (const line of categoryLines) {
		const text = line.replace(/^### /, '');
		const slug = text
			.toLowerCase()
			.replace(/[^\w\s-]/g, '')
			.trim()
			.replace(/\s+/g, '-');
		headings.push({ depth: 3, slug, text });
	}
}

headings.push({ depth: 2, slug: 'prior-releases', text: 'Prior Releases' });
---

<StarlightPage
	frontmatter={{
		title: 'Changelog',
		description: 'A log of notable changes to Terragrunt.',
	}}
	headings={headings}
	sidebar={sidebar}
>
	<p>This page tracks notable changes to Terragrunt. For the full list of releases and their assets, see the <a href="https://github.com/gruntwork-io/terragrunt/releases">GitHub Releases Page</a>.</p>
	<hr />
	<ChangelogEntries />
	<h2 id="prior-releases">Prior Releases</h2>
	<p>For all prior releases, see the <a href="https://github.com/gruntwork-io/terragrunt/releases">GitHub Releases Page</a>.</p>
</StarlightPage>
