import { notFound } from "next/navigation";
import { Metadata, ResolvingMetadata } from "next";
import BlogDetail from "@/app/blog/components/BlogDetail";
import { getBlog } from "@/lib/api";

export const revalidate = 0;

// ---------------------------
// ⭐ FIXED generateMetadata
// ---------------------------
export async function generateMetadata(
  { params }: { params: Promise<{ slug: string }> },
  _parent: ResolvingMetadata
): Promise<Metadata> {
  
  const { slug } = await params;   // ✅ FIXED

  try {
    const blog = await getBlog(slug);

    if (!blog) return {};

    return {
      title: blog.metaTitle || blog.title,
      description: blog.metaDescription || blog.description?.slice(0, 150),
      keywords: blog.metaKeyword || "",
      alternates: { canonical: `https://www.fruxinfo.com/blog/detail/${slug}` },
      openGraph: {
        title: blog.metaTitle || blog.title,
        description: blog.metaDescription || blog.description,
        images: blog.image ? [{ url: blog.image }] : [],
        type: "article",
      },
    };
  } catch {
    return {};
  }
}

// ---------------------------
// ⭐ FIXED PAGE
// ---------------------------
export default async function BlogDetailPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  
  const { slug } = await params;   // ✅ FIXED

  const blog = await getBlog(slug);

  if (!blog) return notFound();

  // Convert API date "DD-MM-YYYY" to ISO "YYYY-MM-DD" for schema.org
  const isoDate = (() => {
    const m = /^(\d{2})-(\d{2})-(\d{4})$/.exec(blog.date || "");
    return m ? `${m[3]}-${m[2]}-${m[1]}` : blog.date || "";
  })();

  const blogPostingSchema = {
    "@context": "https://schema.org",
    "@type": "BlogPosting",
    headline: blog.metaTitle || blog.title,
    description: blog.metaDescription || (blog.description ? String(blog.description).replace(/<[^>]+>/g, "").slice(0, 200) : ""),
    image: blog.image
      ? [blog.image.startsWith("http") ? blog.image : `https://www.fruxinfo.com${blog.image}`]
      : ["https://www.fruxinfo.com/images/fruxinfo-logo.png"],
    datePublished: isoDate,
    dateModified: isoDate,
    author: {
      "@type": "Organization",
      name: "Fruxinfo",
      url: "https://www.fruxinfo.com/",
    },
    publisher: {
      "@type": "Organization",
      name: "Fruxinfo Pvt. Ltd.",
      logo: {
        "@type": "ImageObject",
        url: "https://www.fruxinfo.com/images/fruxinfo-logo.png",
      },
    },
    mainEntityOfPage: {
      "@type": "WebPage",
      "@id": `https://www.fruxinfo.com/blog/detail/${slug}`,
    },
  };

  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(blogPostingSchema) }}
      />
      <BlogDetail blog={blog} />
    </>
  );
}
