---
import PageLayout from "../../layouts/PageLayout.astro";
import { getCollection, getEntry, render } from "astro:content";
import TableOfContents from "../../components/TableOfContents.astro";

export const getStaticPaths = async () => {
  const allArticles = await getCollection("blog");
  return allArticles.map((article) => ({
    params: { slug: article.id },
    props: { article },
  }));
};

const { slug } = Astro.params;
const article = await getEntry("blog", slug);

if (!article) {
  throw new Error();
}

const { title, description, pubDate, modDate } = article.data;

const { Content, headings } = await render(article);
---

<PageLayout {title} {description} {pubDate} {modDate} {slug}>
  <TableOfContents {headings} />
  <Content />
</PageLayout>

<script>
  const setAnchorListener = () => {
    const tocLinks = document.querySelectorAll("#toc a");

    for (const link of tocLinks) {
      link.addEventListener("click", () => {
        document.querySelector("#toc")?.removeAttribute("open");
      });
    }
  };

  setAnchorListener();
  document.addEventListener("astro:after-swap", setAnchorListener);
</script>
