---
import Layout from '../layouts/Layout.astro';
import Demo from '../components/Demo.astro';
import Sidebar from '../components/Sidebar.astro';
import SidebarToggle from '../components/SidebarToggle.astro';
import TableOfContents from '../components/TableOfContents.astro';
import Breadcrumbs from '../components/Breadcrumbs.astro';
import PageHeader from '../components/PageHeader.astro';
import ReadingModeToggle from '../components/ReadingModeToggle.astro';
import Pagination from '../components/Pagination.astro';
import CollectionCards from '../components/CollectionCards.astro';
import FinderLink from '../components/FinderLink.astro';
import Header from '../components/Header.astro';
import Footer from '../components/Footer.astro';
import { getFolder, render, COLLECTIONS } from '../lib/content.ts';

export async function getStaticPaths() {
    const paths = [];

    for (const collection of COLLECTIONS) {
        const isHome = collection === 'home';
        const folder = await getFolder(collection);

        paths.push({
            params: { slug: isHome ? undefined : collection },
            props: { folder, collection }
        });

        folder.allFiles.forEach((file) => {
            paths.push({
                params: { slug: isHome ? file.slug : `${collection}/${file.slug}` },
                props: { file, folder, collection }
            });
        });

        // Reference subfolders are listed inline on /reference — no separate pages
        if (collection !== 'reference') {
            folder.folders.forEach((subfolder) => {
                paths.push({
                    params: { slug: `${collection}/${subfolder.slug}` },
                    props: { subfolder, folder, collection }
                });
            });
        }
    }

    return paths;
}

const { file, subfolder, folder, collection } = Astro.props;

const isCollectionRootPage = !file && !subfolder;
const isSubfolderIndexPage = !!subfolder;
const isHomePage = isCollectionRootPage && collection === 'home';
const page = isCollectionRootPage ? folder! : isSubfolderIndexPage ? subfolder! : file;

const {Content} = await render(page);
const {title, description, keywords} = page.frontmatter;

// Display flags
const isReference = collection === 'reference';
const isReferenceIndex = isCollectionRootPage && isReference;
const isPatternsIndex = isCollectionRootPage && collection === 'patterns';
const isExtensionsIndex = isCollectionRootPage && collection === 'extensions';
// Aggregate pages (slug `full`) skip the sidebar — the page IS the whole collection.
const isAggregate = !!file && file.slug === 'full' && !!folder?.folders?.length;
// Extensions is flat (no subfolders), but sibling navigation is useful, so show sidebar on inner pages.
const isFlatCollectionWithSidebar = collection === 'extensions';
const includeSidebar = !!(folder?.folders?.length || (isFlatCollectionWithSidebar && folder?.files?.length))
    && !isReferenceIndex && !isPatternsIndex && !isExtensionsIndex && !isAggregate;

// Reading-mode toggle: when the collection has an aggregate `full` page,
// surface a link between the split/index view and the single-page view on
// both sides. Pure link, no persistence.
const aggregateFile = folder?.allFiles?.find(f => f.slug === 'full');
const readingModeToggle = aggregateFile && (isCollectionRootPage || isAggregate)
    ? {
        splitHref: folder!.url,
        fullHref: aggregateFile.url,
        active: (isAggregate ? 'full' : 'split') as 'full' | 'split',
    }
    : null;
const includeHeader = !isHomePage;
const includeDemo = !isCollectionRootPage && !isSubfolderIndexPage && collection === 'patterns';
const includeCollectionCards = (isCollectionRootPage && ['docs'].includes(collection)) || isSubfolderIndexPage;
const includePagination = !isCollectionRootPage && !isSubfolderIndexPage && !!(file?.prev || file?.next);
const useWideLayout = (isCollectionRootPage || isSubfolderIndexPage) && ['about', 'docs'].includes(collection);

let headings: any[] = [];
if (file) {
    headings = (await render(file)).headings;
} else if (isReferenceIndex) {
    headings = folder!.folders.map(sub => ({ depth: 2, slug: sub.slug, text: sub.frontmatter.title }));
}
const includeTableOfContents = headings.length > 0;
---

<Layout title={title}
        description={description}
        keywords={keywords}
        type={!isCollectionRootPage ? 'article' : undefined}
        publishedTime={file?.frontmatter.created}
        modifiedTime={file?.frontmatter.modified}
        authors={file?.frontmatter.authors}
        articleTags={file?.frontmatter.tags}>

    <Header slot="header">
        {includeSidebar && <SidebarToggle />}
    </Header>

    {includeSidebar && <Sidebar folder={folder} file={file}/>}

    <div id="content-wrapper" class:list={[includeSidebar && "lg:pl-72"]}>
        <main id="content-main-content" class="flex-1" data-home-page={isHomePage ? '' : undefined}>
            <div class="w-full mx-auto px-4 sm:px-6 lg:px-8 flex justify-center max-w-360">

                <div class:list={["pt-6 sm:pt-8 lg:pt-12 flex-1 w-full relative starting:opacity-0 delay-150 transition", useWideLayout ? 'max-w-4xl' : 'max-w-prose']}>
                    <Breadcrumbs breadcrumbs={page.breadcrumbs} />

                    {readingModeToggle && (
                        <div class="mt-3 flex justify-end">
                            <ReadingModeToggle {...readingModeToggle} />
                        </div>
                    )}

                    {includeHeader && <PageHeader {title} description={isReferenceIndex ? undefined : description} {file} {collection} />}

                    <article class="prose prose-htmx prose-sm sm:prose-base dark:prose-invert max-w-none">
                        {includeDemo && <Demo />}
                        <Content/>
                        {includePagination && <Pagination prev={file!.prev} next={file!.next} />}
                    </article>
                    {includeCollectionCards && !isSubfolderIndexPage && <CollectionCards folders={folder!.folders.sort((a, b) => a.path.localeCompare(b.path))} {collection} />}
                    {isSubfolderIndexPage && (
                        <nav class="not-prose mt-4 flex flex-col gap-1">
                            {subfolder!.files.map((f) => (
                                <FinderLink href={f.url}>
                                    <span class="flex-1 min-w-0 flex flex-col sm:flex-row sm:items-center gap-0.5 sm:gap-4">
                                        <span class:list={["text-[13px] sm:text-sm leading-snug truncate", isReference && "font-mono"]} set:html={f.frontmatter.title} />
                                        {f.frontmatter.description && (
                                            <span class="text-[11px] text-neutral-500 dark:text-neutral-450 group-interact/link:text-blue-200 dark:group-interact/link:text-black transition truncate">
                                                {f.frontmatter.description}
                                            </span>
                                        )}
                                    </span>
                                </FinderLink>
                            ))}
                        </nav>
                    )}
                </div>

                {includeTableOfContents && (
                        <aside class:list={[
                            "hidden xl:flex xl:flex-col xl:w-60 shrink-0 xl:ml-16 self-start sticky top-(--header-height) h-[calc(100vh-var(--header-height))] pt-27 pb-8 pr-4",
                            includeSidebar ? "xl:-me-16" : "xl:-me-[19rem]",
                        ]}>
                            <div class="shrink-0 mb-2">
                                <h2 class="text-[0.675rem] font-sans tracking-wide uppercase text-neutral-500">
                                    On this page
                                </h2>
                            </div>
                            <div class="flex-1 min-h-0 overflow-hidden">
                                <div class="h-full overflow-y-auto scrollbar-subtle">
                                    <TableOfContents {headings}/>
                                </div>
                            </div>
                        </aside>
                )}
            </div>
        </main>
    </div>

    <Footer slot="footer"
            class:list={[includeSidebar && "lg:pl-72"]}
            containerClass="px-4 sm:px-6 lg:px-12 xl:px-8"
            contentClass="mx-auto max-w-4xl"
    />
</Layout>
