---
import { format, add } from 'date-fns';
import { getCollection } from 'astro:content';

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

export async function getStaticPaths() {
	const posts = await getCollection('blog');

	const tags = ['all'];
	posts.forEach((post) =>
		post.data.tags.forEach((tag) => {
			if (!tags.includes(tag)) {
				tags.push(tag);
			}
		})
	);

	return tags.map((tag) => ({
		params: { tag },
		props: { tag },
	}));
}

const { tag }: { tag?: string } = Astro.params;

const posts = await getCollection('blog', ({ data }) => {
	if (!tag) {
		return false;
	}

	if (tag === 'all') {
		return true;
	}

	return data.tags.includes(tag);
});

if (posts.length === 0) {
	return Astro.redirect('/404');
}

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

<Layout title="Blog Archive">
	{
		posts.map(({ slug, data }) => (
			<div class="archive-post">
				<a href={`/posts/${slug}`}>{data.title}</a>
				<span>
					{format(add(new Date(data.pubDate), { hours: 6 }), 'MMM do, y')}
				</span>
			</div>
		))
	}
</Layout>

<style>
	.archive-post {
		display: flex;
		justify-content: space-between;
	}
	.archive-post:not(:last-of-type) {
		margin-bottom: 26px;
	}
	.archive-post a {
		max-width: 400px;
		font-weight: bold;
	}

	.navigation {
		max-width: 400px;
		margin: auto;
		display: flex;
		padding: 30px;
		justify-content: space-between;
	}

	@media screen and (max-width: 800px) {
		.archive-post {
			flex-direction: column;
		}
	}
</style>
