---
import Layout from '../layouts/Layout.astro';
import mockServerScript from '../assets/js/mock-server.js?raw';
import Sidebar from '../components/Sidebar.astro';
import TableOfContents from '../components/TableOfContents.astro';
import Breadcrumbs from '../components/Breadcrumbs.astro';
import PageHeader from '../components/PageHeader.astro';
import Pagination from '../components/Pagination.astro';
import FinderLink from '../components/FinderLink.astro';
import { getFolder, render, COLLECTIONS, hasSubfolderPages } from '../lib/content';
import { buildDocsSidebar } from '../lib/docs-sidebar';
import { EXTENSION_CATEGORIES, PATTERN_CATEGORIES, buildCategorySidebar } from '../lib/content-groups';

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 }
            });
        });

        // Inline subfolders are listed on their collection root, not as pages.
        if (hasSubfolderPages(collection)) {
            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, headings: pageHeadings} = await render(page);
const {title, description, keywords, icon} = page.frontmatter;

// Display flags
const isReference = collection === 'reference';
const isReferenceIndex = isCollectionRootPage && isReference;
const isPatternsIndex = isCollectionRootPage && collection === 'patterns';
const isExtensionsIndex = isCollectionRootPage && collection === 'extensions';
const isEssaysIndex = isCollectionRootPage && collection === 'essays';
const isDocsRoot = isCollectionRootPage && collection === 'docs';
const flatSidebarCategories = collection === 'extensions'
    ? EXTENSION_CATEGORIES
    : collection === 'patterns'
        ? PATTERN_CATEGORIES
        : null;
const includeSidebar = isDocsRoot
    || (!!(folder?.folders?.length || (flatSidebarCategories && folder?.files?.length))
        && !isReferenceIndex && !isPatternsIndex && !isExtensionsIndex);
const includeHeader = !isHomePage;
const includeMockServer = file?.frontmatter?.includeMockServer === true;
const includePagination = !isCollectionRootPage && !isSubfolderIndexPage && !!(file?.prev || file?.next);
const useWideLayout = (isCollectionRootPage || isSubfolderIndexPage) && collection === 'about';

let headings: any[] = isHomePage ? [] : pageHeadings;
let sidebarFolder = folder!;
if (isDocsRoot) {
    ({headings, sidebar: sidebarFolder} = await buildDocsSidebar(folder));
}

if (flatSidebarCategories) {
    sidebarFolder = buildCategorySidebar(folder, flatSidebarCategories);
}
const includeTableOfContents = headings.length > 0;
const editPageUrl = `https://github.com/bigskysoftware/htmx/edit/four-dev/www/src/content/${page.path}`;
---

<Layout title={title}
        description={description}
        keywords={keywords}
        article={!isCollectionRootPage ? {
            publishedTime: file?.frontmatter.created?.toISOString(),
            modifiedTime: file?.frontmatter.modified?.toISOString(),
            authors: file?.frontmatter.authors,
            tags: file?.frontmatter.tags,
        } : undefined}
        breadcrumbs={page.breadcrumbs}
        hasSidebar={includeSidebar}>

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

    <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 transition", useWideLayout ? 'max-w-4xl' : 'max-w-prose']}>
                    <Breadcrumbs breadcrumbs={page.breadcrumbs} />

                    {includeHeader && <PageHeader {title} {description} {icon} file={file ?? (isDocsRoot ? folder : undefined)} {collection} />}

                    <article class:list={["prose prose-htmx prose-sm sm:prose-base dark:prose-invert max-w-none", (isDocsRoot || isReferenceIndex || isEssaysIndex || isPatternsIndex || isExtensionsIndex) && "sticky-headers"]}>
                        {includeMockServer && <script is:inline set:html={mockServerScript}></script>}
                        <Content/>
                        {includePagination && <Pagination prev={file!.prev} next={file!.next} />}
                    </article>
                    {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 truncate">
                                                {f.frontmatter.description}
                                            </span>
                                        )}
                                    </span>
                                </FinderLink>
                            ))}
                        </nav>
                    )}
                </div>

                {includeTableOfContents && (
                        <aside class:list={[
                            "hidden xl:flex xl:flex-col xl:w-60 xl:min-w-60 shrink-0 xl:ml-16 self-start sticky top-(--header-height) max-h-[calc(100vh-var(--header-height))] pt-27 pb-8 pr-4",
                            includeSidebar ? "xl:-me-16" : "xl:-me-[19rem]",
                        ]}>
                            <div class="shrink-0 mb-4">
                                <h2 class="text-tertiary">
                                    On this page
                                </h2>
                            </div>
                            <div class="min-h-0 overflow-hidden">
                                <div class="max-h-[calc(100vh-var(--header-height)-12rem)] overflow-y-auto scrollbar-subtle">
                                    <TableOfContents {headings}/>
                                </div>
                            </div>
                            <nav class="mt-4 pt-4 border-t border-neutral-100 dark:border-neutral-900" aria-label="Page actions">
                                <a href={editPageUrl}
                                   target="_blank"
                                   rel="noopener noreferrer"
                                   class="group flex items-center gap-2.5 rounded-sm text-[13px] font-medium text-neutral-600 dark:text-neutral-400 interact:text-blue-600 dark:interact:text-blue-300 interact:underline outline-hidden">
                                    <i class="icon-[mdi--pencil] size-3.5" aria-hidden="true"></i>
                                    <span>Edit page</span>
                                </a>
                            </nav>
                        </aside>
                )}
            </div>
        </main>
    </div>

</Layout>
