"use client";

import HeroSlider from "@/components/balmy/hero-slider";
import {
  ProductsSectionBalmy,
  PaymentInstallmentBanner,
  BrandsShowcaseSection,
  PromotionalBannerSection,
  TrustFeaturesSection,
} from "@/components/balmy";

import HomePageSkeleton from "@/components/skeletons/home-page-skeleton";
import PageWrapper from "@/components/page-wrapper";
import useHome from "@/hooks/use-home";
import { transformProduct } from "@/lib/markatty-transformer";
import { motion } from "framer-motion";

import RecentlyViewed from "@/components/balmy/recently-viewed";

export default function HomePageClient() {
  const { t, loading, data } = useHome();

  if (loading) {
    return <HomePageSkeleton />;
  }

  // Get bannerImages directly from raw data or transformed sliders
  const bannerImages = data?._raw?.bannerImages || data?.bannerImages || [];

  // Get homeSections from API - this contains the ordered sections with data
  const homeSections = data?._raw?.homeSections || data?.homeSections || [];

  // Render section based on type
  const renderSection = (section: any, index: number) => {
    switch (section.type) {
      case 'category':
        const category = section.data;
        if (!category?.productList || category.productList.length === 0) return null;

        // Transform raw API products so ProductCard fields map correctly
        const transformedProducts = category.productList.map(transformProduct);

        // Use categoryName (from featuredCategories) or label (from carousel) as section title
        const sectionTitle = category.categoryName || category.label || category.type || "Products";

        // Only use categoryId if it's a real category ID (not the carousel section index)
        const realCategoryId = category.categoryId || undefined;

        return (
          <ProductsSectionBalmy
            key={`category-${realCategoryId || index}`}
            title={sectionTitle}
            products={transformedProducts}
            categoryId={realCategoryId}
            maxProducts={8}
          />
        );

      case 'payment_installment':
        return <PaymentInstallmentBanner key={`payment-${index}`} />;

      case 'partners':
        // Find the first real categoryId from homeSections for temporary brand links
        const firstCategoryId = homeSections
          .filter((s: any) => s.type === 'category' && s.data?.categoryId)
          .map((s: any) => s.data.categoryId)[0];

        return (
          <BrandsShowcaseSection
            key={`partners-${index}`}
            title={section.data?.title}
            subtitle={section.data?.subtitle}
            partners={section.data?.partners}
            fallbackCategoryId={firstCategoryId}
          />
        );

      case 'ad':
        return (
          <PromotionalBannerSection
            key={`ad-${index}`}
            ad={section.data}
          />
        );

      case 'promotions':
        return (
          <TrustFeaturesSection
            key={`promotions-${index}`}
            promotions={section.data}
          />
        );

      default:
        return null;
    }
  };

  return (
    <>
      {/* Hero Slider Section with dynamic banners */}
      <HeroSlider banners={bannerImages} />

      <PageWrapper yPadding="py-2.5">
        <div className="my-8 flex flex-col gap-10 relative">

          {/* Render homeSections from API in order — scroll-triggered stagger */}
          {homeSections.map((section: any, index: number) => {
            const content = renderSection(section, index);
            if (!content) return null;
            return (
              <motion.div
                key={`section-${index}`}
                initial={{ opacity: 0, y: 24 }}
                whileInView={{ opacity: 1, y: 0 }}
                viewport={{ once: true, margin: "-80px" }}
                transition={{ duration: 0.4, delay: Math.min(index * 0.06, 0.36), ease: "easeOut" }}
              >
                {content}
              </motion.div>
            );
          })}
          {/* Recently Viewed Products — persisted in localStorage */}
          <RecentlyViewed />

        </div>
      </PageWrapper>
    </>
  );
}
