---
import type { MarkdownHeading } from 'astro';
import { render } from 'astro:content';
import DocsContextLayout from '../layouts/DocsContextLayout.astro';
import SplashLayout from '../layouts/SplashLayout.astro';
import TextLayout from '../layouts/TextLayout.astro';
import PageAside from 'virtual:prosefly/lotus/components/PageAside';
import PageHeader from 'virtual:prosefly/lotus/components/PageHeader';
import PageMeta from 'virtual:prosefly/lotus/components/PageMeta';
import PageNavigation from 'virtual:prosefly/lotus/components/PageNavigation';
import { getEntryContributors } from '../lib/contributors';
import {
  getDocsContext,
  createDocsNavigationHandoff,
  getEntrySectionFromContext,
  getEntrySlug,
  getSidebarPagination,
  getSidebarSectionTitle,
} from '../lib/docs';
import {
  getLocalizedHref,
  getLocalizedMarkdownHref,
  getLocales,
  getRouteSlugForLocalizedSlug,
} from '../lib/i18n';
import { getEntryLastUpdated } from '../lib/page/last-updated';
import type { HeadConfig } from '../lib/page/head';
import { createDocsJsonLd } from '../lib/page/schema';
import { resolveEditUrl } from '../lib/page/edit-link';
import { isPagefindSearchEnabled } from '../lib/search';
import rawThemeConfig from 'virtual:prosefly/lotus/config';
import type { LotusThemeConfig } from '../lib/theme';

function getTableOfContentsHeadings(
  headings: MarkdownHeading[],
  tableOfContents: false | { minHeadingLevel?: number; maxHeadingLevel?: number } | undefined,
): MarkdownHeading[] {
  if (tableOfContents === false) {
    return [];
  }

  const minHeadingLevel = tableOfContents?.minHeadingLevel ?? 2;
  const maxHeadingLevel = tableOfContents?.maxHeadingLevel ?? 3;

  return headings.filter(
    (heading) =>
      heading.slug !== 'footnote-label' &&
      heading.depth >= minHeadingLevel &&
      heading.depth <= maxHeadingLevel,
  );
}

export async function getStaticPaths() {
  const themeConfig = rawThemeConfig as LotusThemeConfig;
  const locales = getLocales(themeConfig);
  const paths = await Promise.all(locales.map(async (currentLocale) => {
    const docsContext = await getDocsContext(undefined, currentLocale.key);

    return docsContext.entries.map((entry) => {
      const entrySlug = getEntrySlug(entry);
      const currentSection = getEntrySectionFromContext(docsContext, entry);

      return {
        params: {
          slug: getRouteSlugForLocalizedSlug({
            locale: currentLocale,
            slug: entrySlug,
          }),
        },
        props: {
          entry,
          currentLocale,
          docsNavigation: createDocsNavigationHandoff(docsContext, currentSection),
        },
      };
    });
  }));

  return paths.flat();
}

const { entry, currentLocale, docsNavigation } = Astro.props;
const currentSection = docsNavigation.currentSection;
const { Content, headings } = await render(entry);
const tocHeadings = getTableOfContentsHeadings(
  headings as MarkdownHeading[],
  entry.data.tableOfContents,
);
const isTextTemplate = entry.data.template === 'text';
const isSplashTemplate = entry.data.template === 'splash';
const subnav = docsNavigation.sections;
const sidebars = docsNavigation.sidebars;
const sidebar = currentSection ? sidebars[currentSection] ?? { links: [], groups: [] } : { links: [], groups: [] };
const entrySlug = getEntrySlug(entry);
const sectionTitle = getSidebarSectionTitle(sidebar, entrySlug);
const themeConfig = rawThemeConfig as LotusThemeConfig;
const editUrl = resolveEditUrl(themeConfig, entry);
const contributors = await getEntryContributors(themeConfig, entry);
const lastUpdated = await getEntryLastUpdated(entry);
const pageNavigation = getSidebarPagination(sidebar, entrySlug, {
  previous: entry.data.prev,
  next: entry.data.next,
});
const docsRootHref = getLocalizedHref(themeConfig, 'index', currentLocale.key);
const currentPath = getLocalizedHref(themeConfig, entrySlug, currentLocale.key);
const markdownHref = getLocalizedMarkdownHref(themeConfig, entrySlug, currentLocale.key);
const baseUrl = Astro.site ?? Astro.url;
const pageUrl = currentPath;
const markdownUrl = markdownHref;
const schemaPageUrl = new URL(currentPath, baseUrl).toString();
const schemaMarkdownUrl = new URL(markdownHref, baseUrl).toString();
const pageActions = themeConfig.pageActions ?? [];
const activeSection = subnav.find((section) => section.active);
const breadcrumbs: { label: string; href: string }[] = [];
const pagefindIgnoreAttrs = isPagefindSearchEnabled(themeConfig)
  ? { 'data-pagefind-ignore': true }
  : {};
const docsHead: HeadConfig = [
  ...(entry.data.head ?? []),
  {
    tag: 'link',
    attrs: {
      rel: 'alternate',
      type: 'text/markdown',
      href: markdownHref,
      title: 'Markdown',
    },
  },
];

function addBreadcrumb(label: string | undefined, href: string | undefined) {
  if (!label || !href) {
    return;
  }

  const previous = breadcrumbs.at(-1);

  if (previous?.href === href) {
    breadcrumbs[breadcrumbs.length - 1] = { label, href };
    return;
  }

  breadcrumbs.push({ label, href });
}

addBreadcrumb(themeConfig.name, '/');

if (themeConfig.docsBase !== '/') {
  addBreadcrumb('Docs', docsRootHref);
}

addBreadcrumb(activeSection?.label, activeSection?.href);
addBreadcrumb(entry.data.title, currentPath);

const jsonLd = createDocsJsonLd({
  themeConfig,
  baseUrl,
  pageUrl: schemaPageUrl,
  title: entry.data.title,
  description: entry.data.description,
  sectionTitle,
  breadcrumbs,
  markdownUrl: schemaMarkdownUrl,
  lastUpdated,
});

---

{isSplashTemplate ? (
  <SplashLayout title={entry.data.title} description={entry.data.description} head={entry.data.head} hero={entry.data.hero} locale={currentLocale} pagefind={entry.data.pagefind}>
    <Content />
  </SplashLayout>
) : isTextTemplate ? (
  <TextLayout title={entry.data.title} description={entry.data.description} head={entry.data.head} locale={currentLocale} pagefind={entry.data.pagefind}>
    <Content />
  </TextLayout>
) : (
  <DocsContextLayout
    title={entry.data.title}
    description={entry.data.description}
    head={docsHead}
    jsonLd={jsonLd}
    locale={currentLocale}
    currentPath={currentPath}
    currentSection={currentSection}
    docsNavigation={docsNavigation}
    currentSlug={entrySlug}
    pagefind={entry.data.pagefind}
    headings={tocHeadings}
  >
    <div>
      <PageHeader
        description={entry.data.description}
        markdownUrl={markdownUrl}
        pageActions={pageActions}
        pageUrl={pageUrl}
        sectionTitle={sectionTitle}
        title={entry.data.title}
      />

      <div class="prose max-w-none py-8">
        <Content />
      </div>
    </div>

    <div class="xl:hidden" {...pagefindIgnoreAttrs}>
      <PageAside
        currentSlug={entrySlug}
        editUrl={editUrl}
        headings={tocHeadings}
        markdownUrl={markdownUrl}
        pageUrl={pageUrl}
        tableOfContents={false}
        title={entry.data.title}
      />
    </div>

    <div {...pagefindIgnoreAttrs}>
      <PageMeta
        contributors={contributors}
        lastUpdated={lastUpdated}
        title={entry.data.title}
      />
      <PageNavigation navigation={pageNavigation} />
    </div>

    <Fragment slot="aside">
      <PageAside
        currentSlug={entrySlug}
        editUrl={editUrl}
        headings={tocHeadings}
        markdownUrl={markdownUrl}
        pageUrl={pageUrl}
        title={entry.data.title}
      />
    </Fragment>

  </DocsContextLayout>
)}
