---
import { getCollection, render } from 'astro:content';
import DocsLayout from '@/layouts/DocsLayout.astro';
import { DocsNavigation } from '@/components/DocsNavigation';
import { DocsTableOfContents } from '@/components/DocsTableOfContents';
import { DocsPageDropdown } from '@/components/DocsPageDropdown';
import { Prose } from '@/components/Prose';
import { Button } from '@rivet-gg/components';
import { Icon, faPencil } from '@rivet-gg/icons';
import { sitemap } from '@/sitemap/mod';
import { findActiveTab } from '@/lib/sitemap';
import { getContentParamSlug, getContentSlugPath } from '@/lib/content-path';
import * as mdxComponents from '@/components/mdx';

export async function getStaticPaths() {
	const docs = await getCollection('docs');
	return docs.map((entry) => {
		const slug = getContentParamSlug(entry.id);
		return {
			params: { slug },
			props: { entry },
		};
	});
}

const { entry } = Astro.props;
const { Content, headings, remarkPluginFrontmatter } = await render(entry);

// Format last modified date
const lastModified = remarkPluginFrontmatter?.lastModified;
const lastModifiedFormatted = lastModified
	? new Date(lastModified).toLocaleDateString('en-US', {
			year: 'numeric',
			month: 'long',
			day: 'numeric',
		})
	: null;

// Build table of contents from headings
const tableOfContents = headings
	.filter((h) => h.depth === 2 || h.depth === 3)
	.reduce((acc, h) => {
		if (h.depth === 2) {
			acc.push({ title: h.text, id: h.slug, children: [] });
		} else if (acc.length > 0) {
			acc[acc.length - 1].children.push({ title: h.text, id: h.slug, children: [] });
		}
		return acc;
	}, [] as Array<{ title: string; id: string; children: Array<{ title: string; id: string; children: never[] }> }>);

const { title, description } = entry.data as { title: string; description: string };
const slugPath = getContentSlugPath(entry.id);
const fullPath = slugPath ? `/docs/${slugPath}/` : '/docs/';
const foundTab = findActiveTab(fullPath, sitemap);
const parentPage = foundTab?.page?.parent;
const canonicalUrl = `https://rivet.dev${fullPath}`;

// Create markdown path for the dropdown
const markdownPath = slugPath ? `docs/${slugPath}` : 'docs';
const componentSourcePath = `docs/${entry.id}.mdx`;

// Build BreadcrumbList schema
const breadcrumbItems = [
	{ name: "Home", url: "https://rivet.dev/" },
	{ name: "Docs", url: "https://rivet.dev/docs/" },
];
if (parentPage) {
	breadcrumbItems.push({ name: parentPage.title, url: `https://rivet.dev${parentPage.href || '/docs/'}` });
}
if (slugPath) {
	breadcrumbItems.push({ name: title, url: canonicalUrl });
}

const breadcrumbSchema = {
	"@context": "https://schema.org",
	"@type": "BreadcrumbList",
	"itemListElement": breadcrumbItems.map((item, index) => ({
		"@type": "ListItem",
		"position": index + 1,
		"name": item.name,
		"item": item.url
	}))
};
---

<DocsLayout title={`${title} - Rivet`} description={description} canonicalUrl={canonicalUrl} sidebar={foundTab?.tab?.sidebar}>
	<script type="application/ld+json" set:html={JSON.stringify(breadcrumbSchema)} />
	<aside class="hidden md:block border-r">
		{foundTab?.tab?.sidebar && <DocsNavigation sidebar={foundTab.tab.sidebar} client:load />}
	</aside>
	<div class="flex justify-center w-full min-w-0">
		<div class="flex gap-8 max-w-6xl w-full min-w-0">
			<main class="w-full py-8 px-8 lg:mx-0 mx-auto max-w-prose-docs lg:max-w-none min-w-0">
				<div class="relative flex justify-end">
					<div class={`flex items-end md:absolute md:right-0 ${parentPage ? 'md:top-5' : 'md:top-0'}`}>
						<DocsPageDropdown
							title={title || 'Documentation'}
							markdownPath={markdownPath}
							currentUrl={fullPath}
							client:load
						/>
					</div>
				</div>
				<Prose as="article" className="max-w-prose-docs lg:max-w-prose-docs mx-auto [&>h1:first-of-type]:pr-44">
					{parentPage && (
						<div class="eyebrow h-5 text-primary text-sm font-semibold">
							{parentPage.title}
						</div>
					)}
					<h1>{title}</h1>
					{description && <p>{description}</p>}
					<Content components={mdxComponents} />
				</Prose>
				<div class="border-t mt-12 pt-6 flex flex-wrap items-center justify-between gap-4">
					<Button variant="outline" size="sm" asChild>
						<a
							href={`https://github.com/rivet-dev/rivet/edit/main/website/src/content/${componentSourcePath}`}
							target="_blank"
							rel="noreferrer"
						>
							<Icon icon={faPencil} />
							Edit this page
						</a>
					</Button>
					{lastModifiedFormatted && (
						<span class="text-xs text-muted-foreground">
							Last updated {lastModifiedFormatted}
						</span>
					)}
				</div>
			</main>
			{tableOfContents.length > 0 && (
				<aside class="hidden xl:block w-64 min-w-0 flex-shrink-0 pb-4">
					<DocsTableOfContents className="lg:max-h-content" tableOfContents={tableOfContents} client:load />
				</aside>
			)}
		</div>
	</div>
</DocsLayout>
