import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import Header from "@/components/shared/layout/header/Header";
import BlogSingle from "@/components/pages/blog/BlogSingle";
import LatestPost from "@/components/pages/blog/LatestPost";
import Footer from "@/components/shared/layout/footer/Footer";
import BlogScrollProgressButton from "@/components/pages/blog/BlogScrollProgressButton";
import BlogInitAnimations from "@/components/pages/blog/BlogInitAnimations";
import { generateBlogMetadata } from "@/lib/seo/metadata";
import { API_CONFIG } from "@/lib/config/api";

interface PageProps {
  params: Promise<{
    slug: string;
  }>;
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { slug } = await params;
  
  try {
    const response = await fetch(
      `${API_CONFIG.BASE_URL}/api/blog/posts/${slug}/`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        next: { revalidate: 3600 },
      }
    );

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const post = await response.json();
    
    return generateBlogMetadata({
      title: post.title,
      description: post.meta_description || post.excerpt || post.content?.substring(0, 160),
      excerpt: post.excerpt,
      slug: post.slug,
      image: post.featured_image || post.thumbnail,
      published_at: post.published_at,
      updated_at: post.updated_at,
      author: post.author ? { name: post.author.name } : undefined,
      category: post.category ? { name: post.category.title } : undefined,
      tags: post.tags?.map((tag: any) => tag.name) || [],
    });
  } catch (error) {
    return {
      title: 'Insight Not Found | GNX Soft',
      description: 'The requested insight article could not be found.',
    };
  }
}

const page = async ({ params }: PageProps) => {
  const { slug } = await params;
  
  return (
    <div className="tp-app">
      <Header />
      <main>
        <BlogSingle />
        <LatestPost />
      </main>
      <Footer />
      <BlogScrollProgressButton />
      <BlogInitAnimations />
    </div>
  );
};

export default page;
