---
import { getCollection, type CollectionEntry } from 'astro:content';
import type { Page } from 'astro';

import Layout from '@layouts/Layout.astro';
import PostPreview from '@components/PostPreview.astro';

export async function getStaticPaths({ paginate }) {
	const allPosts = await getCollection('blog');

	allPosts.sort(
		(a, b) =>
			Date.parse(String(b.data.pubDate)) - Date.parse(String(a.data.pubDate))
	);

	return paginate(allPosts, { pageSize: 10 });
}

interface Props {
	page: Page<CollectionEntry<'blog'>>;
}

const { page } = Astro.props;
---

<Layout title="Blog Archive">
	{page.data.map((post) => <PostPreview post={post} />)}

	<div class="pagination">
		{
			page.currentPage !== 1 ? (
				<a href={`/blog/page/${page.currentPage - 1}`}>Previous</a>
			) : (
				<span class="disabled">Previous</span>
			)
		}
		{
			page.currentPage !== page.lastPage ? (
				<a href={`/blog/page/${page.currentPage + 1}`}>Next</a>
			) : (
				<span class="disabled">Next</span>
			)
		}
	</div>
</Layout>

<style>
	ul {
		list-style: none;
	}

	.pagination {
		display: flex;
		justify-content: center;
		margin-top: 2rem;
		margin: auto;
		gap: 1rem;
	}

	.disabled {
		color: var(--text);
		opacity: 0.5;
	}
</style>
