---
import { getCollection, render } from 'astro:content';
import { metadata } from '../include/SiteConfig.js';

import '../css/page.css';
import Html from '../layouts/Html.astro';
import Sidebar from '../components/Sidebar.astro';
import Subsections from '../components/Subsections.astro';
import PrevNext from '../components/PrevNext.astro';
import Footer from '../components/Footer.astro';
import PageNavi from '../components/PageNavi.astro';
import Search from '../components/Search.astro';
import FootnoteTooltips from '../components/FootnoteTooltips.astro';
import Scripts from '../components/Scripts.astro';
import Banner from '../components/Banner.astro';

export async function getAllPages() {
  const pages = await getCollection('pages');
  const special = await getCollection('special');
  const annotated = await getCollection('annotated');
  return [pages, special, annotated].flat();
}

export async function getStaticPaths() {
  // Serve pages according to their frontmatter paths
  return (await getAllPages()).map((page) => ({
    params: { path: page.data.path },
    props: { page },
  }));
}

// Put pages that have undefined sequence numbers (e.g. '/404/' and '/') at the end
const allPages = (await getAllPages()).sort(
  (a, b) => (a.data.sequence ?? 10000) - (b.data.sequence ?? 10000),
);

const { page } = Astro.props;

const frontmatter = page.data;
const indexArray = frontmatter.index;

var pageTitle = metadata.title;
if (frontmatter.titles !== undefined) {
  const titles = frontmatter.titles.filter((x) => x !== '');
  const number = indexArray.length >= 2 ? indexArray.join('.') + ' ' : '';
  pageTitle += ' | ' + number + titles[titles.length - 1];
}

const pageUrl = metadata.hostname + '/' + metadata.version + frontmatter.path;
const canonical =
  metadata.canonical + (frontmatter.hide ? '/' : frontmatter.path);
const path = frontmatter.path;
const index = frontmatter.index;
const here = frontmatter.sequence;

const { Content } = await render(page);
---

<Html pageTitle={pageTitle} canonical={canonical} pageUrl={pageUrl}>
  <div id="page">
    <Sidebar
      pageIndex={index}
      pages={allPages.filter((p) => p.data.titles !== undefined)}
      here={here}
    />
    <div id="main-content" class="scrollable">
      <Banner />
      <div id="padded-content">
        <PrevNext seq={here} pages={allPages} />
        <main>
          <Content />
        </main>
        {
          path.startsWith('/search') ? (
            <Search />
          ) : (
            <Subsections
              indexArray={index}
              pages={allPages.filter((p) => p.data.index)}
            />
          )
        }
        <Footer />
        <PrevNext seq={here} pages={allPages} />
      </div>
    </div>
    <PageNavi page={page} />
  </div>
  <FootnoteTooltips />
  <Scripts />
</Html>
