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

interface Props {
	count?: number;
	showThumbnails?: boolean;
	showDate?: boolean;
}

const { count = 5, showThumbnails = false, showDate = true } = Astro.props;

const { entries: posts } = await getEmDashCollection("posts", {
	limit: count,
	orderBy: { published_at: "desc" },
});

// Helper to get typed values from dynamic data
function getString(data: Record<string, unknown>, key: string): string | undefined {
	const val = data[key];
	return typeof val === "string" ? val : undefined;
}
---

<ul class="widget-recent-posts">
	{
		posts.map((post) => {
			const publishedAt = getString(post.data, "publishedAt");
			const featuredImage = getString(post.data, "featured_image");
			const title = getString(post.data, "title");
			return (
				<li>
					{showThumbnails && featuredImage && (
						<img
							src={featuredImage}
							alt=""
							class="widget-recent-posts__thumbnail"
						/>
					)}
					<a href={`/posts/${post.id}`} class="widget-recent-posts__link">
						{title}
					</a>
					{showDate && publishedAt && (
						<time datetime={publishedAt} class="widget-recent-posts__date">
							{new Date(publishedAt).toLocaleDateString()}
						</time>
					)}
				</li>
			);
		})
	}
</ul>
