---
import type { CollectionEntry } from "astro:content";
import Pagination from "@/components/Paginator.astro";
import PostPreview from "@/components/blog/PostPreview.astro";
import { getAllPosts, getUniqueTags } from "@/data/post";
import PageLayout from "@/layouts/Base.astro";
import { collectionDateSort } from "@/utils/date";
import type { GetStaticPaths, Page } from "astro";

export const getStaticPaths: GetStaticPaths = async ({ paginate }) => {
	const allPosts = await getAllPosts();
	const sortedPosts = allPosts.sort(collectionDateSort);
	const uniqueTags = getUniqueTags(sortedPosts);

	return uniqueTags.flatMap((tag) => {
		const filterPosts = sortedPosts.filter((post) => post.data.tags.includes(tag));
		return paginate(filterPosts, {
			pageSize: 10,
			params: { tag },
		});
	});
};

interface Props {
	page: Page<CollectionEntry<"post">>;
}

const { page } = Astro.props;
const { tag } = Astro.params;

const meta = {
	description: `View all posts with the tag - ${tag}`,
	title: `Tag: ${tag}`,
};

const paginationProps = {
	...(page.url.prev && {
		prevUrl: {
			text: "← Previous Tags",
			url: page.url.prev,
		},
	}),
	...(page.url.next && {
		nextUrl: {
			text: "Next Tags →",
			url: page.url.next,
		},
	}),
};
---

<PageLayout meta={meta}>
	<h1 class="title mb-6 flex items-center">
		<a class="text-accent-two sm:hover:underline" href="/tags/">Tags</a>
		<span class="me-3 ms-2">→</span>
		<span class="text-2xl">#{tag}</span>
	</h1>
	<section aria-label="Blog post list">
		<ul class="space-y-4">
			{
				page.data.map((p) => (
					<li class="grid-cols-[auto_1fr]">
						<PostPreview post={p} />
					</li>
				))
			}
		</ul>
		<Pagination {...paginationProps} />
	</section>
</PageLayout>
