---
import { getCollection } from 'astro:content';
import FormattedDate from '../../components/FormattedDate.astro';
import SectionContainer from '../../components/SectionContainer.astro';

const posts = (await getCollection('blog')).sort(
    (a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf()
);

// Group posts by year
const postsByYear = posts.reduce((acc:any, post) => {
    const year = new Date(post.data.pubDate).getFullYear();
    if (!acc[year]) {
        acc[year] = [];
    }
    acc[year].push(post);
    return acc;
}, {});

// Sort the years
const sortedYears = Object.keys(postsByYear).sort((a:any, b:any) => b - a);
---
<SectionContainer title="blog" description="">
	<main class="flex flex-col gap-4 mt-4">
		<h1 class="text-3xl font-extrabold">[ blog ]</h1>
		<a href="/rss.xml">💥 Subscribe via RSS</a>
		{sortedYears.map(year => (
			<section>
				<div class="text-xl font-semibold">{year}</div>
				<ul>
					{
						postsByYear[year].map((post:any) => (
							<div class="flex justify-between mb-2 break-words">
								<a class="font-semibold w-1/2" href={`/blog/${post.slug}/`}>✨ {post.data.title}</a>
								<FormattedDate date={post.data.pubDate} />
							</div>
						))
					}
				</ul>
			</section>
		))}
	</main>
</SectionContainer>
