import { createFileRoute, Link, notFound } from "@tanstack/react-router";
import RichText from "@/components/RichText";
import Section from "@/components/Section";
import { findPostBySlug } from "@/lib/cms";

export const Route = createFileRoute("/blog/$slug")({
	loader: async ({ params }) => {
		const post = await findPostBySlug(params.slug);
		if (!post) throw notFound();
		return { post };
	},
	component: BlogPost,
	head: ({ loaderData }) => ({
		meta: [
			{
				title: `unom - ${loaderData?.post?.meta?.title ?? loaderData?.post?.title ?? "Blog"}`,
			},
			...(loaderData?.post?.summary
				? [{ name: "description", content: loaderData.post.summary }]
				: []),
		],
	}),
});

const dateFmt = new Intl.DateTimeFormat("de-DE", {
	day: "2-digit",
	month: "long",
	year: "numeric",
});

function BlogPost() {
	const { post } = Route.useLoaderData();
	return (
		<Section className="pt-height-header">
			<Link to="/blog" className="text-secondary text-sm">
				← Blog
			</Link>
			<article className="markdown mt-4">
				<time
					dateTime={post.createdAt}
					className="text-secondary text-sm block mb-2"
				>
					{dateFmt.format(new Date(post.createdAt))}
				</time>
				<h1>{post.title}</h1>
				<p className="text-secondary text-lg mb-8">{post.summary}</p>
				<RichText data={post.content} />
			</article>
		</Section>
	);
}
