---
import { getEmDashCollection } from "../../query.js";

interface Props {
	type?: "monthly" | "yearly";
	limit?: number;
}

const { type = "monthly", limit = 12 } = Astro.props;

// Get all posts to build archives
const { entries: posts } = await getEmDashCollection("posts", {
	orderBy: { published_at: "desc" },
});

// Group posts by date
const archives = new Map<string, { label: string; count: number; url: string }>();

for (const post of posts) {
	const publishedAt = post.data.publishedAt;
	if (typeof publishedAt !== "string") continue;

	const date = new Date(publishedAt);
	let key: string;
	let label: string;
	let url: string;

	if (type === "yearly") {
		const year = date.getFullYear();
		key = `${year}`;
		label = `${year}`;
		url = `/archives/${year}`;
	} else {
		const year = date.getFullYear();
		const month = date.getMonth() + 1;
		key = `${year}-${month.toString().padStart(2, "0")}`;
		label = date.toLocaleDateString("en-US", {
			year: "numeric",
			month: "long",
		});
		url = `/archives/${year}/${month.toString().padStart(2, "0")}`;
	}

	if (!archives.has(key)) {
		archives.set(key, { label, count: 0, url });
	}
	archives.get(key)!.count++;
}

// Convert to array and limit
const archiveList = [...archives.values()].slice(0, limit);
---

<ul class="widget-archives">
	{
		archiveList.map((archive) => (
			<li>
				<a href={archive.url} class="widget-archives__link">
					{archive.label}
				</a>
				<span class="widget-archives__count">({archive.count})</span>
			</li>
		))
	}
</ul>
