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

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 { Content, headings } = await render(article);
---

<PageLayout
  title={article.data.title}
  description={article.data.description}
  pubDate={article.data.pubDate}
  modDate={article.data.modDate}
  {slug}
>
  <details
    class="toc sticky top-10 z-10 -translate-y-px border border-neutral-300 bg-white lg:top-2 dark:border-neutral-600 dark:bg-neutral-800"
  >
    <summary
      title="Table of contents"
      class="mx-auto flex w-fit cursor-pointer list-none border-b-2 border-transparent p-2 hover:border-neutral-300 hover:bg-neutral-100 hover:dark:border-neutral-600 hover:dark:bg-neutral-700"
    >
      <svg
        xmlns="http://www.w3.org/2000/svg"
        viewBox="0 0 20 20"
        fill="currentColor"
        class="size-5"
      >
        <path
          d="M10.75 16.82A7.462 7.462 0 0 1 15 15.5c.71 0 1.396.098 2.046.282A.75.75 0 0 0 18 15.06v-11a.75.75 0 0 0-.546-.721A9.006 9.006 0 0 0 15 3a8.963 8.963 0 0 0-4.25 1.065V16.82ZM9.25 4.065A8.963 8.963 0 0 0 5 3c-.85 0-1.673.118-2.454.339A.75.75 0 0 0 2 4.06v11a.75.75 0 0 0 .954.721A7.506 7.506 0 0 1 5 15.5c1.579 0 3.042.487 4.25 1.32V4.065Z"
        ></path>
      </svg>
    </summary>
    <div class="not-prose max-h-[calc(100vh-8rem)] overflow-y-scroll p-2">
      <p class="text-center">
        <strong class="text-sm">Table of Contents</strong>
      </p>
      <ul>
        {
          headings
            .filter(({ depth }) => depth === 2)
            .map((heading) => (
              <li>
                <a
                  class="block px-2 py-1 text-center text-blue-800 hover:underline dark:text-blue-300"
                  href={`#${heading.slug}`}
                  aria-labelledby={`Section: ${heading.slug}`}
                >
                  {heading.text}
                </a>
              </li>
            ))
        }
      </ul>
    </div>
  </details>
  <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>
