/**
 * Blog Listing Page
 *
 * Displays the blog homepage with:
 * - Editorial-style hero section
 * - Featured posts (when on first page)
 * - Paginated article grid
 * - CTA section
 */

import type { Metadata } from "next";
import { LANGS, UI, type Lang } from "@/lib/config";
import { getPaginatedPosts } from "@/lib/blog";
import {
  BLOG_PAGINATION,
  BLOG_REVALIDATION,
  SECTION_NUMBERS,
  getBlogTranslations,
  generateBlogListMetadata,
  getSectionNumber,
} from "@/lib/blog.config";
import {
  BlogHero,
  FeaturedPostsSection,
  BlogCTA,
  SectionHeader,
  ArticleCard,
  BlogPagination,
  EmptyState,
} from "@/components/blog";

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

export const revalidate = BLOG_REVALIDATION.listPage;

export async function generateStaticParams() {
  return LANGS.map((lang) => ({ lang }));
}

export function generateMetadata({
  params,
}: {
  params: { lang: Lang };
}): Metadata {
  return generateBlogListMetadata(params.lang);
}

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

interface BlogPageProps {
  params: { lang: Lang };
  searchParams: { page?: string };
}

export default async function BlogPage({
  params,
  searchParams,
}: BlogPageProps) {
  const { lang } = params;
  const t = UI[lang].t;
  const blogT = getBlogTranslations(lang);
  const dir = UI[lang].dir;

  // Get current page from query params (default to 1)
  const currentPage = Number(searchParams.page) || 1;

  // Get all posts to properly separate featured from regular
  const allPostsResult = await getPaginatedPosts(
    lang,
    1,
    999, // Get all posts for proper separation
  );

  // Separate featured posts from regular posts across ALL posts
  const allFeatured = allPostsResult.posts.filter(
    (post) => post.featured === true,
  );
  const allRegular = allPostsResult.posts.filter(
    (post) => post.featured !== true,
  );

  // Show featured section only on first page
  const showFeatured = allFeatured.length > 0 && currentPage === 1;

  // Paginate the regular (non-featured) posts
  const startIdx = (currentPage - 1) * BLOG_PAGINATION.postsPerPage;
  const displayPosts = allRegular.slice(
    startIdx,
    startIdx + BLOG_PAGINATION.postsPerPage,
  );
  const totalPages = Math.ceil(
    allRegular.length / BLOG_PAGINATION.postsPerPage,
  );
  const totalPosts = allPostsResult.totalPosts;
  const featuredPosts = allFeatured.slice(0, BLOG_PAGINATION.maxFeaturedPosts);
  const posts = displayPosts;

  return (
    <main className="min-h-screen bg-white" dir={dir}>
      {/* Hero Section */}
      <BlogHero
        lang={lang}
        totalPosts={totalPosts}
        translations={{
          blog: blogT.blog,
          blogTitle: blogT.blogTitle,
          blogSubtitle: blogT.blogSubtitle,
          articles: blogT.articles,
          arabicEnglish: blogT.arabicEnglish,
          weeklyUpdates: blogT.weeklyUpdates,
        }}
      />

      {/* Featured Posts Section */}
      {showFeatured && (
        <FeaturedPostsSection
          posts={featuredPosts.slice(0, BLOG_PAGINATION.maxFeaturedPosts)}
          lang={lang}
          translations={{
            featured: blogT.featured,
            featuredArticles: blogT.featuredArticles,
          }}
        />
      )}

      {/* Latest Articles Section */}
      <section className="py-16 md:py-24 bg-white">
        <div className="mx-auto max-w-7xl px-6">
          {/* Section Header */}
          <SectionHeader
            sectionNumber={getSectionNumber("latest", showFeatured)}
            title={blogT.latestArticles}
          />

          {posts.length === 0 ? (
            <EmptyState lang={lang} />
          ) : (
            <>
              {/* Articles Grid */}
              <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-px bg-slate-200">
                {displayPosts.map((post, idx) => (
                  <ArticleCard
                    key={post.slug}
                    post={post}
                    lang={lang}
                    index={idx + 1}
                  />
                ))}
              </div>

              {/* Pagination */}
              <BlogPagination
                currentPage={currentPage}
                totalPages={totalPages}
                lang={lang}
              />
            </>
          )}
        </div>
      </section>

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