import type { Metadata } from "next";
import { getPostBySlug, getAllPostSlugs } from "@/lib/posts";
import { format } from "date-fns";
import { sr } from "date-fns/locale";
import Link from "next/link";
import { notFound } from "next/navigation";

export async function generateStaticParams() {
  return getAllPostSlugs();
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  try {
    const post = await getPostBySlug(slug);
    return { title: post.title, description: post.excerpt };
  } catch {
    return { title: "Post nije pronađen" };
  }
}

export default async function BlogPostPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  let post;
  try {
    post = await getPostBySlug(slug);
  } catch {
    notFound();
  }

  return (
    <div className="max-w-2xl mx-auto px-4 py-12">
      <Link href="/blog" className="text-sky-600 hover:text-sky-800 text-sm mb-8 block">
        ← Nazad na blog
      </Link>

      <article>
        <div className="mb-4 flex flex-wrap gap-2 items-center">
          {post.tags?.map((t) => (
            <span key={t} className="text-xs bg-sky-50 text-sky-700 px-2 py-0.5 rounded-full">
              {t}
            </span>
          ))}
          <span className="text-xs text-gray-400 ml-auto">
            {post.date
              ? format(new Date(post.date), "d. MMMM yyyy.", { locale: sr })
              : ""}
          </span>
        </div>

        <h1 className="text-3xl font-bold text-sky-800 mb-4">{post.title}</h1>

        {post.excerpt && (
          <p className="text-gray-500 text-lg mb-8 leading-relaxed">{post.excerpt}</p>
        )}

        <hr className="border-gray-200 mb-8" />

        <div
          className="prose-content"
          dangerouslySetInnerHTML={{ __html: post.content }}
        />
      </article>
    </div>
  );
}
