import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getPostBySlug, listPublishedPosts, renderPostBody } from "@/lib/blog";

export const dynamic = "force-dynamic";

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  const post = await getPostBySlug(slug);
  if (!post || post.status !== "published") return { title: "Post" };
  return {
    title: post.title,
    description: post.excerpt || post.title,
  };
}

export default async function BlogPostPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const post = await getPostBySlug(slug);
  if (!post || post.status !== "published") notFound();
  const more = (await listPublishedPosts()).filter((p) => p.id !== post.id).slice(0, 3);

  return (
    <article className="mx-auto max-w-3xl px-4 py-14">
      <p className="text-xs uppercase tracking-[0.28em] text-terra">
        <a href="/blog" className="hover:text-forest">
          Blog
        </a>
        {post.published_at ? ` · ${new Date(post.published_at).toLocaleDateString()}` : ""}
      </p>
      <h1 className="font-display mt-3 text-4xl leading-tight text-forest md:text-5xl">{post.title}</h1>
      {post.excerpt ? <p className="mt-4 text-lg text-forest/75">{post.excerpt}</p> : null}
      {post.cover_url ? (
        // eslint-disable-next-line @next/next/no-img-element
        <img src={post.cover_url} alt="" className="mt-8 h-72 w-full rounded-3xl object-cover" />
      ) : null}
      <div className="blog-body mt-10" dangerouslySetInnerHTML={{ __html: renderPostBody(post.body) }} />
      <div className="mt-12 rounded-3xl bg-gold/30 p-6 text-center">
        <p className="font-display text-2xl text-forest">Want the full blueprint?</p>
        <p className="mt-2 text-sm text-forest/75">Join the classroom and walk the Ghana-first paths step by step.</p>
        <a
          href="/register"
          className="mt-4 inline-flex rounded-full bg-forest px-6 py-3 text-sm font-bold uppercase tracking-wide text-gold-2"
        >
          Join
        </a>
      </div>
      {more.length ? (
        <div className="mt-12">
          <h2 className="font-display text-2xl text-forest">More from the journal</h2>
          <ul className="mt-4 space-y-3">
            {more.map((p) => (
              <li key={p.id}>
                <a href={`/blog/${p.slug}`} className="text-sm font-medium text-terra hover:text-forest">
                  {p.title} →
                </a>
              </li>
            ))}
          </ul>
        </div>
      ) : null}
    </article>
  );
}
