/**
 * Blog Post Page
 *
 * Displays an individual blog post with:
 * - Hero section with cover image
 * - MDX content with custom components
 * - Author and share section
 * - Related posts
 * - CTA section
 */

import { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { MDXRemote } from "next-mdx-remote/rsc";
import rehypeRaw from "rehype-raw";
import remarkGfm from "remark-gfm";
import { UI } from "@/lib/config";
import { getPostBySlug, getAllPostSlugs, getRelatedPosts } from "@/lib/blog";
import {
  BLOG_REVALIDATION,
  BLOG_PAGINATION,
  SITE_CONFIG,
  getBlogTranslations,
  generateBlogPostSchema,
  generateBreadcrumbSchema,
  processContent,
} from "@/lib/blog.config";
import {
  ReadingProgress,
  BlogPostContent,
  PostHero,
  RelatedPostsSection,
  BlogCTA,
  ShareButtons,
  AuthorCard,
  ExcerptCallout,
  BackToBlog,
  // MDX Components
  Callout,
  CodeBlock,
  DataTable,
  SectionDivider,
  StatCard,
  InfoBox,
} from "@/components/blog";

// ============================================================================
// STATIC CONFIG
// ============================================================================

export const revalidate = BLOG_REVALIDATION.postPage;

type Props = {
  params: { lang: "ar" | "en"; slug: string };
};

// ============================================================================
// METADATA GENERATION
// ============================================================================

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { lang, slug } = params;
  const post = await getPostBySlug(slug, lang);

  if (!post) {
    return { title: "Post Not Found" };
  }

  const siteUrl = `https://${SITE_CONFIG.domain}`;
  const postUrl = `${siteUrl}/${lang}/blog/${slug}`;
  const imageUrl = post.coverImage || `${siteUrl}/og-image.png`;

  return {
    title: post.title,
    description: post.excerpt,
    openGraph: {
      title: post.title,
      description: post.excerpt,
      type: "article",
      publishedTime: post.date,
      authors: [post.author],
      images: post.coverImage ? [post.coverImage] : [],
      url: postUrl,
      siteName: SITE_CONFIG.name,
      locale: lang === "ar" ? "ar_SA" : "en_US",
    },
    twitter: {
      card: "summary_large_image",
      title: post.title,
      description: post.excerpt,
      images: [imageUrl],
      creator: SITE_CONFIG.twitter,
      site: SITE_CONFIG.twitter,
    },
    alternates: {
      canonical: `/${lang}/blog/${slug}`,
      languages: {
        ar: `/ar/blog/${slug}`,
        en: `/en/blog/${slug}`,
      },
    },
  };
}

export async function generateStaticParams() {
  const arSlugs = await getAllPostSlugs("ar");
  const enSlugs = await getAllPostSlugs("en");

  return [
    ...arSlugs.map((slug) => ({ lang: "ar" as const, slug })),
    ...enSlugs.map((slug) => ({ lang: "en" as const, slug })),
  ];
}

// ============================================================================
// MDX COMPONENTS
// ============================================================================

const mdxComponents = {
  Callout,
  CodeBlock,
  DataTable,
  SectionDivider,
  StatCard,
  InfoBox,
};

// ============================================================================
// PAGE COMPONENT
// ============================================================================

export default async function BlogPostPage({ params }: Props) {
  const { lang, slug } = params;
  const t = UI[lang].t;
  const blogT = getBlogTranslations(lang);
  const dir = UI[lang].dir;

  // Fetch post data
  const post = await getPostBySlug(slug, lang);
  if (!post) {
    notFound();
  }

  // Process content for MDX compatibility
  const processedContent = processContent(post.content);

  // Fetch related posts
  const relatedPosts = await getRelatedPosts(
    slug,
    lang,
    BLOG_PAGINATION.relatedPostsLimit,
  );

  // Generate structured data
  const blogPostingSchema = generateBlogPostSchema(post, lang, slug);
  const breadcrumbSchema = generateBreadcrumbSchema(
    lang,
    post.title,
    slug,
    t.home || "Home",
    t.blog || "Blog",
  );

  const postUrl = `https://${SITE_CONFIG.domain}/${lang}/blog/${slug}`;

  return (
    <main className="min-h-screen bg-white" dir={dir}>
      {/* JSON-LD Structured Data */}
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(blogPostingSchema) }}
      />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbSchema) }}
      />

      {/* Reading Progress Bar */}
      <ReadingProgress />

      {/* Hero Section */}
      <PostHero
        title={post.title}
        author={post.author}
        date={post.date}
        tags={post.tags}
        coverImage={post.coverImage}
        readingTime={post.readingTime}
        lang={lang}
        translations={{
          home: t.home || "Home",
          blog: t.blog || "Blog",
          writtenBy: blogT.writtenBy,
        }}
      />

      {/* Article Content */}
      <div className="max-w-7xl mx-auto px-6 py-16">
        {/* Back to Blog Link */}
        <BackToBlog lang={lang} dir={dir} />

        {/* Excerpt Callout */}
        <ExcerptCallout excerpt={post.excerpt} lang={lang} />

        {/* Main Content Layout */}
        <BlogPostContent lang={lang}>
          <MDXRemote
            source={processedContent}
            options={{
              mdxOptions: {
                remarkPlugins: [remarkGfm],
                rehypePlugins: [
                  [
                    rehypeRaw,
                    { passThrough: ["mdxJsxFlowElement", "mdxJsxTextElement"] },
                  ],
                ],
              },
            }}
            components={mdxComponents}
          />
        </BlogPostContent>

        {/* Author & Share Section */}
        <div className="mt-16 pt-8 border-t border-slate-200 max-w-4xl mx-auto lg:mx-0">
          <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-6">
            <AuthorCard author={post.author} writtenByLabel={blogT.writtenBy} />
            <ShareButtons
              title={post.title}
              url={postUrl}
              lang={lang}
              shareLabel={blogT.shareArticle}
            />
          </div>
        </div>
      </div>

      {/* Related Posts */}
      <RelatedPostsSection
        posts={relatedPosts}
        lang={lang}
        translations={{
          relatedPosts: blogT.relatedPosts,
          continueReading: blogT.continueReading,
        }}
      />

      {/* CTA Section */}
      <BlogCTA
        lang={lang}
        translations={{
          ctaTitle: blogT.ctaTitle,
          ctaDescription: blogT.ctaDescription,
          ctaPrimary: t.ctaPrimary,
          ctaSecondary: t.ctaSecondary,
        }}
      />
    </main>
  );
}
