import UbaidiChat from './UbaidiChat';
import React, { useState, useEffect } from 'react';
import AppDownloadBanner from './AppDownloadBanner';
import { Product, SiteSettings } from '../types';
import { getColorScheme } from '../lib/themeColors';
import {
  ShoppingCart, ChevronLeft, ChevronRight, Star,
  Gift, Zap, ArrowRight, ChevronRight as CRight, Tag, Truck, ShieldCheck, Clock
} from 'lucide-react';

interface HomePageProps {
  settings: SiteSettings;
  featuredProducts: Product[];
  isProductsLoaded: boolean;
  navigateTo: (view: string) => void;
  setDirectCheckoutProduct: (data: { product: Product }) => void;
  onAddToCart?: (product: Product) => void;
  onSelectProduct: (product: Product) => void;
}

const FEATURED_CATEGORIES = [
  { name: 'Oil & Ghee',     image: 'https://images.unsplash.com/photo-1474979266404-7eaacbcd87c5?w=150&h=150&fit=crop' },
  { name: 'Honey',          image: 'https://images.unsplash.com/photo-1587049352851-8d4e89133924?w=150&h=150&fit=crop' },
  { name: 'Dates',          image: 'https://images.unsplash.com/photo-1607532941433-304659e8198a?w=150&h=150&fit=crop' },
  { name: 'Spices',         image: 'https://images.unsplash.com/photo-1532336414038-cf19250c5757?w=150&h=150&fit=crop' },
  { name: 'Nuts & Seeds',   image: 'https://images.unsplash.com/photo-1599599810769-bcde5a160d32?w=150&h=150&fit=crop' },
  { name: 'Herbal',         image: 'https://images.unsplash.com/photo-1512069772995-ec65ed45afd6?w=150&h=150&fit=crop' },
  { name: 'Organic',        image: 'https://images.unsplash.com/photo-1542838132-92c53300491e?w=150&h=150&fit=crop' },
  { name: 'Gift Packs',     image: 'https://images.unsplash.com/photo-1549465220-1a8b9238cd48?w=150&h=150&fit=crop' },
];

const BRANDS = [
  { name: 'Glarvest' }, { name: 'Khejuri' }, { name: 'Shosti' },
  { name: 'Pran' }, { name: 'Fresh' }, { name: 'Organic Valley' },
];

const TESTIMONIALS = [
  { id: 1, name: 'Rafiqul Islam',  profession: 'Housewife',    image: 'https://randomuser.me/api/portraits/women/68.jpg', text: 'The quality of their honey and dates is exceptional! Never disappointed in 6 months.', rating: 5 },
  { id: 2, name: 'Shahana Akter', profession: 'Nutritionist', image: 'https://randomuser.me/api/portraits/women/45.jpg', text: 'Authentic organic products at reasonable prices. Always on time delivery.', rating: 5 },
  { id: 3, name: 'Kamal Hossain', profession: 'Business Owner', image: 'https://randomuser.me/api/portraits/men/32.jpg', text: 'Best place to buy pure ghee and spices. Packaging is excellent and always fresh.', rating: 5 },
];

const DEMO_PRODUCTS: Product[] = [
  { id: '1',  name: 'Fresh Organic Tomatoes', price: 4.99,  image: 'https://images.unsplash.com/photo-1592924357228-91a4daadcfea?w=300&h=300&fit=crop', category: 'Vegetables', description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '2',  name: 'Premium Avocado',        price: 6.99,  image: 'https://images.unsplash.com/photo-1523049673857-eb18f1d7b578?w=300&h=300&fit=crop', category: 'Fruits',     description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '3',  name: 'Organic Bananas',        price: 2.99,  image: 'https://images.unsplash.com/photo-1571501474588-5a8fa8167fe6?w=300&h=300&fit=crop', category: 'Fruits',     description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '4',  name: 'Fresh Broccoli',         price: 3.49,  image: 'https://images.unsplash.com/photo-1459411621453-7b03977f4bfc?w=300&h=300&fit=crop', category: 'Vegetables', description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '5',  name: 'Carrots Pack',           price: 1.99,  image: 'https://images.unsplash.com/photo-1598170845058-32b9d6a5da37?w=300&h=300&fit=crop', category: 'Vegetables', description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '6',  name: 'Organic Lemon',          price: 5.99,  image: 'https://images.unsplash.com/photo-1590502593747-49eb6cc4526d?w=300&h=300&fit=crop', category: 'Fruits',     description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '7',  name: 'Sweet Potatoes',         price: 4.49,  image: 'https://images.unsplash.com/photo-1596040033229-a9821ebd058d?w=300&h=300&fit=crop', category: 'Vegetables', description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '8',  name: 'Green Bell Pepper',      price: 2.49,  image: 'https://images.unsplash.com/photo-1563544605990-2ee2a3fe21aa?w=300&h=300&fit=crop', category: 'Vegetables', description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '9',  name: 'Strawberry Pack',        price: 7.99,  image: 'https://images.unsplash.com/photo-1464965911861-746a04b4bca6?w=300&h=300&fit=crop', category: 'Fruits',     description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '10', name: 'Fresh Garlic',           price: 1.49,  image: 'https://images.unsplash.com/photo-1540148426945-36d5386dbb57?w=300&h=300&fit=crop', category: 'Vegetables', description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '11', name: 'Red Onion',              price: 2.19,  image: 'https://images.unsplash.com/photo-1518977676601-b53f82aba65e?w=300&h=300&fit=crop', category: 'Vegetables', description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '12', name: 'Fresh Cucumber',         price: 1.89,  image: 'https://images.unsplash.com/photo-1604908176997-125f25cc6f3d?w=300&h=300&fit=crop', category: 'Vegetables', description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '13', name: 'Pure Honey',             price: 12.99, image: 'https://images.unsplash.com/photo-1587049352851-8d4e89133924?w=300&h=300&fit=crop', category: 'Groceries',  description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '14', name: 'Fresh Milk',             price: 3.49,  image: 'https://images.unsplash.com/photo-1563636619-e9143da7973b?w=300&h=300&fit=crop', category: 'Dairy',       description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '15', name: 'Farm Eggs',              price: 5.49,  image: 'https://images.unsplash.com/photo-1582722872445-44dc5f7e3c8f?w=300&h=300&fit=crop', category: 'Dairy',       description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '16', name: 'Organic Almonds',        price: 9.99,  image: 'https://images.unsplash.com/photo-1508061253366-f7da158b6d46?w=300&h=300&fit=crop', category: 'Snacks',      description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '17', name: 'Green Grapes',           price: 4.99,  image: 'https://images.unsplash.com/photo-1537640538966-79f369143d8f?w=300&h=300&fit=crop', category: 'Fruits',      description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '18', name: 'Whole Wheat Bread',      price: 3.49,  image: 'https://images.unsplash.com/photo-1509440159596-0249088772ff?w=300&h=300&fit=crop', category: 'Bakery',      description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '19', name: 'Fresh Salmon',           price: 14.99, image: 'https://images.unsplash.com/photo-1519708227418-c8fd9a32b7a2?w=300&h=300&fit=crop', category: 'Meat',        description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '20', name: 'Chicken Breast',         price: 8.99,  image: 'https://images.unsplash.com/photo-1604503468506-a8da13d82791?w=300&h=300&fit=crop', category: 'Meat',        description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '21', name: 'Brown Rice',             price: 2.99,  image: 'https://images.unsplash.com/photo-1586201375761-83865001e31c?w=300&h=300&fit=crop', category: 'Groceries',   description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '22', name: 'Olive Oil',              price: 7.49,  image: 'https://images.unsplash.com/photo-1474979266404-7eaacbcd87c5?w=300&h=300&fit=crop', category: 'Groceries',   description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '23', name: 'Sea Salt',               price: 1.99,  image: 'https://images.unsplash.com/photo-1614283120155-25e227096e57?w=300&h=300&fit=crop', category: 'Groceries',   description: '', gallery: [], nameBangla: '', highlight: '' },
  { id: '24', name: 'Black Pepper',           price: 3.99,  image: 'https://images.unsplash.com/photo-1596647895181-482083072fec?w=300&h=300&fit=crop', category: 'Groceries',   description: '', gallery: [], nameBangla: '', highlight: '' },
];

const ORG = '#F37021'; // orange brand color
const ORG_DARK = '#E05A10';
const ORG_LIGHT = '#FFF5EE';

// ── Shared Stars ──────────────────────────────────────────────
const Stars = ({ count = 4 }: { count?: number }) => (
  <div className="flex gap-0.5">
    {[1,2,3,4,5].map(i => (
      <Star key={i} size={11} fill={i <= count ? ORG : 'none'} className={i <= count ? 'text-[#F37021]' : 'text-gray-200'} />
    ))}
  </div>
);

// ── Mobile Product Card ───────────────────────────────────────
const MobileCard = ({
  product, discount, isOutOfStock = false, badgeLabel, badgeColor,
  onCart, onBuy, onSelect,
}: {
  product: Product; discount?: number; isOutOfStock?: boolean;
  badgeLabel?: string; badgeColor?: string;
  onCart: () => void; onBuy: () => void; onSelect: () => void; key?: any;
}) => {
  const discPrice = discount ? Math.round(product.price * (1 - discount / 100)) : product.price;
  return (
    <div className="bg-white rounded-2xl border border-orange-100 shadow-sm overflow-hidden flex flex-col">
      <div className="relative aspect-square bg-orange-50/40 p-3 flex items-center justify-center" onClick={onSelect}>
        {badgeLabel && (
          <span className={`absolute top-2 left-2 z-10 text-white text-[9px] font-black px-2 py-0.5 rounded-full shadow-sm ${badgeColor || 'bg-[#F37021]'}`}>
            {badgeLabel}
          </span>
        )}
        {isOutOfStock && (
          <div className="absolute inset-0 bg-black/40 flex items-center justify-center z-20 rounded-2xl">
            <span className="text-white text-[10px] font-black bg-red-500 px-2 py-1 rounded-full">Stock Out</span>
          </div>
        )}
        <img src={product.image} alt={product.name} className="w-full h-full object-contain" loading="lazy" />
      </div>
      <div className="px-2.5 pb-2.5 pt-1.5 flex flex-col flex-grow">
        <Stars />
        <p className="text-[11px] font-semibold text-slate-800 line-clamp-2 leading-snug mt-1 mb-1.5 cursor-pointer" onClick={onSelect}>
          {product.name}
        </p>
        <div className="flex items-baseline gap-1.5 mb-2.5">
          <span className="text-[15px] font-black leading-none" style={{ color: ORG }}>৳{discPrice}</span>
          {discount && <span className="text-[10px] text-slate-400 line-through">৳{product.price}</span>}
          {discount && <span className="text-[9px] font-bold text-green-600 bg-green-50 px-1 rounded">-{discount}%</span>}
        </div>
        <div className="flex gap-1.5 mt-auto">
          <button
            disabled={isOutOfStock}
            onClick={(e) => { e.stopPropagation(); onCart(); }}
            className="flex-1 flex items-center justify-center gap-1 border-2 text-[10px] font-black py-2.5 rounded-xl active:scale-95 transition-all duration-100 disabled:opacity-40"
            style={{ borderColor: ORG, color: ORG }}
          >
            <ShoppingCart size={10} strokeWidth={2.5} /> Cart
          </button>
          <button
            disabled={isOutOfStock}
            onClick={(e) => { e.stopPropagation(); onBuy(); }}
            className="flex-1 flex items-center justify-center gap-1 text-white text-[10px] font-black py-2.5 rounded-xl active:scale-95 transition-all duration-100 shadow-sm disabled:opacity-40"
            style={{ background: `linear-gradient(135deg, ${ORG}, ${ORG_DARK})` }}
          >
            <Zap size={10} strokeWidth={2.5} /> কিনুন
          </button>
        </div>
      </div>
    </div>
  );
};

// ── Mobile Top-Seller Card (full-width horizontal) ────────────
const MobileTopSellerCard = ({
  product, onCart, onBuy, onSelect
}: { product: Product; onCart: () => void; onBuy: () => void; onSelect: () => void; key?: any }) => (
  <div className="bg-white rounded-2xl border border-orange-100 shadow-sm overflow-hidden flex gap-3 p-3">
    <div className="relative w-24 h-24 bg-orange-50/50 rounded-xl flex-shrink-0 flex items-center justify-center p-2" onClick={onSelect}>
      <span className="absolute top-1 right-1 bg-red-500 text-white text-[8px] font-black px-1.5 py-0.5 rounded-full">Best</span>
      <img src={product.image} alt={product.name} className="w-full h-full object-contain" loading="lazy" />
    </div>
    <div className="flex flex-col flex-grow min-w-0 py-0.5">
      <Stars />
      <p className="text-[12px] font-bold text-slate-800 line-clamp-2 leading-snug mt-1 mb-1 cursor-pointer" onClick={onSelect}>
        {product.name}
      </p>
      <p className="text-[10px] text-slate-400 mb-1.5 line-clamp-1">Pure & natural organic product</p>
      <div className="flex items-baseline gap-1.5 mb-2">
        <span className="text-[14px] font-black" style={{ color: ORG }}>৳{product.price}</span>
        <span className="text-[10px] text-slate-400 line-through">৳{Math.round(product.price * 1.25)}</span>
        <span className="text-[9px] font-bold text-green-600 bg-green-50 px-1 rounded">-25%</span>
      </div>
      <div className="flex gap-1.5">
        <button
          onClick={(e) => { e.stopPropagation(); onCart(); }}
          className="flex-1 text-[10px] font-black py-1.5 rounded-lg border-2 active:scale-95 transition-all duration-100"
          style={{ borderColor: ORG, color: ORG }}
        >Cart</button>
        <button
          onClick={(e) => { e.stopPropagation(); onBuy(); }}
          className="flex-1 text-[10px] font-black py-1.5 rounded-lg text-white active:scale-95 transition-all duration-100"
          style={{ background: ORG }}
        >কিনুন</button>
      </div>
    </div>
  </div>
);

// ════════════════════════════════════════════════
//  MAIN COMPONENT
// ════════════════════════════════════════════════
const HomePage04: React.FC<HomePageProps> = ({
  settings, featuredProducts, isProductsLoaded, navigateTo,
  setDirectCheckoutProduct, onAddToCart, onSelectProduct
}) => {
  const [currentSlide, setCurrentSlide] = useState(0);
  const [categoryScrollIndex, setCategoryScrollIndex] = useState(0);

  let homeConfig: import('../types').HomePageConfig | null = null;
  if (settings.homePageJson) {
    try { homeConfig = JSON.parse(settings.homePageJson); } catch {}
  }

  const heroSliders = homeConfig?.theme04?.heroSliders?.length
    ? homeConfig.theme04.heroSliders
    : [{ image: 'https://images.unsplash.com/photo-1474979266404-7eaacbcd87c5?w=1200&h=600&fit=crop' }];

  const rightBanner = homeConfig?.theme04?.rightBanner || {
    image: 'https://joreenbrands.com/cdn/shop/articles/Joreen_Blog_1-1965866.png?v=1759837911'
  };

  const displayProducts = featuredProducts?.length > 0 ? featuredProducts : DEMO_PRODUCTS;

  const topSellingIds = homeConfig?.theme04?.topSellingProductIds || [];
  const topSellingProducts = topSellingIds.length > 0
    ? topSellingIds.map((id: string) => displayProducts.find(p => p.id === id)).filter(Boolean) as typeof displayProducts
    : displayProducts.slice(0, 5);

  let displayCategories = [...FEATURED_CATEGORIES];
  if (settings.categoriesJson) {
    try {
      const parsed = JSON.parse(settings.categoriesJson);
      if (Array.isArray(parsed) && parsed.length > 0) {
        displayCategories = [
          ...displayCategories,
          ...parsed.map((c: any) => ({ name: c.name, image: c.image || FEATURED_CATEGORIES[0].image }))
        ];
      }
    } catch {}
  }

  const schemeIdx = homeConfig?.theme04?.colorScheme;
  const cs = schemeIdx !== undefined ? getColorScheme(schemeIdx) : null;

  const honeyProducts = (() => {
    const ids = homeConfig?.theme04?.honeyCollectionIds || [];
    return ids.length > 0
      ? ids.map((id: string) => displayProducts.find(p => p.id === id)).filter(Boolean) as typeof displayProducts
      : displayProducts.slice(4, 10);
  })();

  const cookingProducts = (() => {
    const ids = homeConfig?.theme04?.cookingEssentialsIds || [];
    return ids.length > 0
      ? ids.map((id: string) => displayProducts.find(p => p.id === id)).filter(Boolean) as typeof displayProducts
      : displayProducts.slice(9, 15);
  })();

  const datesProducts = (() => {
    const ids = homeConfig?.theme04?.premiumDatesIds || [];
    return ids.length > 0
      ? ids.map((id: string) => displayProducts.find(p => p.id === id)).filter(Boolean) as typeof displayProducts
      : displayProducts.slice(14, 20);
  })();

  const testimonials = homeConfig?.theme04?.testimonials?.length ? homeConfig.theme04.testimonials : TESTIMONIALS;
  const brands = homeConfig?.theme04?.trustedBrands?.length ? homeConfig.theme04.trustedBrands : BRANDS;

  useEffect(() => {
    if (heroSliders.length <= 1) return;
    const t = setInterval(() => setCurrentSlide(p => (p + 1) % heroSliders.length), 3500);
    return () => clearInterval(t);
  }, [heroSliders.length]);

  const addCart = (p: Product) => { if (onAddToCart) onAddToCart(p); else setDirectCheckoutProduct({ product: p }); };
  const buyNow  = (p: Product) => setDirectCheckoutProduct({ product: p });

  // Horizontal product scroll section for mobile
  const MobileProductRow = ({ title, products, discountPct = 15 }: { title: string; products: Product[]; discountPct?: number }) => (
    <div className="mb-2">
      <div className="flex items-center justify-between px-3 mb-2">
        <h3 className="text-[14px] font-black text-slate-800">{title}</h3>
        <button onClick={() => navigateTo('shop')} className="text-[11px] font-bold flex items-center gap-0.5" style={{ color: ORG }}>
          সব দেখুন <CRight size={11} />
        </button>
      </div>
      <div className="flex gap-2.5 overflow-x-auto no-scrollbar px-3 pb-1">
        {products.map(p => (
          <div key={p.id} className="flex-shrink-0 w-[155px] bg-white rounded-2xl border border-orange-100 shadow-sm overflow-hidden flex flex-col">
            <div className="relative aspect-square bg-orange-50/40 p-2.5 flex items-center justify-center" onClick={() => onSelectProduct(p)}>
              <span className="absolute top-1.5 left-1.5 text-white text-[8px] font-black px-1.5 py-0.5 rounded-full" style={{ background: ORG }}>
                -{discountPct}%
              </span>
              <img src={p.image} alt={p.name} className="w-full h-full object-contain" loading="lazy" />
            </div>
            <div className="px-2 pb-2 pt-1 flex flex-col flex-grow">
              <p className="text-[10px] font-semibold text-slate-700 line-clamp-2 leading-snug mb-1.5" onClick={() => onSelectProduct(p)}>{p.name}</p>
              <div className="flex items-baseline gap-1 mb-2">
                <span className="text-[13px] font-black" style={{ color: ORG }}>৳{Math.round(p.price * (1 - discountPct / 100))}</span>
                <span className="text-[9px] text-slate-400 line-through">৳{p.price}</span>
              </div>
              <button
                onClick={(e) => { e.stopPropagation(); addCart(p); }}
                className="w-full text-white text-[10px] font-black py-2 rounded-xl active:scale-95 transition-all duration-100 flex items-center justify-center gap-1"
                style={{ background: ORG }}
              >
                <ShoppingCart size={9} /> Cart
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );

  return (
    <div className="bg-[#FFF8F2] font-sans" style={{ fontFamily: "'Poppins', 'Hind Siliguri', sans-serif" }}>
      {cs && (
        <style dangerouslySetInnerHTML={{ __html: `
          .hp04-primary { color: ${cs.primary} !important; }
          .hp04-bg { background-color: ${cs.primary} !important; }
        ` }} />
      )}

      {/* Coupon Bar */}
      {(settings.marketingCoupons || []).filter(c => c.showOnHome).length > 0 && (
        <div className="overflow-x-auto no-scrollbar" style={{ background: ORG }}>
          <div className="flex snap-x">
            {(settings.marketingCoupons || []).filter(c => c.showOnHome).map(coupon => (
              <div key={coupon.id} className="min-w-full snap-center flex items-center justify-center gap-2 px-4 py-2 text-white text-xs font-bold shrink-0">
                <Gift size={13} className="animate-pulse text-yellow-200 shrink-0" />
                <span className="truncate">{coupon.discountDesc} · Code:</span>
                <span className="bg-white/20 border border-white/30 px-2 py-0.5 rounded font-mono tracking-wider shrink-0">{coupon.code}</span>
                <button
                  onClick={() => navigator.clipboard.writeText(coupon.code)}
                  className="shrink-0 bg-white/90 text-[#F37021] text-[10px] font-black px-2 py-0.5 rounded-full active:bg-white"
                >Copy</button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ══════════════════════════════════════════
          MOBILE  (md:hidden)
      ══════════════════════════════════════════ */}
      <div className="md:hidden">

        {/* Hero Slider */}
        <div className="relative overflow-hidden bg-slate-900" style={{ aspectRatio: '16/9' }}>
          {heroSliders.map((s, i) => (
            <div key={i} className={`absolute inset-0 transition-opacity duration-700 ${i === currentSlide ? 'opacity-100' : 'opacity-0'}`}>
              <img src={s.image} className="w-full h-full object-cover" alt={`Slide ${i}`} />
              <div className="absolute inset-0 bg-gradient-to-t from-black/30 to-transparent" />
            </div>
          ))}
          {heroSliders.length > 1 && (
            <div className="absolute bottom-3 left-1/2 -translate-x-1/2 flex gap-1.5 z-10">
              {heroSliders.map((_, i) => (
                <button key={i} onClick={() => setCurrentSlide(i)}
                  className="h-1.5 rounded-full transition-all duration-300"
                  style={{ width: i === currentSlide ? 20 : 6, background: i === currentSlide ? ORG : 'rgba(255,255,255,0.5)' }} />
              ))}
            </div>
          )}
        </div>

        {/* Trust Badges */}
        <div className="bg-white border-b border-orange-100 px-3 py-3">
          <div className="flex justify-around">
            {[
              { icon: Truck,       label: 'Fast Delivery' },
              { icon: ShieldCheck, label: '100% Organic' },
              { icon: Star,        label: 'Top Rated' },
              { icon: Clock,       label: 'Fresh Daily' },
            ].map(({ icon: Icon, label }) => (
              <div key={label} className="flex flex-col items-center gap-1">
                <div className="w-9 h-9 rounded-xl flex items-center justify-center" style={{ background: ORG_LIGHT }}>
                  <Icon size={16} style={{ color: ORG }} />
                </div>
                <span className="text-[9px] font-bold text-slate-600 text-center leading-tight">{label}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Category Scroll */}
        <div className="bg-white mt-1.5 border-b border-orange-100">
          <div className="flex items-center justify-between px-4 pt-3.5 pb-2">
            <h2 className="text-[14px] font-black text-slate-900">Categories</h2>
            <button onClick={() => navigateTo('shop')} className="flex items-center gap-0.5 text-[11px] font-bold" style={{ color: ORG }}>
              সব <CRight size={11} />
            </button>
          </div>
          <div className="flex gap-3.5 overflow-x-auto no-scrollbar px-4 pb-4">
            {displayCategories.map((cat, i) => (
              <button key={i} onClick={() => navigateTo('shop')} className="flex flex-col items-center gap-1.5 flex-shrink-0 active:scale-95 transition-transform duration-100">
                <div className="w-[54px] h-[54px] rounded-2xl overflow-hidden border-2 bg-orange-50" style={{ borderColor: 'rgba(243,112,33,0.2)' }}>
                  <img src={cat.image} alt={cat.name} className="w-full h-full object-cover" loading="lazy" />
                </div>
                <span className="text-[10px] font-semibold text-slate-600 text-center max-w-[56px] leading-tight line-clamp-1">{cat.name}</span>
              </button>
            ))}
          </div>
        </div>

        {/* Top Selling Products — vertical list */}
        <div className="bg-white px-3 py-4 mt-1.5 border-b border-orange-100">
          <div className="flex items-center justify-between mb-3">
            <div>
              <h2 className="text-[15px] font-black text-slate-900">Top Sellers</h2>
              <div className="w-7 h-0.5 mt-0.5 rounded-full" style={{ background: ORG }} />
            </div>
            <button onClick={() => navigateTo('shop')} className="text-[11px] font-bold border rounded-full px-2.5 py-1.5 text-slate-600 active:bg-orange-50 border-orange-200">
              View All
            </button>
          </div>
          <div className="flex flex-col gap-2.5">
            {topSellingProducts.slice(0, 4).map(p => (
              <MobileTopSellerCard
                key={p.id}
                product={p}
                onCart={() => addCart(p)}
                onBuy={() => buyNow(p)}
                onSelect={() => onSelectProduct(p)}
              />
            ))}
          </div>
        </div>

        {/* Promo Banner (full-bleed) */}
        <div
          className="relative mx-3 my-3 rounded-2xl overflow-hidden h-40 cursor-pointer active:opacity-90 transition-opacity"
          onClick={() => navigateTo('shop')}
        >
          <img
            src="https://images.unsplash.com/photo-1607532941433-304659e8198a?w=800&h=400&fit=crop"
            alt="Promo"
            className="w-full h-full object-cover"
          />
          <div className="absolute inset-0 bg-gradient-to-r from-black/75 to-transparent flex flex-col justify-center pl-5 pr-32">
            <span className="text-[10px] font-black uppercase tracking-widest mb-1" style={{ color: ORG }}>Premium Quality</span>
            <h3 className="text-white text-[15px] font-black leading-snug mb-2.5">Premium Medjool Dates</h3>
            <span className="inline-flex items-center gap-1 text-[10px] font-black px-3 py-1.5 rounded-full w-fit text-white" style={{ background: ORG }}>
              Shop Now <ArrowRight size={9} />
            </span>
          </div>
        </div>

        {/* Right Banner */}
        <div
          className="relative mx-3 mb-3 rounded-2xl overflow-hidden h-40 cursor-pointer active:opacity-90 transition-opacity"
          onClick={() => navigateTo('shop')}
        >
          <img src={rightBanner.image} alt="Banner" className="w-full h-full object-cover" />
        </div>

        {/* Honey Collection */}
        <div className="bg-white pt-4 pb-2 mt-1.5 border-b border-orange-100">
          <MobileProductRow title="🍯 Pure Honey" products={honeyProducts} discountPct={15} />
        </div>

        {/* Cooking Essentials */}
        <div className="bg-white pt-4 pb-2 mt-1.5 border-b border-orange-100">
          <MobileProductRow title="🥄 Cooking Essentials" products={cookingProducts} discountPct={10} />
        </div>

        {/* Premium Dates */}
        <div className="bg-white pt-4 pb-2 mt-1.5 border-b border-orange-100">
          <MobileProductRow title="🌴 Premium Dates" products={datesProducts} discountPct={20} />
        </div>

        {/* All Products — 2 col grid */}
        <div className="bg-white px-3 py-4 mt-1.5 border-b border-orange-100">
          <div className="flex items-center justify-between mb-3">
            <div>
              <h2 className="text-[15px] font-black text-slate-900">সব পণ্য</h2>
              <div className="w-7 h-0.5 mt-0.5 rounded-full" style={{ background: ORG }} />
            </div>
            <button onClick={() => navigateTo('shop')} className="text-[11px] font-bold border rounded-full px-2.5 py-1.5 text-slate-600 active:bg-orange-50 border-orange-200">
              View All
            </button>
          </div>
          <div className="grid grid-cols-2 gap-2.5">
            {displayProducts.slice(0, 8).map((p, idx) => (
              <MobileCard
                key={p.id}
                product={p}
                discount={15 + idx * 2}
                badgeLabel={`-${15 + idx * 2}%`}
                onCart={() => addCart(p)}
                onBuy={() => buyNow(p)}
                onSelect={() => onSelectProduct(p)}
              />
            ))}
          </div>
          <button
            onClick={() => navigateTo('shop')}
            className="w-full mt-4 text-white font-black text-[12px] py-3 rounded-xl active:scale-95 transition-all duration-100 flex items-center justify-center gap-1.5"
            style={{ background: `linear-gradient(135deg, ${ORG}, ${ORG_DARK})` }}
          >
            আরও পণ্য দেখুন <ArrowRight size={14} />
          </button>
        </div>

        {/* Testimonials — horizontal scroll */}
        <div className="bg-white px-3 py-4 mt-1.5 border-b border-orange-100">
          <h2 className="text-[15px] font-black text-slate-900 mb-1">Customer Reviews</h2>
          <div className="w-7 h-0.5 mb-3 rounded-full" style={{ background: ORG }} />
          <div className="flex gap-3 overflow-x-auto no-scrollbar pb-1">
            {testimonials.map((t: any, i: number) => (
              <div key={i} className="flex-shrink-0 w-64 bg-orange-50/60 rounded-2xl p-4 border border-orange-100">
                <div className="flex items-center gap-3 mb-3">
                  {t.image ? (
                    <img src={t.image} alt={t.name} className="w-10 h-10 rounded-full object-cover" />
                  ) : (
                    <div className="w-10 h-10 rounded-full flex items-center justify-center text-white font-black" style={{ background: ORG }}>
                      {t.name?.charAt(0)}
                    </div>
                  )}
                  <div>
                    <p className="text-[12px] font-bold text-slate-800">{t.name}</p>
                    <p className="text-[10px] text-slate-400">{t.profession}</p>
                  </div>
                </div>
                <Stars count={t.rating || 5} />
                <p className="text-[11px] text-slate-600 leading-relaxed mt-2 line-clamp-4">{t.text}</p>
              </div>
            ))}
          </div>
        </div>

        {/* Brand Strip */}
        <div className="bg-white px-3 py-4 mt-1.5">
          <h2 className="text-[14px] font-black text-slate-900 text-center mb-3">Our Trusted Brands</h2>
          <div className="flex gap-3 overflow-x-auto no-scrollbar justify-start">
            {brands.map((b: any, i: number) => (
              <div key={i} className="flex-shrink-0 bg-orange-50 rounded-xl px-4 py-3 flex items-center justify-center min-w-[90px]">
                {b.logo ? (
                  <img src={b.logo} alt={b.name} className="h-8 w-auto object-contain" />
                ) : (
                  <span className="text-[11px] font-black text-slate-600 text-center">{b.name}</span>
                )}
              </div>
            ))}
          </div>
        </div>

        {/* Policy Links */}
        <div className="bg-gray-800 px-4 py-5 mt-1.5">
          <div className="flex flex-wrap justify-center gap-3">
            {[
              { label: 'Return Policy',       route: 'return-policy' },
              { label: 'Exchange Policy',     route: 'exchange-policy' },
              { label: 'Cancellation Policy', route: 'cancellation-policy' },
              { label: 'Refund Policy',       route: 'refund-only-policy' },
            ].map(p => (
              <button
                key={p.route}
                onClick={() => navigateTo(p.route)}
                className="text-gray-300 text-[11px] font-semibold active:text-orange-400 transition-colors border-b border-gray-600 pb-0.5"
              >
                {p.label}
              </button>
            ))}
          </div>
        </div>

        <div className="h-4" />
      </div>

      {/* ══════════════════════════════════════════
          DESKTOP  (hidden md:block)
      ══════════════════════════════════════════ */}
      <div className="hidden md:block">

        {/* Hero + Right Banner */}
        <div className="max-w-[1280px] mx-auto px-4 mt-6">
          <div className="grid grid-cols-4 gap-6">
            <div className="col-span-3 relative rounded-3xl overflow-hidden h-[400px] group cursor-pointer" onClick={() => navigateTo('shop')}>
              {heroSliders.map((s, i) => (
                <div key={i} className={`absolute inset-0 transition-opacity duration-1000 ${i === currentSlide ? 'opacity-100 z-10' : 'opacity-0 z-0'}`}>
                  <img src={s.image} alt="Slide" className="w-full h-full object-cover group-hover:scale-105 transition duration-700" />
                </div>
              ))}
              {heroSliders.length > 1 && (
                <div className="absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2 z-20">
                  {heroSliders.map((_, i) => (
                    <button key={i} onClick={(e) => { e.stopPropagation(); setCurrentSlide(i); }}
                      className="w-2 h-2 rounded-full transition-colors"
                      style={{ background: i === currentSlide ? ORG : 'rgba(255,255,255,0.7)' }} />
                  ))}
                </div>
              )}
            </div>
            <div className="col-span-1 relative rounded-3xl overflow-hidden h-[400px] group cursor-pointer" onClick={() => navigateTo('shop')}>
              <img src={rightBanner.image} alt="Banner" className="absolute inset-0 w-full h-full object-cover group-hover:scale-105 transition-transform duration-700" />
            </div>
          </div>
        </div>

        {/* Categories */}
        <div className="bg-white py-10 mt-6">
          <div className="max-w-[1280px] mx-auto px-4">
            <div className="flex justify-between items-center mb-6">
              <h2 className="text-2xl font-bold text-gray-800">Shop by Category</h2>
              <div className="flex gap-2">
                <button onClick={() => setCategoryScrollIndex(Math.max(0, categoryScrollIndex - 1))}
                  className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center hover:bg-[#F37021] hover:text-white hover:border-[#F37021] transition">
                  <ChevronLeft size={16} />
                </button>
                <button onClick={() => setCategoryScrollIndex(Math.min(displayCategories.length - 4, categoryScrollIndex + 1))}
                  className="w-8 h-8 rounded-full border border-gray-300 flex items-center justify-center hover:bg-[#F37021] hover:text-white hover:border-[#F37021] transition">
                  <ChevronRight size={16} />
                </button>
              </div>
            </div>
            <div className="overflow-hidden">
              <div className="flex gap-6 transition-transform duration-300" style={{ transform: `translateX(-${categoryScrollIndex * 110}px)` }}>
                {displayCategories.map((cat, i) => (
                  <div key={i} className="flex flex-col items-center flex-shrink-0 cursor-pointer group w-[100px]" onClick={() => navigateTo('shop')}>
                    <div className="w-24 h-24 rounded-2xl bg-orange-50 flex items-center justify-center group-hover:shadow-md transition border-2 border-transparent group-hover:border-[#F37021] p-3">
                      <img src={cat.image} alt={cat.name} className="w-full h-full object-cover rounded-xl" />
                    </div>
                    <span className="text-sm font-medium text-gray-700 mt-3 text-center group-hover:text-[#F37021] transition">{cat.name}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* Top Selling */}
        <div className="bg-orange-50/40 py-12">
          <div className="max-w-[1280px] mx-auto px-4">
            <div className="flex justify-between items-center mb-6">
              <h2 className="text-2xl font-bold text-gray-800">Top Selling Products</h2>
              <button className="text-sm font-semibold hover:underline" style={{ color: ORG }} onClick={() => navigateTo('shop')}>View All →</button>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {topSellingProducts.slice(0, 4).map(product => (
                <div key={product.id} className="bg-white rounded-xl overflow-hidden shadow-sm hover:shadow-lg transition-all duration-300 border border-gray-100 flex flex-col md:flex-row">
                  <div className="relative w-full md:w-1/2 aspect-square bg-gray-50 flex items-center justify-center p-6 cursor-pointer" onClick={() => onSelectProduct(product)}>
                    <div className="absolute top-3 right-3 z-10 bg-red-500 text-white text-[10px] font-bold px-2 py-1 rounded-full">Best Selling</div>
                    <img src={product.image} alt={product.name} className="w-full h-full object-contain" />
                  </div>
                  <div className="p-5 flex-1 flex flex-col justify-center">
                    <div className="mb-2"><Stars count={5} /></div>
                    <h3 className="font-bold text-gray-800 text-lg mb-2 hover:text-[#F37021] cursor-pointer" onClick={() => onSelectProduct(product)}>{product.name}</h3>
                    <p className="text-gray-500 text-sm mb-3 line-clamp-2">Pure and natural organic product sourced directly from farmers.</p>
                    <div className="flex items-baseline gap-3 mb-4">
                      <span className="font-bold text-2xl" style={{ color: ORG }}>৳{product.price}</span>
                      <span className="text-gray-400 text-sm line-through">৳{Math.round(product.price * 1.25)}</span>
                      <span className="bg-green-100 text-green-700 text-xs font-bold px-2 py-1 rounded-full">Save 25%</span>
                    </div>
                    <div className="flex gap-3">
                      <button onClick={(e) => { e.stopPropagation(); addCart(product); }}
                        className="border-2 px-5 py-2 rounded-lg font-semibold text-sm hover:text-white transition"
                        style={{ borderColor: ORG, color: ORG, ['--hover-bg' as any]: ORG }}
                        onMouseEnter={e => { (e.target as HTMLButtonElement).style.background = ORG; (e.target as HTMLButtonElement).style.color = 'white'; }}
                        onMouseLeave={e => { (e.target as HTMLButtonElement).style.background = 'transparent'; (e.target as HTMLButtonElement).style.color = ORG; }}
                      >Add to Cart</button>
                      <button onClick={() => buyNow(product)}
                        className="text-white px-6 py-2 rounded-lg font-semibold text-sm transition"
                        style={{ background: ORG }}
                        onMouseEnter={e => (e.target as HTMLButtonElement).style.background = ORG_DARK}
                        onMouseLeave={e => (e.target as HTMLButtonElement).style.background = ORG}
                      >Buy Now</button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Brands */}
        <div className="bg-white py-12 border-b border-gray-100">
          <div className="max-w-[1280px] mx-auto px-4">
            <h2 className="text-2xl font-bold text-gray-800 text-center mb-8">Our Trusted Brands</h2>
            <div className="flex flex-wrap justify-center items-center gap-8">
              {brands.map((b: any, i: number) => (
                <div key={i} className="cursor-pointer hover:scale-105 transition flex flex-col items-center gap-2 p-4 bg-gray-50 rounded-xl">
                  {b.logo ? (
                    <img src={b.logo} alt={b.name} className="h-12 w-auto object-contain" />
                  ) : (
                    <div className="text-base font-bold text-gray-600">{b.name}</div>
                  )}
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Product Sliders */}
        {[
          { title: 'Pure Honey Collection', products: honeyProducts, discount: 'Save 15%' },
          { title: 'Cooking Essentials',    products: cookingProducts, discount: 'Save 10%' },
          { title: 'Premium Dates',         products: datesProducts, discount: 'Save 20%' },
        ].map(({ title, products, discount }) => (
          <div key={title} className="bg-white py-12 border-b border-gray-100">
            <div className="max-w-[1280px] mx-auto px-4">
              <div className="flex justify-between items-center mb-6">
                <h2 className="text-2xl font-bold text-gray-800">{title}</h2>
                <button className="text-sm font-semibold hover:underline" style={{ color: ORG }} onClick={() => navigateTo('shop')}>View All →</button>
              </div>
              <div className="flex gap-5 overflow-x-auto pb-4" style={{ scrollbarWidth: 'thin' }}>
                {products.map(p => (
                  <div key={p.id} className="group bg-white rounded-xl overflow-hidden shadow-sm hover:shadow-lg transition-all duration-300 border border-gray-100 flex-shrink-0 w-[200px]">
                    <div className="relative aspect-square bg-gray-50 flex items-center justify-center p-4 cursor-pointer" onClick={() => onSelectProduct(p)}>
                      <div className="absolute top-2 left-2 z-10 text-white text-[10px] font-bold px-2 py-1 rounded-md" style={{ background: ORG }}>{discount}</div>
                      <img src={p.image} alt={p.name} className="w-full h-full object-contain group-hover:scale-105 transition-transform duration-500" />
                    </div>
                    <div className="p-3">
                      <h3 className="font-semibold text-gray-800 text-sm mb-1 line-clamp-2 hover:text-[#F37021] cursor-pointer" onClick={() => onSelectProduct(p)}>{p.name}</h3>
                      <div className="flex items-baseline gap-2 mt-1">
                        <span className="font-bold" style={{ color: ORG }}>৳{p.price}</span>
                        <span className="text-gray-400 text-xs line-through">৳{Math.round(p.price * 1.2)}</span>
                      </div>
                      <button
                        onClick={(e) => { e.stopPropagation(); addCart(p); }}
                        className="w-full mt-2 border-2 font-semibold py-1.5 rounded-lg text-xs transition-all duration-300"
                        style={{ borderColor: ORG, color: ORG }}
                        onMouseEnter={e => { (e.target as HTMLButtonElement).style.background = ORG; (e.target as HTMLButtonElement).style.color = 'white'; }}
                        onMouseLeave={e => { (e.target as HTMLButtonElement).style.background = 'transparent'; (e.target as HTMLButtonElement).style.color = ORG; }}
                      >Add to Cart</button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        ))}

        {/* Full Promo Banner */}
        <div className="relative w-full h-[300px] overflow-hidden my-8">
          <img src="https://images.unsplash.com/photo-1607532941433-304659e8198a?w=1920&h=500&fit=crop" alt="Dates Promo" className="w-full h-full object-cover" />
          <div className="absolute inset-0 bg-gradient-to-r from-black/70 to-transparent flex items-center">
            <div className="max-w-[1280px] mx-auto px-4 w-full">
              <div className="max-w-lg text-white">
                <span className="text-sm font-bold tracking-wider" style={{ color: ORG }}>Premium Quality</span>
                <h2 className="text-4xl md:text-5xl font-bold mt-2 mb-4">Premium Medjool Dates</h2>
                <p className="text-white/80 mb-6">Naturally sweet, rich in fiber and antioxidants.</p>
                <button className="text-white px-8 py-3 rounded-full font-semibold hover:opacity-90 transition" style={{ background: ORG }} onClick={() => navigateTo('shop')}>
                  Shop Now →
                </button>
              </div>
            </div>
          </div>
        </div>

        {/* All Products */}
        <div className="bg-white py-16">
          <div className="max-w-[1280px] mx-auto px-4">
            <div className="flex justify-between items-center mb-8">
              <div>
                <h2 className="text-2xl font-bold text-gray-800">All Products</h2>
                <p className="text-gray-500 text-sm mt-1">Browse our complete collection</p>
              </div>
              <button className="text-sm font-semibold hover:underline" style={{ color: ORG }} onClick={() => navigateTo('shop')}>View All →</button>
            </div>
            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
              {displayProducts.slice(0, 10).map(p => (
                <div key={p.id} className="group bg-white border border-gray-100 rounded-2xl p-4 hover:shadow-lg transition-all duration-300 cursor-pointer flex flex-col" onClick={() => onSelectProduct(p)}>
                  <div className="aspect-square mb-3 bg-gray-50 rounded-xl overflow-hidden flex items-center justify-center">
                    <img src={p.image} alt={p.name} className="w-full h-full object-cover group-hover:scale-105 transition duration-300" />
                  </div>
                  <h3 className="text-sm font-bold text-gray-800 line-clamp-2 mb-1 leading-tight">{p.name}</h3>
                  <div className="flex items-baseline gap-2 mt-auto pt-2">
                    <span className="font-black text-base" style={{ color: ORG }}>৳{p.price}</span>
                    <span className="text-gray-400 text-xs line-through">৳{Math.round(p.price * 1.2)}</span>
                  </div>
                  <button
                    onClick={(e) => { e.stopPropagation(); addCart(p); }}
                    className="mt-2 w-full font-bold py-1.5 rounded-lg text-xs transition-colors"
                    style={{ background: `${ORG}1A`, color: ORG }}
                    onMouseEnter={e => { (e.target as HTMLButtonElement).style.background = ORG; (e.target as HTMLButtonElement).style.color = 'white'; }}
                    onMouseLeave={e => { (e.target as HTMLButtonElement).style.background = `${ORG}1A`; (e.target as HTMLButtonElement).style.color = ORG; }}
                  >Add to Cart</button>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Testimonials */}
        <div className="bg-orange-50/40 py-16">
          <div className="max-w-[1280px] mx-auto px-4">
            <div className="text-center mb-12">
              <h2 className="text-3xl font-bold text-gray-800 mb-2">What Our Customers Say</h2>
              <p className="text-gray-500">Trusted by thousands of happy customers</p>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              {testimonials.map((t: any, i: number) => (
                <div key={i} className="bg-white rounded-2xl p-6 shadow-sm hover:shadow-md transition">
                  <div className="flex items-center gap-4 mb-4">
                    {t.image ? (
                      <img src={t.image} alt={t.name} className="w-14 h-14 rounded-full object-cover" />
                    ) : (
                      <div className="w-14 h-14 rounded-full flex items-center justify-center text-white font-black text-xl" style={{ background: ORG }}>
                        {t.name?.charAt(0)}
                      </div>
                    )}
                    <div>
                      <h4 className="font-bold text-gray-800">{t.name}</h4>
                      <p className="text-gray-400 text-sm">{t.profession}</p>
                    </div>
                  </div>
                  <Stars count={t.rating || 5} />
                  <p className="text-gray-600 text-sm leading-relaxed mt-3">{t.text}</p>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Policy Strip */}
        <div className="bg-gray-800 py-8">
          <div className="max-w-[1280px] mx-auto px-4">
            <div className="flex flex-wrap justify-center gap-6 md:gap-10">
              {[
                { label: 'Return Policy',       route: 'return-policy' },
                { label: 'Exchange Policy',     route: 'exchange-policy' },
                { label: 'Cancellation Policy', route: 'cancellation-policy' },
                { label: 'Refund Policy',       route: 'refund-only-policy' },
              ].map(p => (
                <button key={p.route} onClick={() => navigateTo(p.route)}
                  className="text-gray-300 hover:text-[#F37021] text-sm font-semibold transition-colors flex items-center gap-2 group">
                  <span className="w-1.5 h-1.5 rounded-full bg-[#F37021]/50 group-hover:bg-[#F37021] transition-colors" />
                  {p.label}
                </button>
              ))}
            </div>
          </div>
        </div>

      <AppDownloadBanner settings={settings} bgColor="#1a1a1a" />

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

export default HomePage04;