---
import { getCollection, render } from 'astro:content';
import SiteLayout from '../../components/SiteLayout.astro';
import AuthorCard from '../../components/AuthorCard.astro';

export async function getStaticPaths() {
  const posts = await getCollection('blog');
  /* dev only, see blog/index.astro */
  return posts
    .filter((post) => import.meta.env.DEV || !post.data.draft)
    .map((post) => {
      const slug = post.id.replace(/\.(md|mdx)$/i, '');
      return { params: { slug }, props: { post, slug } };
    });
}

const { post, slug } = Astro.props;
const { Content, headings } = await render(post);
const sectionHeadings = headings.filter((heading) => heading.depth === 2);
---

<SiteLayout
  title={`${post.data.title} — Herdr blog`}
  description={post.data.description}
  canonicalPath={`/blog/${slug}/`}
  ogType="article"
  ogImage={post.data.ogImage}
  ogImageAlt={post.data.ogImage ? post.data.title : undefined}
>
  {/* a post with no h2s renders no sidebar, so the grid must stop reserving
      a column for it */}
  <div class:list={['article', sectionHeadings.length === 0 && 'article-solo']}>
    <article class="article-body">
      <p class="article-meta">
        <a href="/blog/">← Blog</a>
        <time datetime={post.data.date.toISOString()}>
          {post.data.date.toLocaleDateString('en', {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
          })}
        </time>
      </p>
      <h1>{post.data.title}</h1>
      {post.data.lede && post.data.description && (
        <p class="article-lede">{post.data.description}</p>
      )}
      <hr class="article-rule" />
      <div class="prose">
        <Content />
      </div>
      <AuthorCard />
    </article>

    {sectionHeadings.length > 0 && (
      <aside class="toc" aria-label="Article sections">
        <p>Sections</p>
        <nav>
          {sectionHeadings.map((heading) => (
            <a href={`#${heading.slug}`} data-heading-link={heading.slug}>{heading.text}</a>
          ))}
        </nav>
      </aside>
    )}
  </div>

  <script>
    const headings = Array.from(document.querySelectorAll('.prose h2[id]'));
    const links = new Map(
      Array.from(document.querySelectorAll('[data-heading-link]')).map((link) => [
        link.getAttribute('data-heading-link'),
        link,
      ]),
    );

    function setActive(id) {
      for (const link of links.values()) link.removeAttribute('aria-current');
      links.get(id)?.setAttribute('aria-current', 'true');
    }

    if (headings.length > 0 && links.size > 0) {
      setActive(headings[0].id);
      const observer = new IntersectionObserver(
        (entries) => {
          const visible = entries
            .filter((entry) => entry.isIntersecting)
            .sort((a, b) => a.boundingClientRect.top - b.boundingClientRect.top)[0];
          if (visible?.target instanceof HTMLElement) setActive(visible.target.id);
        },
        { rootMargin: '-18% 0px -68% 0px', threshold: 0 },
      );
      for (const heading of headings) observer.observe(heading);
    }
  </script>
</SiteLayout>
