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, ArrowRight, Star, Gift, Zap, ChevronRight, Tag, TrendingUp, 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 CATEGORIES = [
  { name: 'Fruits',     icon: 'https://images.unsplash.com/photo-1610832958506-aa56368176cf?w=200&h=200&fit=crop' },
  { name: 'Baby',       icon: 'https://images.unsplash.com/photo-1519689680058-324335c77eba?w=200&h=200&fit=crop' },
  { name: 'Beverages',  icon: 'https://images.unsplash.com/photo-1556881286-fc6915169721?w=200&h=200&fit=crop' },
  { name: 'Meats',      icon: 'https://images.unsplash.com/photo-1607623814075-e51df1bdc82f?w=200&h=200&fit=crop' },
  { name: 'Snacks',     icon: 'https://images.unsplash.com/photo-1599599810769-bcde5a160d32?w=200&h=200&fit=crop' },
  { name: 'Bakery',     icon: 'https://images.unsplash.com/photo-1509440159596-0249088772ff?w=200&h=200&fit=crop' },
  { name: 'Dairy',      icon: 'https://images.unsplash.com/photo-1628088062854-d1870b4553da?w=200&h=200&fit=crop' },
  { name: 'Frozen',     icon: 'https://images.unsplash.com/photo-1581513689404-b90302fffa98?w=200&h=200&fit=crop' },
  { name: 'Beauty',     icon: 'https://images.unsplash.com/photo-1596462502278-27bfdc403348?w=200&h=200&fit=crop' },
];

const BLOG_POSTS = [
  { id: 1, title: 'How grocers are approaching delivery as the market evolves',       category: 'GROCERY', date: '5 May 2024', author: 'admin', image: 'https://images.unsplash.com/photo-1542838132-92c53300491e?w=500&h=300&fit=crop' },
  { id: 2, title: 'The Friday Checkout: Food insecurity keeps wallet well balance',   category: 'NEWS',    date: '5 May 2024', author: 'admin', image: 'https://images.unsplash.com/photo-1583258292688-d0213dc5a3a8?w=500&h=300&fit=crop' },
  { id: 3, title: 'Consumer want grocer to use AI to help them save money',           category: 'TECH',    date: '5 May 2024', author: 'admin', image: 'https://images.unsplash.com/photo-1579621970588-a35d0e7ab9b6?w=500&h=300&fit=crop' },
  { id: 4, title: 'Close up: How grocers are squeezing the restaurant experience',    category: 'FOOD',    date: '1 May 2024', author: 'admin', image: 'https://images.unsplash.com/photo-1556740758-90de374c12ad?w=500&h=300&fit=crop' },
];

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: '' },
];

// ─── Reusable Stars ─────────────────────────────
const Stars = () => (
  <div className="flex gap-0.5">
    {[1,2,3,4].map(i => <Star key={i} size={10} className="text-amber-400" fill="currentColor" />)}
    <Star size={10} className="text-slate-200" />
  </div>
);

// ─── Mobile Section Header ───────────────────────
const MobileSectionHeader = ({
  title, sub, icon: Icon, onViewAll, accent = '#1E1B4B'
}: { title: string; sub?: string; icon?: any; onViewAll?: () => void; accent?: string }) => (
  <div className="flex items-center justify-between mb-3">
    <div className="flex items-center gap-2">
      {Icon && (
        <div className="w-7 h-7 rounded-xl flex items-center justify-center" style={{ background: accent }}>
          <Icon size={13} className="text-white" />
        </div>
      )}
      <div>
        <h2 className="text-[15px] font-black text-slate-900 leading-none">{title}</h2>
        {sub && <p className="text-[10px] text-slate-400 mt-0.5">{sub}</p>}
      </div>
    </div>
    {onViewAll && (
      <button
        onClick={onViewAll}
        className="flex items-center gap-0.5 text-[11px] font-bold px-2.5 py-1.5 rounded-full border border-slate-200 text-slate-600 active:bg-slate-100 transition-colors"
      >
        সব দেখুন <ChevronRight size={11} />
      </button>
    )}
  </div>
);

// ─── Mobile Product Card ─────────────────────────
const MobileProductCard = ({
  product, discountPct = 15, badgeLabel, badgeColor = 'bg-red-500',
  onCart, onBuy, onSelect
}: {
  product: Product; discountPct?: number; badgeLabel?: string; badgeColor?: string;
  onCart: () => void; onBuy: () => void; onSelect: () => void; key?: any;
}) => {
  const discPrice = Math.round(product.price * (1 - discountPct / 100));
  return (
    <div className="bg-white rounded-2xl overflow-hidden border border-slate-100 shadow-sm flex flex-col">
      {/* Image */}
      <div className="relative aspect-square bg-slate-50 p-3 flex items-center justify-center" onClick={onSelect}>
        {badgeLabel && (
          <span className={`absolute top-2 left-2 z-10 ${badgeColor} text-white text-[9px] font-black px-2 py-0.5 rounded-full shadow-sm`}>
            {badgeLabel}
          </span>
        )}
        <img src={product.image} alt={product.name} className="w-full h-full object-contain" loading="lazy" />
      </div>
      {/* Info */}
      <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 text-red-600 leading-none">৳{discPrice}</span>
          <span className="text-[10px] text-slate-400 line-through">৳{product.price}</span>
          <span className="text-[9px] font-bold text-green-600 bg-green-50 px-1 rounded">-{discountPct}%</span>
        </div>
        {/* Dual action buttons */}
        <div className="flex gap-1.5 mt-auto">
          <button
            onClick={(e) => { e.stopPropagation(); onCart(); }}
            className="flex-1 flex items-center justify-center gap-1 bg-[#1E1B4B] text-white text-[10px] font-black py-2.5 rounded-xl active:scale-95 active:opacity-80 transition-all duration-100"
          >
            <ShoppingCart size={10} strokeWidth={2.5} />
            Cart
          </button>
          <button
            onClick={(e) => { e.stopPropagation(); onBuy(); }}
            className="flex-1 flex items-center justify-center gap-1 bg-gradient-to-r from-red-500 to-rose-600 text-white text-[10px] font-black py-2.5 rounded-xl active:scale-95 active:opacity-80 transition-all duration-100 shadow-sm shadow-red-200"
          >
            <Zap size={10} strokeWidth={2.5} />
            কিনুন
          </button>
        </div>
      </div>
    </div>
  );
};

// ─── Deal Card (wider, horizontal timer) ────────
const MobileDealCard = ({
  product, countdown, onCart, onSelect
}: { product: Product; countdown: string; onCart: () => void; onSelect: () => void; key?: any }) => {
  const discPrice = Math.round(product.price * 0.72);
  const discPct = 28;
  return (
    <div className="bg-white rounded-2xl border border-orange-100 shadow-sm overflow-hidden flex flex-col">
      <div className="relative aspect-square bg-gradient-to-br from-orange-50 to-amber-50 p-3 flex items-center justify-center" onClick={onSelect}>
        <span className="absolute top-2 left-2 bg-red-500 text-white text-[9px] font-black px-2 py-0.5 rounded-full shadow-sm z-10">
          -{discPct}%
        </span>
        <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">
        <p className="text-[11px] font-semibold text-slate-800 line-clamp-2 leading-snug mb-1.5 cursor-pointer" onClick={onSelect}>
          {product.name}
        </p>
        <div className="flex items-baseline gap-1 mb-2">
          <span className="text-[14px] font-black text-red-600">৳{discPrice}</span>
          <span className="text-[9px] text-slate-400 line-through">৳{product.price}</span>
        </div>
        {/* Timer */}
        <div className="flex items-center gap-1 mb-2.5 bg-red-50 rounded-lg px-2 py-1.5">
          <Clock size={9} className="text-red-500 shrink-0" />
          <span className="font-mono text-[10px] font-black text-red-600 tracking-wider">{countdown}</span>
        </div>
        <button
          onClick={(e) => { e.stopPropagation(); onCart(); }}
          className="w-full bg-slate-900 text-white text-[10px] font-black py-2.5 rounded-xl active:scale-95 active:bg-red-600 transition-all duration-100 flex items-center justify-center gap-1"
        >
          <Zap size={10} /> Grab Deal
        </button>
      </div>
    </div>
  );
};

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

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

  const banner1 = homeConfig?.theme02?.banner1 || {
    subtitle: 'Weekly Special', title: 'Make grocery shopping easy', buttonText: 'Shop Now',
    image: 'https://images.unsplash.com/photo-1542838132-92c53300491e?auto=format&fit=crop&w=600&q=80'
  };
  const banner2 = homeConfig?.theme02?.banner2 || {
    subtitle: 'Daily Essentials', title: 'Get your everyday needs here', buttonText: 'Shop Now',
    image: 'https://images.unsplash.com/photo-1604719312566-8912e9227c6a?auto=format&fit=crop&w=600&q=80'
  };

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

  const todayDealsProductIds = homeConfig?.theme02?.todayDealsProductIds || [];
  let todayDealsProducts = (featuredProducts || []).filter(p => todayDealsProductIds.includes(p.id));
  if (!isLiveMode || todayDealsProducts.length === 0) todayDealsProducts = displayProducts.slice(0, 6);

  let heroSliders = homeConfig?.theme02?.heroSliders || [];
  if (!heroSliders.length) {
    heroSliders = [
      { image: 'https://images.unsplash.com/photo-1542838132-92c53300491e?auto=format&fit=crop&w=1200&q=80' },
      { image: 'https://images.unsplash.com/photo-1604719312566-8912e9227c6a?auto=format&fit=crop&w=1200&q=80' }
    ];
  }

  const blogPosts = homeConfig?.theme02?.blogPosts || BLOG_POSTS;

  let bestSellerProductIds = homeConfig?.theme02?.bestSellerProductIds || [];
  let bestSellerProducts = (featuredProducts || []).filter(p => bestSellerProductIds.includes(p.id));
  if (!bestSellerProducts.length) bestSellerProducts = displayProducts;

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

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

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

  useEffect(() => {
    const tick = () => {
      const now = new Date();
      const cd: Record<string, string> = {};
      displayProducts.forEach(p => {
        cd[p.id] = `${String(23 - now.getHours()).padStart(2,'0')}:${String(59 - now.getMinutes()).padStart(2,'0')}:${String(59 - now.getSeconds()).padStart(2,'0')}`;
      });
      setCountdowns(cd);
    };
    tick();
    const t = setInterval(tick, 1000);
    return () => clearInterval(t);
  }, [displayProducts]);

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

  return (
    <div className="bg-slate-50 font-sans">
      {cs && (
        <style dangerouslySetInnerHTML={{ __html: `
          .hp02-primary { color: ${cs.primary} !important; }
          .hp02-bg { background-color: ${cs.primary} !important; }
        ` }} />
      )}

      {/* ── Coupon Bar ──────────────────────────────── */}
      {settings.marketingCoupons?.filter(c => c.showOnHome).length > 0 && (
        <div className="bg-[#1E1B4B] overflow-x-auto no-scrollbar">
          <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="text-indigo-300 animate-pulse 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-[#1E1B4B] 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/40 to-transparent" />
            </div>
          ))}
          {heroSliders.length > 1 && (
            <div className="absolute bottom-2.5 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 ${i === currentSlide ? 'bg-white w-5' : 'bg-white/40 w-1.5'}`} />
              ))}
            </div>
          )}
        </div>

        {/* Category Scroll */}
        <div className="bg-white border-b border-slate-100">
          <div className="flex items-center justify-between px-4 pt-4 pb-2">
            <MobileSectionHeader title="Categories" icon={Tag} accent="#1E1B4B" />
            <button onClick={() => navigateTo('shop')} className="flex items-center gap-0.5 text-[11px] font-bold text-indigo-700 active:opacity-60">
              সব <ChevronRight size={11} />
            </button>
          </div>
          <div className="flex gap-4 overflow-x-auto no-scrollbar px-4 pb-4">
            {displayCategories.map((cat: any, 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-[52px] h-[52px] rounded-2xl overflow-hidden border-2 border-slate-100 bg-slate-50 shadow-sm">
                  <img src={cat.icon} 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-[54px] leading-tight line-clamp-1">{cat.name}</span>
              </button>
            ))}
          </div>
        </div>

        {/* Flash Deals Section */}
        {todayDealsProducts.length > 0 && (
          <div className="px-3 py-4">
            {/* Header with live countdown */}
            <div className="flex items-center justify-between mb-3 bg-gradient-to-r from-[#1E1B4B] to-[#3730A3] rounded-2xl px-4 py-3">
              <div className="flex items-center gap-2">
                <div className="w-6 h-6 rounded-full bg-red-500 flex items-center justify-center">
                  <Zap size={12} className="text-white" fill="currentColor" />
                </div>
                <div>
                  <p className="text-white text-[13px] font-black leading-none">Flash Deals</p>
                  <p className="text-indigo-300 text-[9px] mt-0.5">Today only</p>
                </div>
              </div>
              <div className="flex items-center gap-1">
                {(countdowns[todayDealsProducts[0]?.id] || '00:00:00').split(':').map((seg, i) => (
                  <React.Fragment key={i}>
                    <div className="bg-white/10 border border-white/20 rounded-lg px-1.5 py-1 min-w-[28px] text-center">
                      <span className="text-white font-mono text-[12px] font-black">{seg}</span>
                    </div>
                    {i < 2 && <span className="text-white/60 font-black text-[11px]">:</span>}
                  </React.Fragment>
                ))}
              </div>
            </div>

            {/* Deal cards grid */}
            <div className="grid grid-cols-2 gap-2.5">
              {todayDealsProducts.slice(0, 4).map(p => (
                <MobileDealCard
                  key={p.id}
                  product={p}
                  countdown={countdowns[p.id] || '00:00:00'}
                  onCart={() => addCart(p)}
                  onSelect={() => onSelectProduct(p)}
                />
              ))}
            </div>

            <button
              onClick={() => navigateTo('shop')}
              className="w-full mt-3 flex items-center justify-center gap-1.5 text-[12px] font-black text-[#1E1B4B] bg-white border border-indigo-100 py-3 rounded-xl shadow-sm active:bg-indigo-50 transition-colors"
            >
              সব Deals দেখুন <ArrowRight size={13} />
            </button>
          </div>
        )}

        {/* Editor's Pick */}
        <div className="bg-white px-3 py-4 border-y border-slate-100">
          <MobileSectionHeader
            title="Editor's Pick"
            sub="Handpicked just for you"
            icon={TrendingUp}
            accent="#634C9F"
            onViewAll={() => navigateTo('shop')}
          />
          <div className="grid grid-cols-2 gap-2.5">
            {displayProducts.slice(0, 6).map((p, idx) => (
              <MobileProductCard
                key={p.id}
                product={p}
                discountPct={10 + idx * 2}
                badgeLabel={`-${10 + idx * 2}%`}
                onCart={() => addCart(p)}
                onBuy={() => buyNow(p)}
                onSelect={() => onSelectProduct(p)}
              />
            ))}
          </div>
        </div>

        {/* Promo Banners */}
        <div className="px-3 py-4 flex flex-col gap-3">
          {[banner1, banner2].map((b, i) => (
            <button
              key={i}
              onClick={() => navigateTo('shop')}
              className="relative w-full h-36 rounded-2xl overflow-hidden shadow-sm active:opacity-90 transition-opacity text-left"
            >
              <img src={b.image} alt={b.title} className="absolute inset-0 w-full h-full object-cover" />
              <div className={`absolute inset-0 ${i === 0 ? 'bg-gradient-to-r from-amber-900/80 to-transparent' : 'bg-gradient-to-r from-emerald-900/80 to-transparent'}`} />
              <div className="absolute inset-0 p-4 flex flex-col justify-center max-w-[65%]">
                <span className={`text-[10px] font-black uppercase tracking-widest mb-1 ${i === 0 ? 'text-amber-300' : 'text-emerald-300'}`}>{b.subtitle}</span>
                <h3 className="text-white text-[13px] font-black leading-snug mb-2.5 line-clamp-2">{b.title}</h3>
                <span className={`inline-flex items-center gap-1 text-[10px] font-black px-3 py-1.5 rounded-full w-fit ${i === 0 ? 'bg-amber-400 text-amber-900' : 'bg-emerald-400 text-emerald-900'}`}>
                  {b.buttonText} <ArrowRight size={9} />
                </span>
              </div>
            </button>
          ))}
        </div>

        {/* Best Sellers */}
        <div className="bg-white px-3 py-4 border-y border-slate-100">
          <MobileSectionHeader
            title="Best Sellers"
            sub="Most loved this week"
            icon={Star}
            accent="#D93939"
            onViewAll={() => navigateTo('shop')}
          />
          <div className="grid grid-cols-2 gap-2.5">
            {bestSellerProducts.slice(0, 6).map((p, idx) => (
              <MobileProductCard
                key={`bs-${p.id}`}
                product={p}
                discountPct={20}
                badgeLabel="⭐ Best"
                badgeColor="bg-amber-500"
                onCart={() => addCart(p)}
                onBuy={() => buyNow(p)}
                onSelect={() => onSelectProduct(p)}
              />
            ))}
          </div>
        </div>

        {/* Blog — horizontal scroll */}
        <div className="bg-white px-3 py-4">
          <MobileSectionHeader title="Latest News" sub="Stay updated" />
          <div className="flex gap-3 overflow-x-auto no-scrollbar">
            {blogPosts.map(post => (
              <div key={post.id} className="flex-shrink-0 w-52 bg-slate-50 rounded-2xl overflow-hidden border border-slate-100 shadow-sm active:opacity-80 transition-opacity cursor-pointer">
                <div className="relative aspect-video overflow-hidden">
                  <img src={post.image} alt={post.title} className="w-full h-full object-cover" loading="lazy" />
                  {post.category && (
                    <span className="absolute top-2 left-2 bg-white/90 text-slate-700 text-[8px] font-black px-1.5 py-0.5 rounded uppercase tracking-wide">
                      {post.category}
                    </span>
                  )}
                </div>
                <div className="p-3">
                  <h3 className="text-[11px] font-bold text-slate-800 line-clamp-2 leading-snug mb-1.5">{post.title}</h3>
                  <p className="text-[9px] text-slate-400 font-semibold">By {post.author} · {post.date}</p>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Bottom spacer for nav */}
        <div className="h-4" />
      </div>

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

        {/* Hero Slider */}
        <div className="relative w-full overflow-hidden bg-slate-900" style={{ minHeight: 480 }}>
          {heroSliders.map((s, i) => (
            <div key={i} className={`absolute inset-0 transition-opacity duration-1000 ${i === currentSlide ? 'opacity-100' : 'opacity-0'}`}>
              <img src={s.image} className="w-full h-full object-cover" alt={`Slide ${i}`} />
            </div>
          ))}
          {heroSliders.length > 1 && (
            <div className="absolute bottom-6 left-1/2 -translate-x-1/2 flex gap-2 z-10">
              {heroSliders.map((_, i) => (
                <button key={i} onClick={() => setCurrentSlide(i)}
                  className={`h-2.5 rounded-full transition-all duration-300 ${i === currentSlide ? 'bg-white w-8' : 'bg-white/50 w-2.5'}`} />
              ))}
            </div>
          )}
        </div>

        <div className="max-w-[1400px] mx-auto px-4">

          {/* Categories */}
          <div className="bg-white rounded-3xl shadow-sm border border-slate-100 mt-8 mb-10 overflow-hidden">
            <div className="flex items-center justify-between px-6 pt-5 pb-3 border-b border-gray-50">
              <h3 className="font-black text-[#1E1B4B] text-sm uppercase tracking-widest">Shop by Category</h3>
              <button onClick={() => navigateTo('shop')} className="text-xs font-bold text-[#634C9F] hover:underline flex items-center gap-1">View All <ArrowRight size={12} /></button>
            </div>
            <div className="flex gap-4 overflow-x-auto px-6 py-5" style={{ scrollbarWidth: 'thin' }}>
              {displayCategories.map((cat: any, i) => (
                <div key={i} onClick={() => navigateTo('shop')} className="flex flex-col items-center flex-shrink-0 group cursor-pointer w-20">
                  <div className="w-16 h-16 mb-2 rounded-full overflow-hidden border-2 border-gray-100 group-hover:border-[#634C9F] transition-all duration-300 shadow-sm group-hover:-translate-y-1">
                    <img src={cat.icon} alt={cat.name} className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500" />
                  </div>
                  <span className="text-[11px] font-semibold text-center text-gray-600 group-hover:text-[#634C9F] transition-colors line-clamp-2">{cat.name}</span>
                </div>
              ))}
            </div>
          </div>

          {/* Editor's Pick */}
          <div className="mb-16">
            <div className="flex items-end justify-between border-b border-gray-200 pb-4 mb-8">
              <div>
                <h2 className="text-2xl md:text-3xl font-black text-[#1E1B4B]">Editor's Pick</h2>
                <p className="text-gray-500 text-sm mt-1">Handpicked fresh products</p>
              </div>
              <button onClick={() => navigateTo('shop')} className="text-sm font-semibold text-[#634C9F] hover:underline flex items-center gap-1">View All <ArrowRight size={16} /></button>
            </div>
            <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4">
              {displayProducts.slice(0, 10).map((p, idx) => (
                <div key={p.id} className="group border border-gray-100 rounded-2xl bg-white p-4 hover:shadow-xl transition-all duration-300 relative flex flex-col cursor-pointer">
                  <div className="absolute top-3 left-3 z-10 bg-red-600 text-white text-[10px] font-bold px-2 py-1 rounded-full">-{10 + idx}%</div>
                  <div className="aspect-square mb-4 flex items-center justify-center p-3 bg-gray-50 rounded-xl" onClick={() => onSelectProduct(p)}>
                    <img src={p.image} alt={p.name} className="w-full h-full object-contain mix-blend-multiply group-hover:scale-110 transition-transform duration-500" />
                  </div>
                  <div className="flex flex-col flex-grow">
                    <Stars />
                    <h3 className="font-bold text-[#1E1B4B] text-sm leading-tight mt-2 mb-2 line-clamp-2 hover:text-[#634C9F]" onClick={() => onSelectProduct(p)}>{p.name}</h3>
                    <div className="flex items-baseline gap-2 mb-4">
                      <span className="text-red-600 font-black text-lg">৳{p.price}</span>
                      <span className="text-gray-400 text-xs line-through">৳{Math.round(p.price * 1.25)}</span>
                    </div>
                    <button
                      onClick={(e) => { e.stopPropagation(); addCart(p); }}
                      className="w-full mt-auto border-2 border-[#634C9F] text-[#634C9F] font-bold rounded-full py-2 text-xs hover:bg-[#634C9F] hover:text-white transition-all duration-200 flex items-center justify-center gap-1.5"
                    >
                      <ShoppingCart size={12} /> Add to Cart
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Today's Deals */}
          {todayDealsProducts.length > 0 && (
            <div className="mb-16 rounded-[32px] bg-gradient-to-br from-[#FFF5ED] to-[#FFEBE0] p-8 md:p-12 border border-orange-100 relative overflow-hidden">
              <div className="flex flex-col md:flex-row items-end justify-between border-b border-orange-200/60 pb-5 mb-10">
                <div className="flex items-center gap-3 mb-2">
                  <div className="w-8 h-8 rounded-full bg-red-500 text-white flex items-center justify-center animate-bounce shadow-lg shadow-red-500/30">
                    <Zap size={16} fill="currentColor" />
                  </div>
                  <div>
                    <h2 className="text-3xl font-black text-slate-800">Today's Deals</h2>
                    <p className="text-orange-800 font-semibold text-sm">Grab top products at crazy prices.</p>
                  </div>
                </div>
                <button onClick={() => navigateTo('shop')} className="hidden md:flex text-sm font-black text-red-600 bg-white px-5 py-2.5 rounded-full hover:bg-red-50 transition items-center gap-2 shadow-sm border border-orange-100">
                  View All Deals <ArrowRight size={16} />
                </button>
              </div>
              <div className="grid grid-cols-2 lg:grid-cols-4 gap-5">
                {todayDealsProducts.slice(0, 4).map(p => (
                  <div key={`deal-${p.id}`} className="group bg-white rounded-3xl p-5 shadow-sm hover:shadow-xl transition-all duration-300 border border-white/60 relative cursor-pointer flex flex-col hover:-translate-y-1" onClick={() => onSelectProduct(p)}>
                    <div className="absolute -top-3 -right-3 z-20 w-12 h-12 bg-red-500 rounded-full flex flex-col items-center justify-center text-white font-black text-[10px] rotate-12 shadow-lg">
                      <span>SAVE</span><span className="text-sm">🔥</span>
                    </div>
                    <div className="aspect-square mb-5 bg-orange-50/30 rounded-2xl p-4 flex items-center justify-center">
                      <img src={p.image} alt={p.name} className="w-full h-full object-contain mix-blend-multiply group-hover:scale-110 transition-transform duration-500" />
                    </div>
                    <div className="flex flex-col flex-grow">
                      <Stars />
                      <h3 className="font-bold text-slate-800 text-sm leading-snug mt-2 mb-3 line-clamp-2 group-hover:text-red-500 transition-colors">{p.name}</h3>
                      <div className="mt-auto">
                        <div className="flex items-center gap-3 bg-red-50/50 rounded-xl p-2.5 border border-red-100/50 mb-3">
                          <span className="text-xl font-black text-red-600">৳{p.price}</span>
                          <span className="text-xs text-slate-400 line-through">৳{Math.round(p.price * 1.35)}</span>
                        </div>
                        <button onClick={(e) => { e.stopPropagation(); addCart(p); }}
                          className="w-full bg-slate-900 text-white font-bold py-2.5 rounded-xl text-xs hover:bg-red-600 transition-colors shadow-md">
                          Grab Deal
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Promo Banners */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-16">
            {[banner1, banner2].map((b, i) => (
              <div key={i} className="rounded-2xl overflow-hidden relative h-[220px] group cursor-pointer hover:shadow-lg transition" onClick={() => navigateTo('shop')}>
                <img src={b.image} alt={b.title} className="w-full h-full object-cover group-hover:scale-105 transition duration-500" />
                <div className={`absolute inset-0 ${i === 0 ? 'bg-gradient-to-r from-amber-900/75' : 'bg-gradient-to-r from-emerald-900/75'} to-transparent flex flex-col justify-center pl-8 pr-28`}>
                  <span className={`text-xs font-black uppercase tracking-widest mb-1 ${i === 0 ? 'text-amber-300' : 'text-emerald-300'}`}>{b.subtitle}</span>
                  <h3 className="text-white text-xl font-black leading-tight mb-3">{b.title}</h3>
                  <span className={`inline-flex items-center gap-1 text-xs font-black px-4 py-2 rounded-full w-fit ${i === 0 ? 'bg-white text-amber-900 hover:bg-amber-50' : 'bg-white text-emerald-900 hover:bg-emerald-50'} transition`}>
                    {b.buttonText} <ArrowRight size={12} />
                  </span>
                </div>
              </div>
            ))}
          </div>

          {/* Best Sellers */}
          <div className="mb-16">
            <div className="flex items-end justify-between border-b border-gray-200 pb-4 mb-8">
              <div>
                <h2 className="text-2xl md:text-3xl font-black text-[#1E1B4B]">Best Sellers</h2>
                <p className="text-gray-500 text-sm mt-1">Most loved products this week</p>
              </div>
              <button onClick={() => navigateTo('shop')} className="text-sm font-semibold text-[#634C9F] hover:underline flex items-center gap-1">View All <ArrowRight size={16} /></button>
            </div>
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              <div className="flex flex-col gap-4">
                {bestSellerProducts.slice(1, 5).map(p => (
                  <div key={`l-${p.id}`} className="group flex gap-3 border border-gray-100 rounded-xl p-3 bg-white hover:shadow-md cursor-pointer transition" onClick={() => onSelectProduct(p)}>
                    <div className="w-16 h-16 bg-gray-50 rounded-lg p-2 flex-shrink-0">
                      <img src={p.image} alt={p.name} className="w-full h-full object-contain mix-blend-multiply group-hover:scale-110 transition" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <Stars />
                      <h4 className="font-bold text-[#1E1B4B] text-xs leading-tight mt-1 line-clamp-2">{p.name}</h4>
                      <div className="flex items-baseline gap-1 mt-1 mb-2">
                        <span className="text-red-600 font-black text-sm">৳{p.price}</span>
                        <span className="text-gray-400 text-[10px] line-through">৳{Math.round(p.price * 1.2)}</span>
                      </div>
                      <button onClick={(e) => { e.stopPropagation(); addCart(p); }}
                        className="w-full bg-gray-100 text-[#634C9F] hover:bg-[#634C9F] hover:text-white py-1.5 rounded-lg text-[10px] font-bold uppercase tracking-wider transition flex items-center justify-center gap-1">
                        <ShoppingCart size={10} /> Add to Cart
                      </button>
                    </div>
                  </div>
                ))}
              </div>
              <div className="border-2 border-[#D93939] rounded-2xl bg-white p-6 hover:shadow-2xl transition-shadow relative cursor-pointer" onClick={() => onSelectProduct(bestSellerProducts[0])}>
                <div className="absolute -top-3 left-6 bg-[#D93939] text-white text-xs font-bold px-3 py-1 rounded-full shadow-lg">🔥 Hot Deal</div>
                <div className="flex justify-center mb-6 pt-4">
                  <img src={bestSellerProducts[0]?.image} alt="Best" className="h-52 object-contain mix-blend-multiply hover:scale-105 transition" />
                </div>
                <div className="text-center">
                  <div className="flex justify-center mb-2"><Stars /></div>
                  <h3 className="text-xl font-black text-[#1E1B4B] mb-3">{bestSellerProducts[0]?.name}</h3>
                  <div className="flex items-center justify-center gap-3 mb-5">
                    <span className="text-[#D93939] font-black text-3xl">৳{bestSellerProducts[0]?.price}</span>
                    <span className="text-gray-400 text-lg line-through">৳{Math.round((bestSellerProducts[0]?.price || 0) * 1.3)}</span>
                  </div>
                  <div className="bg-gray-50 rounded-xl p-4 mb-5">
                    <p className="text-xs text-gray-500 font-bold mb-2 text-center">⏰ Offer ends in</p>
                    <div className="flex justify-center font-mono text-sm font-bold bg-white border py-2 rounded-lg mb-3">
                      {countdowns[bestSellerProducts[0]?.id || ''] || '00:00:00'}
                    </div>
                    <div className="w-full h-2 bg-gray-200 rounded-full"><div className="h-full bg-[#34A853] rounded-full" style={{ width: '62%' }} /></div>
                    <p className="text-xs text-gray-500 text-center mt-2">62% stock remaining</p>
                  </div>
                  <button onClick={(e) => { e.stopPropagation(); if (bestSellerProducts[0]) addCart(bestSellerProducts[0]); }}
                    className="w-full bg-[#34A853] text-white font-black py-3.5 rounded-xl shadow-lg hover:bg-green-600 transition text-sm uppercase tracking-wide flex items-center justify-center gap-2">
                    <ShoppingCart size={16} /> Add to Cart
                  </button>
                </div>
              </div>
              <div className="flex flex-col gap-4">
                {bestSellerProducts.slice(5, 9).map(p => (
                  <div key={`r-${p.id}`} className="group flex gap-3 border border-gray-100 rounded-xl p-3 bg-white hover:shadow-md cursor-pointer transition relative" onClick={() => onSelectProduct(p)}>
                    <div className="w-16 h-16 bg-gray-50 rounded-lg p-2 flex-shrink-0 relative">
                      <div className="absolute -top-1 -left-1 bg-blue-500 text-white text-[8px] font-bold px-1 rounded">NEW</div>
                      <img src={p.image} alt={p.name} className="w-full h-full object-contain mix-blend-multiply group-hover:scale-110 transition" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <Stars />
                      <h4 className="font-bold text-[#1E1B4B] text-xs leading-tight mt-1 line-clamp-2">{p.name}</h4>
                      <div className="flex items-baseline gap-1 mt-1 mb-2">
                        <span className="text-red-600 font-black text-sm">৳{p.price}</span>
                        <span className="text-gray-400 text-[10px] line-through">৳{Math.round(p.price * 1.18)}</span>
                      </div>
                      <button onClick={(e) => { e.stopPropagation(); addCart(p); }}
                        className="w-full bg-gray-100 text-[#634C9F] hover:bg-[#634C9F] hover:text-white py-1.5 rounded-lg text-[10px] font-bold uppercase tracking-wider transition flex items-center justify-center gap-1">
                        <ShoppingCart size={10} /> Add to Cart
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>

          {/* Blog */}
          <div className="mb-16">
            <div className="flex items-end justify-between border-b border-gray-200 pb-4 mb-8">
              <div>
                <h2 className="text-2xl md:text-3xl font-black text-[#1E1B4B]">Our News</h2>
                <p className="text-gray-500 text-sm mt-1">Latest updates</p>
              </div>
              <button className="text-sm font-semibold text-[#634C9F] hover:underline flex items-center gap-1">All Articles <ArrowRight size={16} /></button>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
              {blogPosts.map(post => (
                <div key={post.id} className="group cursor-pointer">
                  <div className="rounded-2xl overflow-hidden mb-4 relative aspect-[4/3]">
                    {post.category && <div className="absolute top-3 left-3 z-10 bg-white text-gray-800 text-[9px] font-black px-2 py-1 rounded shadow uppercase">{post.category}</div>}
                    <img src={post.image} alt={post.title} className="w-full h-full object-cover group-hover:scale-105 transition duration-500" />
                  </div>
                  <h3 className="font-black text-base leading-tight text-[#1E1B4B] mb-3 line-clamp-2 group-hover:text-[#634C9F] transition">{post.title}</h3>
                  <div className="flex items-center text-[10px] font-bold text-gray-400 gap-2">
                    <span className="text-[#634C9F]">By {post.author}</span><span>•</span><span>{post.date}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>

        <AppDownloadBanner settings={settings} />

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

export default HomePage02;