---
import type { CollectionEntry } from "astro:content";
import { config } from "../../config";
import { getCollection } from "astro:content";
import blogSchema from "../../utils/schemas/blogSchema";
import breadcrumbSchema from "../../utils/schemas/breadcrumbSchema";
import Layout from "../../layouts/BaseLayout.astro";
import PostElement from "../../components/PostElement.astro";
import RSSIcon from "../../components/Icons/RSS.astro";
import websiteSchema from "../../utils/schemas/websiteSchema";

const posts = await getCollection("blog", ({ data }) => {
	return data.draft !== true;
});

posts.sort((a, b) => b.data.datePublished.getTime() - a.data.datePublished.getTime());

const postsByYear = posts.reduce<Record<string, CollectionEntry<"blog">[]>>((acc, post) => {
	const year = post.data.datePublished.getFullYear().toString();
	if (!acc[year]) {
		acc[year] = [];
	}
	acc[year].push(post);
	return acc;
}, {});

const years = Object.keys(postsByYear).sort((a, b) => Number(b) - Number(a));

const title = "Valentin Popov's Blog | Software Development, Leadership & Open-Source";
const description = "Explore Valentin Popov's blog on software development, tech leadership, and open-source experiments. Stay updated with in-depth tutorials and expert insights.";
const preview = config.og.defaultPreview;
const lang = "en";

const siteUrl = new URL("/", Astro.site).toString();

const schema = [
	websiteSchema({ siteUrl, name: config.og.website, description, lang }),
	blogSchema({ siteUrl, title, description, lang, posts }),
	breadcrumbSchema({
		siteUrl,
		items: [
			{ name: "Home", url: "/" },
			{ name: "Blog", url: "/blog/" },
		],
	}),
];
---

<Layout title={title} description={description} preview={preview} lang={lang} schema={schema}>
	<section>
		<h1>
			Blog posts
			<RSSIcon />
		</h1>
	</section>

	<section>
		{
			years.map((year) => (
				<div>
					<h2>{year}</h2>
					<ul>
						{postsByYear[year].map((post) => (
							<PostElement post={post} />
						))}
					</ul>
				</div>
			))
		}
	</section>
</Layout>
