import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { PageHeader } from "@/components/PageHeader";
import { Section } from "@/components/Section";
import { ImagePlaceholder } from "@/components/ImagePlaceholder";
import { RichText } from "@/components/RichText";
import { getPostBySlug } from "@/lib/payload/content";
import { mediaAlt, mediaUrl } from "@/lib/payload/media";

export const dynamic = "force-dynamic";

type Args = { params: Promise<{ slug: string }> };

export async function generateMetadata({ params }: Args): Promise<Metadata> {
  const { slug } = await params;
  const post = await getPostBySlug(slug);
  if (!post) return {};
  return { title: post.title, description: post.teaser };
}

export default async function PostDetailPage({ params }: Args) {
  const { slug } = await params;
  const post = await getPostBySlug(slug);
  if (!post) notFound();

  const publishDate = new Date(post.publishDate ?? post.createdAt).toLocaleDateString("de-DE", {
    day: "2-digit",
    month: "long",
    year: "numeric",
  });

  return (
    <>
      <PageHeader
        eyebrow={publishDate}
        title={post.title}
        lead={post.teaser}
        crumbs={[{ title: "Aktuelles", href: "/aktuelles" }, { title: post.title }]}
      />
      <div className="mx-auto -mt-10 max-w-5xl px-6 sm:px-8 lg:px-12">
        <div className="relative aspect-[21/9] w-full">
          <ImagePlaceholder
            mood="sand"
            label={post.title}
            src={mediaUrl(post.coverImage, "hero")}
            alt={mediaAlt(post.coverImage) ?? post.title}
            shape="soft"
            priority
            className="h-full w-full"
          />
        </div>
      </div>
      <Section tone="plain">
        <div className="mx-auto max-w-2xl">
          <RichText data={post.content} />
        </div>
      </Section>
    </>
  );
}
