---
import { type CollectionEntry, getCollection, render } from "astro:content";
import Container from "@components/Container.astro";
import FormattedDate from "@components/FormattedDate.astro";
import PostNavigation from "@components/PostNavigation.astro";
import TableOfContents from "@components/TableOfContents.astro";
import Layout from "@layouts/Layout.astro";
import { readingTime } from "@lib/utils";

export async function getStaticPaths() {
	const posts = (await getCollection("blog"))
		.filter((post) => !post.data.draft)
		.sort((a, b) => b.data.date.valueOf() - a.data.date.valueOf());
	return posts.map((post) => ({
		params: { id: post.id },
		props: post,
	}));
}
type Props = CollectionEntry<"blog">;

const posts = (await getCollection("blog"))
	.filter((post) => !post.data.draft)
	.sort((a, b) => b.data.date.valueOf() - a.data.date.valueOf());

function getNextPost() {
	let postIndex;
	for (const post of posts) {
		if (post.id === Astro.params.id) {
			postIndex = posts.indexOf(post);
			return posts[postIndex + 1];
		}
	}
}

function getPrevPost() {
	let postIndex;
	for (const post of posts) {
		if (post.id === Astro.params.id) {
			postIndex = posts.indexOf(post);
			return posts[postIndex - 1];
		}
	}
}

const nextPost = getNextPost();
const prevPost = getPrevPost();

const post = Astro.props;
const { Content, headings } = await render(post);
---

<Layout title={post.data.title} description={post.data.description}>
  <Container>
    <div class="my-10 space-y-1">
      <div class="animate flex items-center gap-1.5">
        <div class="font-base text-sm">
          <FormattedDate date={post.data.date} />
        </div>
        &bull;
        {post.body && <div class="font-base text-sm">{readingTime(post.body)}</div>}
      </div>
      <h1 class="animate text-3xl font-semibold text-black dark:text-white">
        {post.data.title}
      </h1>
    </div>
    {headings.length > 0 && <TableOfContents headings={headings} />}
    <article class="animate">
      <Content />
      <PostNavigation prevPost={prevPost} nextPost={nextPost} />
    </article>
  </Container>
</Layout>
