---
/**
 * Single Post
 *
 * Demonstrates:
 * - getEmDashEntry for fetching a single entry
 * - getEntryTerms for taxonomy terms (NO db parameter!)
 * - PortableText component for rich content
 * - Proper image field access
 */

import { getEmDashEntry, getEntryTerms } from "emdash";
import { PortableText } from "emdash/ui";
import Base from "../../layouts/Base.astro";

const { slug } = Astro.params;

const { entry: post, error } = await getEmDashEntry("posts", slug!);

if (error) {
	return new Response("Server error", { status: 500 });
}

if (!post) {
	return Astro.redirect("/404");
}

// Get taxonomy terms - NOTE: no db parameter!
const categories = await getEntryTerms("posts", post.id, "categories");
const tags = await getEntryTerms("posts", post.id, "tags");

const formattedDate = post.data.published_at
	? new Date(post.data.published_at).toLocaleDateString("en-US", {
			year: "numeric",
			month: "long",
			day: "numeric",
		})
	: null;
---

<Base title={post.data.title} description={post.data.excerpt}>
	<article class="container">
		<div class="content-width">
			<header class="post-header">
				<h1>{post.data.title}</h1>

				<div class="post-meta">
					{
						formattedDate && (
							<time datetime={post.data.published_at}>{formattedDate}</time>
						)
					}

					{
						categories.length > 0 && (
							<span class="post-categories">
								in{" "}
								{categories.map((cat, i) => (
									<>
										{i > 0 && ", "}
										<a href={`/categories/${cat.slug}`}>{cat.label}</a>
									</>
								))}
							</span>
						)
					}
				</div>
			</header>

			{/* IMPORTANT: Check .src, not just the field */}
			{
				post.data.featured_image?.src && (
					<div class="post-featured-image">
						<img
							src={post.data.featured_image.src}
							alt={post.data.featured_image.alt || post.data.title}
						/>
					</div>
				)
			}

			<div class="prose">
				{post.data.content && <PortableText value={post.data.content} />}
			</div>

			{
				tags.length > 0 && (
					<div class="post-tags">
						{tags.map((tag) => (
							<a href={`/tags/${tag.slug}`} class="tag">
								{tag.label}
							</a>
						))}
					</div>
				)
			}
		</div>
	</article>
</Base>
