/**
 * Homepage
 * 
 * Main landing page with Admin /configurations & landing-page-list hydration,
 * Streaming / Suspense boundaries, and high-performance React Server Components (RSC).
 */

import { Suspense } from 'react';
import { type Metadata } from 'next';
import { getTranslations } from 'next-intl/server';
import {
  dashboardService,
  categoryService,
  serviceService,
} from '@/lib/api/client';
import { Footer } from '@/components/layout/Footer';
import { Hero } from '@/components/home/Hero';
import { Categories } from '@/components/home/Categories';
import { TrendingServices } from '@/components/home/TrendingServices';
import { HowItWorks } from '@/components/home/HowItWorks';
import { TestimonialsSection } from '@/components/home/TestimonialsSection';
import { type Locale } from '@/i18n';
import type { Category, Service } from '@shinecode/api-client/types';

interface HomePageProps {
  params: Promise<{ locale: Locale }>;
}

export async function generateMetadata({ params }: HomePageProps): Promise<Metadata> {
  const { locale } = await params;
  const t = await getTranslations({ locale, namespace: 'home' });

  return {
    title: t('metaTitle'),
    description: t('metaDescription'),
    alternates: {
      canonical: `https://shinecode.ae/${locale}`,
      languages: {
        en: `https://shinecode.ae/en`,
        ar: `https://shinecode.ae/ar`,
        'x-default': `https://shinecode.ae/en`,
      },
    },
    openGraph: {
      title: t('metaTitle'),
      description: t('metaDescription'),
      url: `https://shinecode.ae/${locale}`,
      siteName: 'ShineCode',
      images: [
        {
          url: 'https://shinecode.ae/images/frontend/socialP.webp',
          width: 1200,
          height: 630,
          alt: 'ShineCode At-Home Salon & Spa',
        },
      ],
      type: 'website',
      locale: locale === 'ar' ? 'ar_AE' : 'en_AE',
    },
    twitter: {
      card: 'summary_large_image',
      title: t('metaTitle'),
      description: t('metaDescription'),
      images: ['https://shinecode.ae/images/frontend/socialP.webp'],
    },
  };
}

/**
 * Streaming Server Component for Categories
 * Connects directly to Admin landing-page-list (section_2)
 */
async function CategoriesStream({ locale }: { locale: Locale }) {
  const [landingConfigResult, categoriesResult, servicesResult] = await Promise.all([
    dashboardService.getLandingPageConfig(),
    categoryService.getCategories({ per_page: 'all' }),
    serviceService.getServices(),
  ]);

  const allCategories: Category[] = categoriesResult.ok ? categoriesResult.data : [];
  const allServices: Service[] = servicesResult.ok ? servicesResult.data : [];
  const landingConfig = landingConfigResult.ok ? landingConfigResult.data : {};

  // Extract admin section_2 category_id array
  const section2CatIds = landingConfig.section_2?.category_id || [];
  let orderedCategories: Category[] = [];

  if (section2CatIds.length > 0 && allCategories.length > 0) {
    orderedCategories = section2CatIds
      .map((idStr) => allCategories.find((c) => String(c.id) === String(idStr)))
      .filter((c): c is Category => Boolean(c));
  }

  // Fallback to all categories if none matched
  if (orderedCategories.length === 0) {
    orderedCategories = allCategories;
  }

  // Derive minimum price per category_id from the full services list
  const minPriceByCategory = allServices.reduce<Record<number, number>>((acc, svc) => {
    const price = svc.discount_price ?? svc.price;
    if (acc[svc.category_id] === undefined || price < acc[svc.category_id]) {
      acc[svc.category_id] = price;
    }
    return acc;
  }, {});

  return (
    <Categories
      categories={orderedCategories}
      minPriceByCategory={minPriceByCategory}
      locale={locale}
    />
  );
}

/**
 * Streaming Server Component for Trending Services
 * Uses /top-rated-service — API-provided order, first 8 items.
 */
async function TrendingServicesStream({ locale }: { locale: Locale }) {
  const result = await serviceService.getTopRatedServices(8);
  const services: Service[] = result.ok ? result.data : [];

  return <TrendingServices locale={locale} services={services} />;
}

/**
 * Skeleton Fallback for Categories
 */
function CategoriesSkeletonFallback() {
  return (
    <section className="py-16 md:py-24 bg-white dark:bg-zinc-950 border-b border-zinc-100 dark:border-zinc-900">
      <div className="container mx-auto px-4 lg:px-8">
        <div className="flex items-end justify-between mb-8 md:mb-10">
          <div className="h-9 w-64 bg-zinc-200/70 dark:bg-zinc-800 rounded-lg animate-pulse" />
          <div className="h-5 w-20 bg-zinc-200/50 dark:bg-zinc-800 rounded animate-pulse" />
        </div>
        <div className="flex w-full gap-4 overflow-x-auto hide-scrollbar pb-4">
          {Array.from({ length: 5 }).map((_, index) => (
            <div
              key={index}
              className="flex-none w-[260px] sm:w-[280px] aspect-[9/13] rounded-2xl bg-zinc-100 dark:bg-zinc-900 animate-pulse border border-zinc-200/70 dark:border-zinc-800"
            />
          ))}
        </div>
      </div>
    </section>
  );
}

export default async function HomePage({ params }: HomePageProps) {
  const { locale } = await params;

  // Pre-fetch Admin Landing Page config & services in parallel for immediate SSR hydration of Hero
  const [landingConfigResult, categoriesResult, servicesResult, topServicesResult] = await Promise.all([
    dashboardService.getLandingPageConfig(),
    categoryService.getCategories({ per_page: 'all' }),
    serviceService.getServices(),
    serviceService.getTopRatedServices(6),
  ]);

  const allCategories: Category[] = categoriesResult.ok ? categoriesResult.data : [];
  const allServices: Service[] = servicesResult.ok ? servicesResult.data : [];
  const topServices: Service[] = topServicesResult.ok ? topServicesResult.data : [];
  const landingConfig = landingConfigResult.ok ? landingConfigResult.data : {};

  // Extract Admin Section 1 categories (strictly 4 items for 2x2 grid)
  const section1CatIds = landingConfig.section_1?.category_id || [];
  let heroCategories: Category[] = [];
  if (section1CatIds.length > 0 && allCategories.length > 0) {
    heroCategories = section1CatIds
      .map((idStr) => allCategories.find((c) => String(c.id) === String(idStr)))
      .filter((c): c is Category => Boolean(c))
      .slice(0, 4);
  }
  if (heroCategories.length === 0) {
    heroCategories = allCategories.slice(0, 4);
  }

  // Extract Admin Section 3 / Section 4 trending services (strictly 3 items for dropdown)
  const section3ServiceIds = landingConfig.section_3?.service_id || landingConfig.section_4?.service_id || [];
  let heroTrendingServices: Service[] = [];
  if (section3ServiceIds.length > 0 && allServices.length > 0) {
    heroTrendingServices = section3ServiceIds
      .map((idStr) => allServices.find((s) => String(s.id) === String(idStr)))
      .filter((s): s is Service => Boolean(s))
      .slice(0, 3);
  }
  if (heroTrendingServices.length === 0) {
    heroTrendingServices = topServices.slice(0, 3);
  }
  if (heroTrendingServices.length === 0) {
    heroTrendingServices = allServices.slice(0, 3);
  }

  return (
    <div className="min-h-screen bg-background flex flex-col">
      <main id="main-content" className="flex-1">
        <Hero
          locale={locale}
          categories={heroCategories}
          trendingServices={heroTrendingServices}
          allServices={allServices}
        />

        {/* ── 1. Category Discovery Section ("Explore our services.") ── */}
        <Suspense fallback={<CategoriesSkeletonFallback />}>
          <CategoriesStream locale={locale} />
        </Suspense>

        {/* ── 2. Trending Services Showcase (API top-rated, first 8) ── */}
        <Suspense fallback={<div className="py-16 md:py-24 bg-white dark:bg-zinc-950 border-b border-zinc-100" />}>
          <TrendingServicesStream locale={locale} />
        </Suspense>

        {/* ── 3. How It Works / Experience Section ── */}
        <HowItWorks locale={locale} />

        {/* ── 4. Infinite Marquee Testimonials Section ── */}
        <TestimonialsSection locale={locale} />
      </main>
      <Footer locale={locale} />
    </div>
  );
}
