'use client';

import React, { useEffect, useState } from 'react';
import Link from 'next/link';
import Image from 'next/image';
import { useRouter } from 'next/navigation';
import api from '@/lib/api';
import { Header } from '@/components/Header';
import { Footer } from '@/components/Footer';
import { ProductCard } from '@/components/ProductCard';
import { useCart } from '@/context/CartContext';
import { useSiteSettings } from '@/context/SiteSettingsContext';
import * as LucideIcons from 'lucide-react';
import { 
  ChevronRight, 
  ArrowRight, 
  Star, 
  Truck, 
  ShieldCheck, 
  Clock, 
  ChevronLeft, 
  ArrowUpRight,
  ShoppingCart,
  Loader2,
  Check
} from 'lucide-react';

interface Product {
  id: number;
  name: string;
  slug: string;
  price: number;
  compare_at_price?: number;
  sale_price?: number;
  image_url: string;
  category?: {
    name: string;
    slug: string;
  };
  is_best_selling?: boolean;
}

interface Category {
  id: number;
  name: string;
  slug: string;
  description?: string;
  image_url?: string;
}

interface CategoryWithProducts {
  category: Category;
  products: Product[];
}

const DynamicIcon = ({ name, ...props }: { name: string; [key: string]: any }) => {
  const IconComponent = (LucideIcons as any)[name];
  if (!IconComponent) return <LucideIcons.ShieldCheck {...props} />;
  return <IconComponent {...props} />;
};

export default function Home() {
  const { addToCart } = useCart();
  const { settings, formatPrice } = useSiteSettings();
  const router = useRouter();

  const [latestProducts, setLatestProducts] = useState<Product[]>([]);
  const [featuredProducts, setFeaturedProducts] = useState<Product[]>([]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [categorySections, setCategorySections] = useState<CategoryWithProducts[]>([]);
  const [loading, setLoading] = useState(true);
  const [sectionsLoading, setSectionsLoading] = useState(true);
  const [activeSlide, setActiveSlide] = useState(0);
  const [cartLoading, setCartLoading] = useState<Record<number, boolean>>({});

  // Just For You states
  const [justForYouProducts, setJustForYouProducts] = useState<Product[]>([]);
  const [justForYouPage, setJustForYouPage] = useState(1);
  const [loadingMore, setLoadingMore] = useState(false);
  const [hasMoreJustForYou, setHasMoreJustForYou] = useState(true);

  // Middle slider states
  const [middleSlide, setMiddleSlide] = useState(0);
  const middleSlides = (settings?.sliders?.middle || []).map(slide => ({
    title: slide.title,
    subtitle: slide.subtitle,
    badge: slide.badge,
    bgGradient: slide.bg_gradient || "from-[#003b20] via-emerald-950/90 to-[#003b20]",
    image: slide.image,
    link_url: slide.link_url
  }));

  // Load More logic for Just For You
  const handleLoadMoreJustForYou = async () => {
    if (loadingMore || !hasMoreJustForYou) return;
    setLoadingMore(true);
    const nextPage = justForYouPage + 1;
    try {
      const res = await api.get(`/api/products?page=${nextPage}`);
      const items = res.data.data;
      if (Array.isArray(items)) {
        setJustForYouProducts((prev) => [...prev, ...items]);
        setJustForYouPage(nextPage);
        setHasMoreJustForYou(res.data.current_page < res.data.last_page);
      }
    } catch (err) {
      console.error('Failed to load more products', err);
    } finally {
      setLoadingMore(false);
    }
  };

  const handleAddToCart = (e: React.MouseEvent, product: any) => {
    e.preventDefault();
    e.stopPropagation();

    const productId = product.id;
    // Show instant loading → success feedback
    setCartLoading(prev => ({ ...prev, [productId]: true }));
    setTimeout(() => setCartLoading(prev => ({ ...prev, [productId]: false })), 600);

    // Fire and forget — CartContext optimistic update makes it instant
    addToCart(productId, null, 1, false, product).catch((err) => {
      console.warn('Add to cart failed', err);
    });
  };

  const handleDirectOrder = async (e: React.MouseEvent, product: any) => {
    e.preventDefault();
    e.stopPropagation();

    const productId = product.id;
    setCartLoading(prev => ({ ...prev, [productId]: true }));
    try {
      await addToCart(productId, null, 1, false, product);
      router.push('/checkout');
    } catch (err) {
      alert(err instanceof Object && 'message' in err ? (err as any).message : 'Failed to process order');
      setCartLoading(prev => ({ ...prev, [productId]: false }));
    }
  };

  const scrollRef = React.useRef<HTMLDivElement>(null);
  const [showScrollButtons, setShowScrollButtons] = useState(false);

  const checkScrollOverflow = () => {
    if (scrollRef.current) {
      const { scrollWidth, clientWidth } = scrollRef.current;
      setShowScrollButtons(scrollWidth > clientWidth);
    }
  };

  useEffect(() => {
    if (categories.length > 0) {
      const timer = setTimeout(checkScrollOverflow, 150);
      window.addEventListener('resize', checkScrollOverflow);
      return () => {
        clearTimeout(timer);
        window.removeEventListener('resize', checkScrollOverflow);
      };
    }
  }, [categories]);

  const handleScroll = (direction: 'left' | 'right') => {
    if (scrollRef.current) {
      const { scrollLeft } = scrollRef.current;
      const scrollAmount = 300;
      scrollRef.current.scrollTo({
        left: direction === 'left' ? scrollLeft - scrollAmount : scrollLeft + scrollAmount,
        behavior: 'smooth'
      });
    }
  };

  const [isHovered, setIsHovered] = useState(false);

  useEffect(() => {
    if (isHovered || categories.length === 0) return;

    const interval = setInterval(() => {
      if (scrollRef.current) {
        const { scrollLeft, scrollWidth, clientWidth } = scrollRef.current;
        // If reached the end, scroll back to the start, otherwise scroll right by one item
        if (scrollLeft + clientWidth >= scrollWidth - 15) {
          scrollRef.current.scrollTo({ left: 0, behavior: 'smooth' });
        } else {
          scrollRef.current.scrollTo({ left: scrollLeft + 150, behavior: 'smooth' });
        }
      }
    }, 3000);

    return () => clearInterval(interval);
  }, [isHovered, categories]);


  const heroSlides = (settings?.sliders?.hero || []).map(slide => ({
    title: slide.title,
    subtitle: slide.subtitle,
    btnText: slide.btn_text,
    link: slide.link_url || '/',
    bgGradient: slide.bg_gradient || "from-[#003b20] via-emerald-950/90 to-[#003b20]",
    badge: slide.badge,
    image: slide.image
  }));

  const heroSideSlide = settings?.sliders?.hero_side?.[0] ?? null;


  // Rotate slides
  useEffect(() => {
    const timer = setInterval(() => {
      setActiveSlide((prev) => (prev + 1) % heroSlides.length);
    }, 5000);
    return () => clearInterval(timer);
  }, [heroSlides.length]);

  // Rotate middle slides
  useEffect(() => {
    const timer = setInterval(() => {
      setMiddleSlide((prev) => (prev + 1) % middleSlides.length);
    }, 4000);
    return () => clearInterval(timer);
  }, [middleSlides.length]);

  useEffect(() => {
    // 1. Try to load cached data from localStorage for instant rendering
    if (typeof window !== 'undefined') {
      try {
        const cachedData = localStorage.getItem('homepage_cache');
        if (cachedData) {
          const parsed = JSON.parse(cachedData);
          if (
            Array.isArray(parsed.categories) && 
            Array.isArray(parsed.latestProducts) && 
            Array.isArray(parsed.featuredProducts) &&
            Array.isArray(parsed.categorySections)
          ) {
            setCategories(parsed.categories);
            setLatestProducts(parsed.latestProducts);
            setFeaturedProducts(parsed.featuredProducts);
            setCategorySections(parsed.categorySections);
            if (Array.isArray(parsed.justForYouProducts)) {
              setJustForYouProducts(parsed.justForYouProducts);
            }
            setLoading(false);
            setSectionsLoading(false);
          }
        }
      } catch (err) {
        console.error('Failed to load homepage cache from localStorage', err);
      }
    }

    const loadHomeData = async () => {
      try {
        const res = await api.get('/api/home-data');
        
        const latest = res.data.latestProducts;
        const featured = res.data.featuredProducts;
        const categoriesList = res.data.categories;
        const sections = res.data.categorySections;

        setLatestProducts(Array.isArray(latest) ? latest : []);
        setFeaturedProducts(Array.isArray(featured) ? featured : []);
        setCategories(Array.isArray(categoriesList) ? categoriesList : []);
        setCategorySections(Array.isArray(sections) ? sections : []);
        
        // Cache the newly fetched data in localStorage
        if (typeof window !== 'undefined') {
          try {
            const cachedData = localStorage.getItem('homepage_cache');
            const parsed = cachedData ? JSON.parse(cachedData) : {};
            parsed.categories = categoriesList;
            parsed.latestProducts = latest;
            parsed.featuredProducts = featured;
            parsed.categorySections = sections;
            localStorage.setItem('homepage_cache', JSON.stringify(parsed));
          } catch (cacheErr) {
            console.error('Failed to save homepage cache to localStorage', cacheErr);
          }
        }
      } catch (err) {
        console.error('Failed to load homepage data', err);
      } finally {
        setLoading(false);
        setSectionsLoading(false); // Stop loading category rails at the bottom
      }
    };

    const loadJustForYou = async () => {
      try {
        const res = await api.get('/api/products?page=1');
        const items = res.data.data;
        setJustForYouProducts(Array.isArray(items) ? items : []);
        setHasMoreJustForYou(res.data.current_page < res.data.last_page);

        // Cache in localStorage preserving other cache keys
        if (typeof window !== 'undefined' && Array.isArray(items)) {
          try {
            const cachedData = localStorage.getItem('homepage_cache');
            const parsed = cachedData ? JSON.parse(cachedData) : {};
            parsed.justForYouProducts = items;
            localStorage.setItem('homepage_cache', JSON.stringify(parsed));
          } catch (cacheErr) {
            console.error('Failed to save justForYou cache to localStorage', cacheErr);
          }
        }
      } catch (err) {
        console.error('Failed to load Just For You products', err);
      }
    };

    loadHomeData();
    loadJustForYou();
  }, []);

  // Map category slugs to styled emojis
  const getCategoryIcon = (slug: string) => {
    switch (slug) {
      case 'honey': return '🍯';
      case 'ghee': return '🧈';
      case 'dates': return '🌴';
      case 'oil': return '🫗';
      case 'spices': return '🌶️';
      case 'nuts': return '🥜';
      case 'tea': return '☕';
      case 'rice': return '🌾';
      default: return '📦';
    }
  };

  const renderCategoryRail = (section: CategoryWithProducts) => (
    <section key={section.category.id} className="py-4 bg-white border-b border-slate-100">
      <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 space-y-4">
        <div className="flex items-center justify-between border-b-2 border-slate-100 pb-3">
          <h2 className="text-xl font-normal text-primary border-l-4 border-secondary pl-3">
            {section.category.name}
          </h2>
          <Link 
            href={`/shop?categorySlug=${section.category.slug}`} 
            className="font-open-sans text-[14px] font-semibold text-primary hover:text-primary-dark flex items-center gap-1"
          >
            <span>View All</span>
            <ChevronRight className="h-4 w-4" />
          </Link>
        </div>

        <div className="flex gap-5 overflow-x-auto pb-4 scroll-smooth scrollbar-none snap-x snap-mandatory">
          {section.products.map((product, pIdx) => (
            <div key={product.id} className="w-[175px] sm:w-[225px] shrink-0 snap-start">
              <ProductCard product={product} priority={pIdx < 2} />
            </div>
          ))}
        </div>
      </div>
    </section>
  );

  return (
    <div className="flex flex-col min-h-screen bg-slate-50">
      <Header />

      <main className="flex-1">
        {/* 1. Hero Slide Carousel & Teaser Banner */}
        <section className="pt-1.5 md:pt-6 pb-2 bg-white">
          <div className="mx-auto max-w-7xl px-1.5 sm:px-6 lg:px-8">
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 items-stretch">
              
              {/* Left Side Slide Carousel */}
              <div className="lg:col-span-2 relative w-full rounded-2xl overflow-hidden shadow-sm group">
                {heroSlides.length === 0 ? (
                  <img src="/hero_banner_placeholder.png" alt="Upload Hero Banner" className="w-full h-auto block" />
                ) : (
                  <>
                    {heroSlides.map((slide, idx) => {
                      const hasOverlay = !!(slide.title || slide.subtitle || slide.badge || slide.btnText);
                      const imageUrl = slide.image
                        ? (slide.image.startsWith('http')
                            ? slide.image
                            : `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'}/storage/${slide.image}`)
                        : null;
                      const isActive = idx === activeSlide;

                      const slideInner = (
                        <div
                          className={`transition-opacity duration-1000 ${
                            isActive ? 'relative opacity-100 z-10' : 'absolute inset-0 opacity-0 z-0'
                          }`}
                        >
                          {imageUrl ? (
                            <>
                              {/* Full image — no crop */}
                              <img
                                src={imageUrl}
                                alt={slide.title || ''}
                                className="w-full block"
                                style={{ visibility: isActive ? 'visible' : 'hidden' }}
                              />
                              {/* Text overlay on top */}
                              {hasOverlay && (
                                <div
                                  className="absolute inset-0 flex flex-col justify-center px-6 md:px-16 text-white"
                                  style={{ background: 'linear-gradient(to right, rgba(0,0,0,0.70), rgba(0,0,0,0.15))' }}
                                >
                                  <div className="relative space-y-2 md:space-y-4 max-w-lg">
                                    {slide.badge && (
                                      <span className="inline-block px-2.5 py-0.5 md:px-3 md:py-1 rounded bg-primary text-[8px] md:text-[10px] font-bold uppercase tracking-wider w-fit">
                                        {slide.badge}
                                      </span>
                                    )}
                                    {slide.title && (
                                      <h1 className="text-lg sm:text-2xl md:text-4xl lg:text-5xl font-black leading-tight">
                                        {slide.title}
                                      </h1>
                                    )}
                                    {slide.subtitle && (
                                      <p className="text-[10px] sm:text-sm text-slate-200">{slide.subtitle}</p>
                                    )}
                                    {slide.btnText && (
                                      <div className="pt-1 md:pt-2">
                                        <span className="inline-flex items-center gap-1.5 md:gap-2 rounded bg-primary hover:bg-primary-dark px-4 py-2 md:px-6 md:py-3 text-xs md:text-sm font-bold transition-all shadow-md shadow-emerald-950/25">
                                          <span>{slide.btnText}</span>
                                          <ArrowRight className="h-3.5 w-3.5 md:h-4 md:w-4" />
                                        </span>
                                      </div>
                                    )}
                                  </div>
                                </div>
                              )}
                            </>
                          ) : (
                            /* No image — gradient background */
                            <div
                              className={`min-h-[200px] sm:min-h-[300px] bg-gradient-to-br ${slide.bgGradient} text-white flex flex-col justify-center px-6 md:px-16 relative`}
                            >
                              <div className="absolute inset-0 opacity-5 bg-[linear-gradient(to_right,#808080_1px,transparent_1px),linear-gradient(to_bottom,#808080_1px,transparent_1px)] bg-[size:16px_16px]" />
                              {hasOverlay && (
                                <div className="relative space-y-2 md:space-y-4 max-w-lg">
                                  {slide.badge && (
                                    <span className="inline-block px-2.5 py-0.5 md:px-3 md:py-1 rounded bg-primary text-[8px] md:text-[10px] font-bold uppercase tracking-wider w-fit">
                                      {slide.badge}
                                    </span>
                                  )}
                                  {slide.title && (
                                    <h1 className="text-lg sm:text-2xl md:text-4xl lg:text-5xl font-black leading-tight">
                                      {slide.title}
                                    </h1>
                                  )}
                                  {slide.subtitle && (
                                    <p className="text-[10px] sm:text-sm text-slate-200">{slide.subtitle}</p>
                                  )}
                                  {slide.btnText && (
                                    <div className="pt-1 md:pt-2">
                                      <span className="inline-flex items-center gap-1.5 md:gap-2 rounded bg-primary hover:bg-primary-dark px-4 py-2 md:px-6 md:py-3 text-xs md:text-sm font-bold transition-all shadow-md shadow-emerald-950/25">
                                        <span>{slide.btnText}</span>
                                        <ArrowRight className="h-3.5 w-3.5 md:h-4 md:w-4" />
                                      </span>
                                    </div>
                                  )}
                                </div>
                              )}
                            </div>
                          )}
                        </div>
                      );

                      return !hasOverlay && slide.link ? (
                        <Link href={slide.link} key={idx}>{slideInner}</Link>
                      ) : (
                        <div key={idx}>{slideInner}</div>
                      );
                    })}

                    {/* Slideshow dots */}
                    <div className="absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2 z-20">
                      {heroSlides.map((_, idx) => (
                        <button
                          key={idx}
                          onClick={() => setActiveSlide(idx)}
                          className={`h-2.5 w-2.5 rounded-full transition-all ${
                            idx === activeSlide ? 'bg-primary w-6' : 'bg-white/60'
                          }`}
                        />
                      ))}
                    </div>
                  </>
                )}
              </div>


              {/* Right Side Teaser Panel — admin controlled (hero_side type slider) */}
              {(() => {
                if (!heroSideSlide) {
                  return (
                    <div className="hidden lg:block relative w-full lg:aspect-[455/372] rounded-2xl overflow-hidden shadow-sm">
                      <img src="/hero_side_placeholder.png" alt="Upload Side Banner" className="absolute inset-0 w-full h-full object-cover" />
                    </div>
                  );
                }

                const hasOverlay = !!(heroSideSlide.title || heroSideSlide.subtitle || heroSideSlide.badge || heroSideSlide.btn_text);
                const imageUrl = heroSideSlide.image
                  ? (heroSideSlide.image.startsWith('http')
                      ? heroSideSlide.image
                      : `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'}/storage/${heroSideSlide.image}`)
                  : null;

                const sideContent = (
                  <div
                    className="hidden lg:flex relative w-full aspect-[1.6/1] lg:aspect-[455/372] rounded-2xl overflow-hidden shadow-sm text-white flex-col justify-end p-8 group"
                    style={imageUrl ? {
                      backgroundImage: hasOverlay
                        ? `linear-gradient(to top, rgba(0,0,0,0.75) 40%, rgba(0,0,0,0.15)), url(${imageUrl})`
                        : `url(${imageUrl})`,
                      backgroundSize: 'cover',
                      backgroundPosition: 'center'
                    } : { background: 'linear-gradient(to bottom right, #003b20, #00522c)' }}
                  >
                    <div className="absolute inset-0 opacity-10 bg-[linear-gradient(to_right,#808080_1px,transparent_1px),linear-gradient(to_bottom,#808080_1px,transparent_1px)] bg-[size:20px_20px]"></div>
                    {hasOverlay && (
                      <div className="relative space-y-3 z-10">
                        {heroSideSlide.badge && (
                          <span className="text-orange-400 font-bold text-xs uppercase tracking-widest">{heroSideSlide.badge}</span>
                        )}
                        {heroSideSlide.title && (
                          <h2 className="text-xl sm:text-2xl lg:text-3xl font-black leading-snug">{heroSideSlide.title}</h2>
                        )}
                        {heroSideSlide.subtitle && (
                          <p className="text-xs text-slate-300">{heroSideSlide.subtitle}</p>
                        )}
                        {heroSideSlide.btn_text && heroSideSlide.link_url && (
                          <span className="inline-flex items-center gap-1 text-orange-400 hover:text-orange-300 font-bold text-sm pt-2">
                            <span>{heroSideSlide.btn_text}</span>
                            <ArrowUpRight className="h-4 w-4" />
                          </span>
                        )}
                      </div>
                    )}
                  </div>
                );

                return !hasOverlay && heroSideSlide.link_url ? (
                  <Link href={heroSideSlide.link_url} className="hidden lg:block">
                    {sideContent}
                  </Link>
                ) : (
                  sideContent
                );
              })()}

            </div>
          </div>
        </section>

        {/* 2. Rounded Square Category Carousel Slider */}
        <section className="pt-1.5 md:pt-4 pb-6 bg-slate-50/50 border-b border-slate-100">
          <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 text-center relative">
            <h2 className="text-2xl font-normal text-slate-800 mb-4 tracking-tight">
              Featured Categories
            </h2>

            {loading ? (
              <div className="flex gap-5 justify-center overflow-hidden">
                {[...Array(8)].map((_, i) => (
                  <div key={i} className="flex flex-col items-center gap-3 animate-pulse">
                    <div className="h-28 w-28 md:h-32 md:w-32 rounded-2xl bg-slate-200"></div>
                    <div className="h-3 bg-slate-200 rounded w-16"></div>
                  </div>
                ))}
              </div>
            ) : (
              <div 
                className="relative px-4"
                onMouseEnter={() => setIsHovered(true)}
                onMouseLeave={() => setIsHovered(false)}
              >
                {/* Left navigation arrow */}
                {showScrollButtons && (
                  <button
                    onClick={() => handleScroll('left')}
                    className="absolute left-0 top-1/2 -translate-y-1/2 bg-primary hover:bg-primary-dark text-white rounded-full w-9 h-9 flex items-center justify-center shadow-md transition-all duration-200 z-20 focus:outline-none"
                    aria-label="Scroll Left"
                  >
                    <ChevronLeft className="h-5 w-5 stroke-[2.5]" />
                  </button>
                )}

                {/* Categories container */}
                <div
                  ref={scrollRef}
                  className="flex gap-5 items-center justify-start overflow-x-auto pt-2 pb-2 scroll-smooth scrollbar-none"
                >
                  {categories.map((category, index) => (
                    <Link
                      key={category.id}
                      href={`/shop?categorySlug=${category.slug}`}
                      className="flex flex-col items-center gap-3 group shrink-0"
                    >
                      <div className="w-28 h-28 md:w-32 md:h-32 bg-white border border-slate-100 rounded-2xl shadow-sm flex items-center justify-center p-4 transition-all duration-300 group-hover:-translate-y-1 group-hover:shadow-md group-hover:border-primary relative overflow-hidden">
                        <Image
                          src={category.image_url || `/images/categories/${category.slug}.png`}
                          alt={category.name}
                          fill
                          sizes="(max-width: 768px) 112px, 128px"
                          priority={index < 4}
                          onError={(e) => {
                            e.currentTarget.src = '/images/placeholder.jpg';
                          }}
                          className="object-contain p-4 transition-transform duration-300 group-hover:scale-105"
                        />
                      </div>
                      <span className="text-xs md:text-sm font-bold text-slate-700 group-hover:text-primary transition-colors">
                        {category.name}
                      </span>
                    </Link>
                  ))}
                </div>

                {/* Right navigation arrow */}
                {showScrollButtons && (
                  <button
                    onClick={() => handleScroll('right')}
                    className="absolute right-0 top-1/2 -translate-y-1/2 bg-primary hover:bg-primary-dark text-white rounded-full w-9 h-9 flex items-center justify-center shadow-md transition-all duration-200 z-20 focus:outline-none"
                    aria-label="Scroll Right"
                  >
                    <ChevronRight className="h-5 w-5 stroke-[2.5]" />
                  </button>
                )}
              </div>
            )}
          </div>
        </section>

        {/* 3. Top Selling Products (হট ডিল) */}
        {(loading || featuredProducts.length > 0) && (
          <section className="pt-0 pb-4 bg-white">
            <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 space-y-6">
              <div className="text-center space-y-2 mb-5">
                <h2 className="text-3xl font-normal text-slate-800 tracking-tight">
                  Top Selling Products
                </h2>
                <div className="h-1 w-20 bg-primary mx-auto rounded-full"></div>
              </div>

              {loading ? (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  {[...Array(4)].map((_, i) => (
                    <div key={i} className="bg-slate-50 border border-slate-100 rounded-3xl p-6 flex items-center gap-6 animate-pulse">
                      <div className="w-1/3 aspect-square bg-slate-200 rounded-2xl"></div>
                      <div className="flex-1 space-y-3">
                        <div className="h-4 bg-slate-200 rounded w-3/4"></div>
                        <div className="h-4 bg-slate-200 rounded w-1/2"></div>
                        <div className="h-8 bg-slate-200 rounded w-full"></div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="grid grid-cols-2 lg:grid-cols-2 gap-6">
                  {featuredProducts.map((product, index) => {
                    const price = product.sale_price ?? product.price;
                    const comparePrice = product.compare_at_price;
                    const savings = comparePrice && comparePrice > price ? (comparePrice - price) : 0;
                    const isBestSelling = product.is_best_selling;
                    
                    const resolvedImageUrl = product.image_url.startsWith('http') 
                      ? product.image_url 
                      : `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'}${product.image_url}`;

                    return (
                      <React.Fragment key={product.id}>
                        {/* Desktop layout: horizontal card */}
                        <div className="hidden md:flex relative bg-white border border-slate-200 rounded-3xl p-6 items-center gap-6 shadow-sm group">
                          {isBestSelling && (
                            <span className="absolute -top-2.5 right-6 bg-[#ef4444] text-white text-[10px] font-extrabold px-3 py-1 rounded-md shadow-sm z-10 uppercase tracking-wider">
                              ★ Best Selling
                            </span>
                          )}
                          
                          {/* Image */}
                          <Link href={`/products/${product.slug}`} className="w-1/3 aspect-square relative flex-shrink-0 bg-slate-50 rounded-2xl overflow-hidden p-2 flex items-center justify-center">
                            <Image
                              src={resolvedImageUrl}
                              alt={product.name}
                              fill
                              sizes="(max-width: 1024px) 33vw, 15vw"
                              priority={index < 2}
                              className="object-contain p-2 transition-transform duration-500 ease-in-out group-hover:scale-110"
                            />
                          </Link>

                          {/* Info */}
                          <div className="flex-1 flex flex-col gap-2">
                            <h3 className="text-[16px] font-medium font-open-sans text-slate-800 line-clamp-2 hover:text-primary transition-colors">
                              <Link href={`/products/${product.slug}`}>{product.name}</Link>
                            </h3>
                            
                            <div className="flex flex-col gap-1.5">
                              <div className="flex items-baseline gap-2">
                                <span className="text-[16px] font-semibold font-poppins text-secondary">{formatPrice(price)}</span>
                                {comparePrice && comparePrice > price && (
                                  <span className="text-[12px] font-normal font-poppins text-slate-400 line-through">{formatPrice(comparePrice)}</span>
                                )}
                              </div>
                              {savings > 0 && (
                                <div>
                                  <span className="inline-block bg-emerald-50 text-emerald-600 px-2 py-0.5 rounded-md text-[10px] font-extrabold">
                                    Save {formatPrice(savings)}
                                  </span>
                                </div>
                              )}
                            </div>

                            {/* Action Buttons */}
                            <div className="flex items-center gap-3 mt-2">
                              <button
                                onClick={(e) => handleAddToCart(e, product)}
                                disabled={cartLoading[product.id]}
                                className="px-4 py-2 bg-white hover:bg-secondary border border-secondary text-secondary hover:text-white text-[12px] md:text-[14px] font-semibold font-open-sans rounded-xl transition-all flex items-center justify-center gap-1.5 active:scale-[0.98] disabled:opacity-50"
                              >
                                <ShoppingCart className="h-3.5 w-3.5" />
                                <span>Add To Cart</span>
                              </button>
                              <button
                                onClick={(e) => handleDirectOrder(e, product)}
                                disabled={cartLoading[product.id]}
                                className="px-5 py-2 bg-secondary hover:bg-secondary-dark text-white text-[12px] md:text-[14px] font-semibold font-open-sans rounded-xl transition-all shadow-md shadow-secondary/20 flex items-center justify-center active:scale-[0.98] disabled:opacity-50"
                              >
                                Buy now
                              </button>
                            </div>
                          </div>
                        </div>

                        {/* Mobile layout: normal vertical product card */}
                        <div className="flex md:hidden w-full">
                          <ProductCard product={product} priority={index < 2} />
                        </div>
                      </React.Fragment>
                    );
                  })}
                </div>
              )}
            </div>
          </section>
        )}

        {/* 4. Brand Qualities / Trust badges */}
        <section className="py-4 bg-slate-50 border-y border-slate-100">
          <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 flex sm:grid sm:grid-cols-3 gap-6 overflow-x-auto sm:overflow-x-visible pb-3 sm:pb-0 scrollbar-none snap-x snap-mandatory">
            {settings?.trust_badges && settings.trust_badges.length > 0 ? (
              settings.trust_badges.map((badge, idx) => {
                const colors = [
                  { bg: 'bg-emerald-50', text: 'text-primary' },
                  { bg: 'bg-amber-50', text: 'text-orange-500' },
                  { bg: 'bg-blue-50', text: 'text-blue-600' }
                ];
                const colorScheme = colors[idx % colors.length];

                return (
                  <div key={badge.id} className="flex items-center gap-4 bg-white p-4 sm:p-5 rounded-xl border border-slate-100 shadow-sm shrink-0 w-[280px] sm:w-auto snap-start">
                    <div className={`p-3 ${colorScheme.bg} ${colorScheme.text} rounded-full shrink-0`}>
                      <DynamicIcon name={badge.icon} className="h-6 w-6" />
                    </div>
                    <div>
                      <h4 className="font-open-sans text-[13px] sm:text-[15px] font-semibold text-slate-800 leading-snug">{badge.title}</h4>
                      <p className="font-open-sans text-[12px] sm:text-[14px] font-medium text-slate-500 mt-0.5 leading-snug">{badge.description}</p>
                    </div>
                  </div>
                );
              })
            ) : (
              <>
                <div className="flex items-center gap-4 bg-white p-4 sm:p-5 rounded-xl border border-slate-100 shadow-sm shrink-0 w-[280px] sm:w-auto snap-start">
                  <div className="p-3 bg-emerald-50 text-primary rounded-full shrink-0">
                    <Truck className="h-6 w-6" />
                  </div>
                  <div>
                    <h4 className="font-open-sans text-[13px] sm:text-[15px] font-semibold text-slate-800 leading-snug">ক্যাশ অন ডেলিভারি</h4>
                    <p className="font-open-sans text-[12px] sm:text-[14px] font-medium text-slate-500 mt-0.5 leading-snug">ঢাকা ও সারা বাংলাদেশে ক্যাশ অন ডেলিভারি সুবিধা</p>
                  </div>
                </div>
                <div className="flex items-center gap-4 bg-white p-4 sm:p-5 rounded-xl border border-slate-100 shadow-sm shrink-0 w-[280px] sm:w-auto snap-start">
                  <div className="p-3 bg-amber-50 text-orange-500 rounded-full shrink-0">
                    <ShieldCheck className="h-6 w-6" />
                  </div>
                  <div>
                    <h4 className="font-open-sans text-[13px] sm:text-[15px] font-semibold text-slate-800 leading-snug">শতভাগ খাঁটি পণ্য</h4>
                    <p className="font-open-sans text-[12px] sm:text-[14px] font-medium text-slate-500 mt-0.5 leading-snug">পণ্য অপছন্দ হলে সাথে সাথে ফেরত দেওয়ার নিশ্চয়তা</p>
                  </div>
                </div>
                <div className="flex items-center gap-4 bg-white p-4 sm:p-5 rounded-xl border border-slate-100 shadow-sm shrink-0 w-[280px] sm:w-auto snap-start">
                  <div className="p-3 bg-blue-50 text-blue-600 rounded-full shrink-0">
                    <Clock className="h-6 w-6" />
                  </div>
                  <div>
                    <h4 className="font-open-sans text-[13px] sm:text-[15px] font-semibold text-slate-800 leading-snug">২৪/৭ কাস্টমার সাপোর্ট</h4>
                    <p className="font-open-sans text-[12px] sm:text-[14px] font-medium text-slate-500 mt-0.5 leading-snug">পণ্য সংগ্রহ ও জিজ্ঞাসা নিয়ে যেকোনো সময় কল করুন</p>
                  </div>
                </div>
              </>
            )}
          </div>
        </section>

        {/* 5. Dynamic Category Rails (যেমন: মধু, ঘি, খেজুর ইত্যাদি) */}
        {sectionsLoading ? (
          <section className="py-4 bg-white">
            <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 space-y-6">
              <div className="h-6 bg-slate-200 animate-pulse rounded w-1/4"></div>
              <div className="flex gap-5 overflow-x-auto pb-4 scrollbar-none">
                {[...Array(5)].map((_, i) => (
                  <div key={i} className="flex flex-col gap-3 w-[175px] sm:w-[225px] shrink-0">
                    <div className="aspect-square bg-slate-200 animate-pulse rounded-xl w-full"></div>
                    <div className="h-3 bg-slate-200 animate-pulse rounded w-3/4"></div>
                    <div className="h-3 bg-slate-200 animate-pulse rounded w-1/2"></div>
                  </div>
                ))}
              </div>
            </div>
          </section>
        ) : (
          <>
            {categorySections.slice(0, 3).map(renderCategoryRail)}

            {/* Banner Slider after 3rd category (or at the bottom if less than 3 categories) */}
            {middleSlides.length > 0 && (
              <section className="py-4 bg-white">
                <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
                  <div className="relative w-full rounded-2xl overflow-hidden shadow-sm group">
                    {middleSlides.map((slide, sIdx) => {
                      const hasOverlay = !!(slide.title || slide.subtitle || slide.badge);
                      const imageUrl = slide.image
                        ? (slide.image.startsWith('http')
                            ? slide.image
                            : `${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'}/storage/${slide.image}`)
                        : null;
                      const isActive = sIdx === middleSlide;

                      const slideInner = (
                        <div
                          key={sIdx}
                          className={`transition-opacity duration-1000 ${
                            isActive ? 'relative opacity-100 z-10' : 'absolute inset-0 opacity-0 z-0'
                          }`}
                        >
                          {imageUrl ? (
                            <>
                              {/* Full image — no crop */}
                              <img
                                src={imageUrl}
                                alt={slide.title || ''}
                                className="w-full block"
                                style={{ visibility: isActive ? 'visible' : 'hidden' }}
                              />
                              {/* Text overlay */}
                              {hasOverlay && (
                                <div
                                  className="absolute inset-0 flex flex-col justify-center px-6 md:px-16 text-white"
                                  style={{ background: 'linear-gradient(to right, rgba(0,0,0,0.70), rgba(0,0,0,0.15))' }}
                                >
                                  <div className="relative space-y-2 md:space-y-4 max-w-lg">
                                    {slide.badge && (
                                      <span className="inline-block px-2.5 py-0.5 rounded bg-primary text-[8px] md:text-[10px] font-bold uppercase tracking-wider">
                                        {slide.badge}
                                      </span>
                                    )}
                                    {slide.title && (
                                      <h3 className="text-sm sm:text-lg md:text-2xl lg:text-4xl font-black leading-tight">
                                        {slide.title}
                                      </h3>
                                    )}
                                    {slide.subtitle && (
                                      <p className="text-[10px] sm:text-xs md:text-sm text-slate-200">{slide.subtitle}</p>
                                    )}
                                  </div>
                                </div>
                              )}
                            </>
                          ) : (
                            /* No image — gradient background */
                            <div
                              className={`min-h-[140px] sm:min-h-[200px] bg-gradient-to-br ${slide.bgGradient} text-white flex flex-col justify-center px-6 md:px-16 relative`}
                            >
                              <div className="absolute inset-0 opacity-5 bg-[linear-gradient(to_right,#808080_1px,transparent_1px),linear-gradient(to_bottom,#808080_1px,transparent_1px)] bg-[size:16px_16px]" />
                              {hasOverlay && (
                                <div className="relative space-y-2 md:space-y-4 max-w-lg">
                                  {slide.badge && (
                                    <span className="inline-block px-2.5 py-0.5 rounded bg-primary text-[8px] md:text-[10px] font-bold uppercase tracking-wider">
                                      {slide.badge}
                                    </span>
                                  )}
                                  {slide.title && (
                                    <h3 className="text-sm sm:text-lg md:text-2xl lg:text-4xl font-black leading-tight">
                                      {slide.title}
                                    </h3>
                                  )}
                                  {slide.subtitle && (
                                    <p className="text-[10px] sm:text-xs md:text-sm text-slate-200">{slide.subtitle}</p>
                                  )}
                                </div>
                              )}
                            </div>
                          )}
                        </div>
                      );

                      const slideLink = slide.link_url || '/shop';
                      return !hasOverlay ? (
                        <Link href={slideLink} key={sIdx}>{slideInner}</Link>
                      ) : (
                        <div key={sIdx}>{slideInner}</div>
                      );
                    })}

                    {/* Dot indicators */}
                    {middleSlides.length > 1 && (
                      <div className="absolute bottom-3 left-1/2 -translate-x-1/2 flex gap-2 z-20">
                        {middleSlides.map((_, sIdx) => (
                          <button
                            key={sIdx}
                            onClick={() => setMiddleSlide(sIdx)}
                            className={`h-1.5 w-1.5 md:h-2 md:w-2 rounded-full transition-all ${
                              sIdx === middleSlide ? 'bg-primary w-4 md:w-6' : 'bg-white/60'
                            }`}
                          />
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              </section>
            )}

            {categorySections.slice(3, 5).map(renderCategoryRail)}
          </>
        )}

        {/* Just For You Section */}
        <section className="pt-4 pb-4 bg-white border-b border-slate-100">
          <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 space-y-4">
            <div className="flex items-center justify-between border-b-2 border-slate-100 pb-3">
              <h2 className="text-xl font-normal text-primary border-l-4 border-secondary pl-3">
                Just For You
              </h2>
              <Link 
                href="/shop" 
                className="font-open-sans text-[14px] font-semibold text-primary hover:text-primary-dark flex items-center gap-1"
              >
                <span>View All</span>
                <ChevronRight className="h-4 w-4" />
              </Link>
            </div>

            <div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-5 gap-6">
              {justForYouProducts.map((product, pIdx) => (
                <ProductCard key={product.id} product={product} priority={pIdx < 4} />
              ))}
            </div>

            {hasMoreJustForYou && (
              <div className="flex justify-center pt-4">
                <button
                  onClick={handleLoadMoreJustForYou}
                  disabled={loadingMore}
                  className="inline-flex items-center justify-center gap-2 border border-primary text-primary bg-white hover:bg-primary hover:text-white transition-all duration-300 font-bold py-2.5 px-6 rounded-lg text-sm disabled:opacity-50 cursor-pointer active:scale-[0.98]"
                >
                  {loadingMore ? (
                    <>
                      <Loader2 className="h-4 w-4 animate-spin" />
                      <span>Loading...</span>
                    </>
                  ) : (
                    <span>Load More</span>
                  )}
                </button>
              </div>
            )}
          </div>
        </section>


        {/* 7. Customer Testimonials / Reviews */}
        <section className="py-4 bg-slate-50">
          <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 space-y-10">
            <div className="text-center space-y-2">
              <h2 className="font-open-sans text-[18px] md:text-[24px] font-semibold text-primary">
                {settings?.settings?.reviews_title || "আমাদের শুভাকাঙ্ক্ষীদের মতামত"}
              </h2>
              <p className="font-open-sans text-[13px] md:text-[14px] font-medium text-slate-500 max-w-md mx-auto">
                {settings?.settings?.reviews_subtitle || "সওদাবাজারের সেবা ও পণ্যের মান নিয়ে গ্রাহকদের প্রকৃত রিভিউসমূহ"}
              </p>
            </div>

            <div className="-mx-4 px-4 sm:mx-0 sm:px-0 flex md:grid md:grid-cols-3 gap-6 overflow-x-auto md:overflow-x-visible pb-3 md:pb-0 scrollbar-none snap-x snap-mandatory">
              {(settings?.settings?.reviews_list || []).map((review: any, index: number) => {
                const rating = parseInt(review.rating || '5');
                const name = review.name || '';
                const designation = review.designation || '';
                const content = review.content || '';
                const image = review.image || '';
                
                const firstLetter = name.trim().charAt(0) || 'G';
                const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://127.0.0.1:8000';
                
                const imageUrl = image 
                  ? (image.startsWith('http') ? image : `${apiUrl}${image}`)
                  : '';

                return (
                  <div key={index} className="bg-white p-6 rounded-xl border border-slate-100 shadow-sm space-y-4 shrink-0 w-[290px] sm:w-auto snap-start">
                    <div className="flex gap-1">
                      {[...Array(rating)].map((_, i) => (
                        <Star key={i} className="h-4 w-4 fill-yellow-400 text-yellow-400" />
                      ))}
                    </div>
                    <p className="font-open-sans text-[13px] md:text-[15px] font-medium leading-relaxed text-slate-600">
                      "{content}"
                    </p>
                    <div className="flex items-center gap-3">
                      {imageUrl ? (
                        <img 
                          src={imageUrl} 
                          alt={name} 
                          className="h-10 w-10 rounded-full object-cover border border-slate-100"
                        />
                      ) : (
                        <div className="h-10 w-10 rounded-full bg-emerald-100 flex items-center justify-center font-bold text-sm text-primary">
                          {firstLetter}
                        </div>
                      )}
                      <div>
                        <h4 className="font-open-sans text-[13px] md:text-[14px] font-semibold text-slate-800">{name}</h4>
                        <p className="font-open-sans text-[11px] md:text-[12px] font-medium text-slate-400">{designation}</p>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </section>
      </main>

      <Footer />
    </div>
  );
}

// Helper to format prices
function numberWithCommas(x: number | null | undefined) {
  if (x === null || x === undefined || isNaN(Number(x))) {
    return '0';
  }
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
