import React, { useState, useEffect } from 'react';
import { Save, Image as ImageIcon, Upload, Eye, X, Plus, RefreshCw, LayoutTemplate, Check } from 'lucide-react';
import { HomePageConfig, SiteSettings, Product } from '../types';
import { SCHEME_LABELS } from '../lib/themeColors';
import HomePage01 from './HomePage01';
import HomePage02 from './HomePage02';
import HomePage03 from './HomePage03';
import HomePage04 from './HomePage04';
import HomePage05 from './HomePage05';
import { GlobalThemeHeader } from './ThemeHeaders';
import { GlobalThemeFooter } from './ThemeFooters';

interface HomePageEditorProps {
  settings: SiteSettings;
  products: Product[];
  onSave: (updates: Partial<SiteSettings>) => Promise<void>;
  onUploadImage: (file: File) => Promise<string | null>;
}

const DEFAULT_CONFIG: HomePageConfig = {
  theme: '01',
  theme01: {
    promoRow1: [
      { title: 'Fresh Eggs', subtitle: 'Farm Fresh', discount: '15% off', image: 'https://images.unsplash.com/photo-1582722872445-44dc5f7e3c8f?w=300&h=200&fit=crop', bg: '#FEF3C7' },
      { title: 'Healthy Snacks', subtitle: 'Nutritious & Tasty', discount: '20% off', image: 'https://images.unsplash.com/photo-1599599810769-bcde5a160d32?w=300&h=200&fit=crop', bg: '#D1FAE5' },
      { title: 'Fresh Vegetables', subtitle: 'Organic Choice', discount: '10% off', image: 'https://images.unsplash.com/photo-1566385101042-1a0aa0c1268c?w=300&h=200&fit=crop', bg: '#E0E7FF' }
    ],
    promoRow2: [
      { title: '30% OFF', subtitle: 'On Beverages', color: '#E91E63' },
      { title: 'Buy 1 Get 1', subtitle: 'On Snacks', color: '#FF9800' },
      { title: 'Free Delivery', subtitle: 'On $50+ order', color: '#4CAF50' },
      { title: 'Member Price', subtitle: 'Extra 10% off', color: '#9C27B0' }
    ]
  },
  theme02: {
    heroTitle: 'Discover Premium Groceries',
    heroSubtitle: 'Fresh, organic, and delivered right to your doorstep.',
    heroTagline: 'Welcome to Store'
  },
  theme03: {
    heroTitle: 'Discover Your Inner Glow',
    heroSubtitle: 'Premium skincare formulated with active ingredients for visible results.',
    heroHighlight: 'Skincare',
    promoBanners: [
      { title: 'Spring Collection', image: 'https://images.unsplash.com/photo-1615397323136-1e0f0f4b3017?w=600&h=400&fit=crop', linkText: 'Shop New Arrivals' },
      { title: 'Premium Skincare', image: 'https://images.unsplash.com/photo-1570194065650-d99fb4b8ccb0?w=600&h=400&fit=crop', linkText: 'Explore Sets' }
    ],
    megaDeals: [
      { title: 'Oral Care', subtitle: 'Up to 40% off', image: 'https://images.unsplash.com/photo-1557177324-56c542165309?w=200&h=200&fit=crop', bg: '#FEF3C7' },
      { title: 'Hygiene Corner', subtitle: '22% off', image: 'https://images.unsplash.com/photo-1583947581927-860b2d8d0d7c?w=200&h=200&fit=crop', bg: '#FCE7F3' },
      { title: 'Skin Care', subtitle: '30% off', image: 'https://images.unsplash.com/photo-1556228578-0d85b1a4d571?w=200&h=200&fit=crop', bg: '#DBEAFE' },
      { title: 'Hair Care', subtitle: '25% off', image: 'https://images.unsplash.com/photo-1535585209827-a15fcdbc4c2d?w=200&h=200&fit=crop', bg: '#D1FAE5' },
      { title: 'Makeup', subtitle: '35% off', image: 'https://images.unsplash.com/photo-1596462502278-27bfdc403348?w=200&h=200&fit=crop', bg: '#FEE2E2' },
      { title: 'Fragrances', subtitle: '20% off', image: 'https://images.unsplash.com/photo-1588405748880-12d1d2a59f75?w=200&h=200&fit=crop', bg: '#EDE9FE' },
      { title: 'Baby Care', subtitle: '15% off', image: 'https://images.unsplash.com/photo-1519689680058-324335c77eba?w=200&h=200&fit=crop', bg: '#FFEDD5' },
      { title: 'Men\'s Grooming', subtitle: '28% off', image: 'https://images.unsplash.com/photo-1621605815971-fbc98d665033?w=200&h=200&fit=crop', bg: '#E0E7FF' }
    ]
  },
  theme04: {
    banner1: { title: 'Pure Cold Pressed Coconut Oil', subtitle: 'Premium Quality', description: 'Starting from ৳399 only', image: 'https://images.unsplash.com/photo-1474979266404-7eaacbcd87c5?w=600&h=400&fit=crop', buttonText: 'Shop Now →' },
    banner2: { title: 'Desi Ghee Pure & A2', subtitle: 'Traditional Recipe', description: 'Get 20% off on first order', image: 'https://images.unsplash.com/photo-1634304250447-9d6db9c5e390?w=600&h=400&fit=crop', buttonText: 'Shop Now →' }
  },
  theme05: {
    heroTagline: 'Summer Collection 2024',
    heroTitle: 'Elevate Your Style',
    heroSubtitle: 'Discover the latest trends in fashion. Premium quality, timeless designs.',
    heroImage: 'https://images.unsplash.com/photo-1445205170230-053b83016050?w=1920&h=800&fit=crop',
    promoTagline: 'Limited Time Offer',
    promoTitle: 'Summer Sale',
    promoSubtitle: 'Up to 50% off on selected items',
    promoImage: 'https://images.unsplash.com/photo-1483985988355-763728e1935b?w=1920&h=500&fit=crop'
  }
};

const HomePageEditor: React.FC<HomePageEditorProps> = ({ settings, products, onSave, onUploadImage }) => {
  const [config, setConfig] = useState<HomePageConfig>(DEFAULT_CONFIG);
  const [isSaving, setIsSaving] = useState(false);
  const [isPreviewMode, setIsPreviewMode] = useState(false);
  const [uploadingField, setUploadingField] = useState<string | null>(null);

  useEffect(() => {
    if (settings.homePageJson) {
      try {
        const parsed = JSON.parse(settings.homePageJson);
        // Merge with DEFAULT_CONFIG to ensure all keys exist
        setConfig({
          theme: parsed.theme || '01',
          theme01: { ...DEFAULT_CONFIG.theme01, ...parsed.theme01 },
          theme02: { ...DEFAULT_CONFIG.theme02, ...parsed.theme02 },
          theme03: { ...DEFAULT_CONFIG.theme03, ...parsed.theme03 },
          theme04: { ...DEFAULT_CONFIG.theme04, ...parsed.theme04 },
          theme05: { ...DEFAULT_CONFIG.theme05, ...parsed.theme05 },
          // Legacy properties logic
          navbar: { ...DEFAULT_CONFIG.navbar, ...parsed.navbar },
          features: parsed.features || DEFAULT_CONFIG.features,
          promoRow1: parsed.promoRow1 || DEFAULT_CONFIG.promoRow1,
          promoRow2: parsed.promoRow2 || DEFAULT_CONFIG.promoRow2,
          specialBanner: { ...DEFAULT_CONFIG.specialBanner, ...parsed.specialBanner }
        });
      } catch (e) {
        console.error('Failed to parse homePageJson', e);
      }
    }
  }, [settings.homePageJson]);

  const handleSave = async () => {
    setIsSaving(true);
    try {
      // ✅ FIX: Explicitly set both theme and activeTheme at the top level
      // This ensures App.tsx can resolve the theme regardless of which key it checks first.
      const configToSave = {
        ...config,
        theme: config.theme,           // primary key App.tsx uses
        activeTheme: config.theme,     // backward-compat key
      };
      const updates: any = { homePageJson: JSON.stringify(configToSave) };
      
      // Theme base categories — swap on theme change, but keep admin's own custom cats
      const ALL_THEME_BASE_CATS: Record<string, string[]> = {
        '01': ["Fruits & Vegetables", "Meats & Seafood", "Breakfast & Dairy", "Beverages", "Breads & Bakery", "Frozen Foods", "Biscuits & Snacks", "Beauty & Hygiene"],
        '02': ["Fruits", "Baby", "Beverages", "Meats", "Snacks", "Bakery", "Dairy", "Frozen", "Beauty"],
        '03': ["Oral Care", "Hygiene Corner", "Skin Care", "Hair Care", "Makeup", "Fragrances", "Baby Care", "Men's Grooming"],
        '04': ["Oil & Ghee", "Honey", "Dates", "Spices", "Nuts & Seeds", "Herbal Products", "Organic Foods", "Gift Packs"],
        '05': ["New Arrivals", "Women", "Men", "Kids", "Accessories"],
      };

      // Collect ALL base cats (across every theme)
      const allBaseCatNames = new Set(
        Object.values(ALL_THEME_BASE_CATS).flat().map(n => n.toLowerCase())
      );

      // Load existing saved categories
      let existingCats: any[] = [];
      try {
        if (settings.categoriesJson) existingCats = JSON.parse(settings.categoriesJson);
      } catch(e) {}

      // Preserve only admin-custom categories (not in any theme's base list)
      const adminCustomCats = existingCats.filter(
        (c: any) => !allBaseCatNames.has((c.name || '').toLowerCase())
      );

      // Build the new category list = current theme's base cats + admin's custom cats
      const currentThemeBase = (ALL_THEME_BASE_CATS[config.theme || '01'] || []).map((c: string) => ({
        name: c,
        slug: c.toLowerCase().replace(/ /g, '-').replace(/&/g, 'and').replace(/'/g, '')
      }));

      const newCats = [...currentThemeBase, ...adminCustomCats];
      updates.categoriesJson = JSON.stringify(newCats);
      
      await onSave(updates);
    } finally {
      setIsSaving(false);
    }
  };

  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>, fieldCallback: (url: string) => void, fieldId: string) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploadingField(fieldId);
    try {
      const url = await onUploadImage(file);
      if (url) {
        fieldCallback(url);
      }
    } finally {
      setUploadingField(null);
    }
  };

  return (
    <div className="space-y-8 animate-fade-in-up pb-20">
      <div className="flex items-center justify-between bg-white dark:bg-slate-900 p-8 rounded-[32px] border shadow-sm">
        <div>
          <h2 className="text-3xl font-black text-slate-800 dark:text-white">Home Page Editor</h2>
          <p className="text-slate-400 font-medium mt-1">Live edit banners, texts, and promotions on the web app home page.</p>
        </div>
        <div className="flex gap-3">
          <button
            onClick={() => setIsPreviewMode(true)}
            className="bg-slate-100 hover:bg-slate-200 text-slate-700 px-6 py-4 rounded-2xl font-black text-sm uppercase tracking-wider transition-all flex items-center gap-2"
          >
            <Eye size={18} /> Preview Theme
          </button>
          <button
            onClick={handleSave}
            disabled={isSaving}
            className="bg-red-600 hover:bg-red-700 text-white px-8 py-4 rounded-2xl font-black text-sm uppercase tracking-wider shadow-lg shadow-red-600/20 transition-all flex items-center gap-2 disabled:opacity-50"
          >
            {isSaving ? <RefreshCw className="animate-spin" size={18} /> : <Save size={18} />}
            {isSaving ? 'Saving...' : 'Save Live Changes'}
          </button>
        </div>
      </div>

      {/* Theme Selection */}
      <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
        <h3 className="text-xl font-black mb-6 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4 flex items-center gap-2">
          <LayoutTemplate size={24} className="text-[#634C9F]" /> Select Home Page Theme
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-5 gap-4">
          {[
            { id: '01', name: 'Default App Style', desc: 'Standard eCommerce layout with banners and grids.' },
            { id: '02', name: 'Minimalist Clean', desc: 'Whitespace focused, premium product showcase layout.' },
            { id: '03', name: 'Grocery Supermarket', desc: 'Category-first layout optimized for daily essentials.' },
            { id: '04', name: 'Organic Food', desc: 'Dark theme with heavy focus on premium selection.' },
            { id: '05', name: 'Fashion', desc: 'Tells your factory story alongside signature products.' },
          ].map((th) => (
            <label
              key={th.id}
              className={`relative flex flex-col items-center text-center p-6 rounded-2xl border-2 cursor-pointer transition-all ${config.theme === th.id
                ? 'border-[#634C9F] bg-purple-50 ring-4 ring-purple-500/20 shadow-xl'
                : 'border-slate-100 bg-white hover:border-slate-300 hover:shadow-md'
                }`}
            >
              <input
                type="radio"
                name="homeTheme"
                value={th.id}
                checked={config.theme === th.id}
                onChange={(e) => setConfig({ ...config, theme: e.target.value as any })}
                className="hidden"
              />
              <div className={`w-12 h-12 rounded-full flex items-center justify-center font-black text-lg mb-3 ${config.theme === th.id ? 'bg-[#634C9F] text-white' : 'bg-slate-100 text-slate-500'
                }`}>
                {th.id}
              </div>
              <h4 className="font-bold text-slate-800 text-sm mb-1">{th.name}</h4>
              <p className="text-[10px] text-slate-500 leading-tight">{th.desc}</p>

              {config.theme === th.id && (
                <div className="absolute top-3 right-3 w-4 h-4 rounded-full bg-green-500 border-2 border-white shadow-sm" />
              )}
            </label>
          ))}
        </div>
      </div>

      {/* Theme 01 Editor */}
      {config.theme === '01' && (
        <div className="space-y-8">
          {/* Color Scheme Picker */}
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-2 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">🎨 Color Scheme</h3>
            <p className="text-sm text-slate-500 mb-5">Choose a color palette for this homepage theme.</p>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
              {SCHEME_LABELS.map((scheme, idx) => {
                const isActive = config.theme01?.colorScheme === idx;
                return (
                  <button
                    key={idx}
                    onClick={() => setConfig({ ...config, theme01: { ...config.theme01, colorScheme: isActive ? undefined : idx } })}
                    className={`relative p-4 rounded-2xl border-2 transition-all text-left ${
                      isActive ? 'border-slate-800 bg-slate-50 shadow-lg' : 'border-slate-200 hover:border-slate-400'
                    }`}
                  >
                    <div className="flex gap-1.5 mb-3">
                      {scheme.preview.map((c, ci) => (
                        <div
                          key={ci}
                          className={`h-5 rounded-full shadow-sm border border-slate-100 ${ci === 2 ? 'flex-1' : 'w-5'}`}
                          style={{ backgroundColor: c }}
                        />
                      ))}
                    </div>
                    <p className="text-xs font-black text-slate-700">{scheme.label}</p>
                    {isActive && <div className="absolute top-2 right-2 w-5 h-5 bg-slate-800 rounded-full flex items-center justify-center"><Check size={10} className="text-white" /></div>}
                  </button>
                );
              })}
            </div>
          </div>
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <div className="flex justify-between items-center mb-6 border-b pb-4">
              <h3 className="text-xl font-black uppercase tracking-tight text-slate-800 dark:text-white">Hero Slider Covers (Max 4)</h3>
              <button
                onClick={() => {
                  const currentSliders = config.theme01?.heroSliders || [];
                  if (currentSliders.length >= 4) { alert('Maximum 4 sliders allowed.'); return; }
                  setConfig({ ...config, theme01: { ...config.theme01, heroSliders: [...currentSliders, { image: '' }] } });
                }}
                className="bg-purple-100 text-[#634C9F] hover:bg-purple-200 px-4 py-2 rounded-xl font-bold flex items-center gap-2 text-xs uppercase"
              >
                <Plus size={16} /> Add Slider
              </button>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {(config.theme01?.heroSliders || []).map((slider, index) => (
                <div key={index} className="bg-slate-50 rounded-2xl p-4 border border-slate-100 space-y-4 relative">
                  <button
                    onClick={() => {
                      const nu = [...(config.theme01?.heroSliders || [])];
                      nu.splice(index, 1);
                      setConfig({ ...config, theme01: { ...config.theme01, heroSliders: nu } });
                    }}
                    className="absolute top-2 right-2 p-1.5 bg-white border rounded-full text-red-500 hover:bg-red-50 z-10 shadow-sm"
                  >
                    <X size={14} />
                  </button>
                  {slider.image ? (
                    <div className="relative h-40 w-full rounded-xl overflow-hidden shadow-sm">
                      <img src={slider.image} className="w-full h-full object-cover" />
                      <label className="absolute bottom-2 right-2 bg-white/90 backdrop-blur px-3 py-1.5 rounded-lg text-xs font-bold cursor-pointer hover:bg-white shadow-sm flex items-center gap-1">
                        {uploadingField === `t1hero-${index}` ? <RefreshCw className="animate-spin text-themePrimary" size={12} /> : <ImageIcon size={12} />} Change
                        <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                          const nu = [...(config.theme01?.heroSliders || [])]; nu[index].image = url; setConfig({ ...config, theme01: { ...config.theme01, heroSliders: nu } });
                        }, `t1hero-${index}`)} />
                      </label>
                    </div>
                  ) : (
                    <label className="flex items-center justify-center gap-2 w-full bg-slate-200 hover:bg-slate-300 h-40 rounded-xl font-bold text-sm cursor-pointer transition-colors text-slate-500">
                      {uploadingField === `t1hero-${index}` ? <RefreshCw className="animate-spin" size={20} /> : <Upload size={20} />} Upload Cover Image
                      <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                        const nu = [...(config.theme01?.heroSliders || [])]; nu[index].image = url; setConfig({ ...config, theme01: { ...config.theme01, heroSliders: nu } });
                      }, `t1hero-${index}`)} />
                    </label>
                  )}
                </div>
              ))}
              {(config.theme01?.heroSliders?.length || 0) === 0 && (
                <div className="col-span-full py-8 text-center bg-slate-50 rounded-2xl border border-dashed border-slate-300">
                  <p className="text-sm font-bold text-slate-500 mb-2">No hero sliders added</p>
                  <p className="text-xs text-slate-400">Add cover images to display a sliding banner on the home page.</p>
                </div>
              )}
            </div>
          </div>
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-6 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">Large Promo Banner</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
               <div className="space-y-4">
                  <div>
                    <label className="block text-xs font-bold text-slate-500 mb-1">Title</label>
                    <input type="text" value={config.theme01?.largePromoBanner?.title || 'Make your grocery shopping easy with us'} onChange={(e) => setConfig({ ...config, theme01: { ...config.theme01, largePromoBanner: { ...(config.theme01?.largePromoBanner || {}), title: e.target.value } as any } })} className="w-full border border-slate-200 px-3 py-2 rounded-xl text-sm font-bold text-slate-800 dark:bg-slate-800" />
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-slate-500 mb-1">Subtitle</label>
                    <textarea value={config.theme01?.largePromoBanner?.subtitle || 'Get fresh groceries delivered to your doorstep. Shop now and save big!'} onChange={(e) => setConfig({ ...config, theme01: { ...config.theme01, largePromoBanner: { ...(config.theme01?.largePromoBanner || {}), subtitle: e.target.value } as any } })} className="w-full border border-slate-200 px-3 py-2 rounded-xl text-sm font-bold text-slate-800 dark:bg-slate-800 resize-none h-20" />
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-bold text-slate-500 mb-1">Button Text</label>
                      <input type="text" value={config.theme01?.largePromoBanner?.buttonText || 'Shop Now →'} onChange={(e) => setConfig({ ...config, theme01: { ...config.theme01, largePromoBanner: { ...(config.theme01?.largePromoBanner || {}), buttonText: e.target.value } as any } })} className="w-full border border-slate-200 px-3 py-2 rounded-xl text-sm font-bold text-slate-800 dark:bg-slate-800" />
                    </div>
                    <div>
                      <label className="block text-xs font-bold text-slate-500 mb-1">Background Color</label>
                      <input type="color" value={config.theme01?.largePromoBanner?.bg || '#FFF8E7'} onChange={(e) => setConfig({ ...config, theme01: { ...config.theme01, largePromoBanner: { ...(config.theme01?.largePromoBanner || {}), bg: e.target.value } as any } })} className="w-full h-[42px] p-1 border border-slate-200 rounded-xl cursor-pointer bg-white" />
                    </div>
                  </div>
               </div>
               <div>
                  <label className="block text-xs font-bold text-slate-500 mb-1">Banner Image (Transparent PNG)</label>
                  {config.theme01?.largePromoBanner?.image ? (
                    <div className="relative h-48 w-full rounded-2xl overflow-hidden shadow-sm bg-slate-100 flex items-center justify-center border border-slate-200">
                      <img src={config.theme01.largePromoBanner.image} className="h-full object-contain mix-blend-multiply" />
                      <label className="absolute bottom-2 right-2 bg-white/90 backdrop-blur px-3 py-1.5 rounded-lg text-xs font-bold cursor-pointer hover:bg-white shadow-sm flex items-center gap-1">
                        {uploadingField === 't1-largePromo' ? <RefreshCw className="animate-spin text-themePrimary" size={12} /> : <ImageIcon size={12} />} Change
                        <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                          setConfig({ ...config, theme01: { ...config.theme01, largePromoBanner: { ...(config.theme01?.largePromoBanner || {}), image: url } as any } });
                        }, 't1-largePromo')} />
                      </label>
                    </div>
                  ) : (
                    <label className="flex flex-col items-center justify-center gap-2 w-full bg-slate-50 hover:bg-slate-100 border-2 border-dashed border-slate-200 h-48 rounded-2xl font-bold text-sm cursor-pointer transition-colors text-slate-500">
                      {uploadingField === 't1-largePromo' ? <RefreshCw className="animate-spin" size={24} /> : <Upload size={24} className="text-slate-400" />} 
                      <span>Upload Banner Image</span>
                      <span className="text-[10px] text-slate-400 font-normal">Suggested size: 400x300</span>
                      <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                        setConfig({ ...config, theme01: { ...config.theme01, largePromoBanner: { ...(config.theme01?.largePromoBanner || {}), image: url } as any } });
                      }, 't1-largePromo')} />
                    </label>
                  )}
               </div>
            </div>
          </div>
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-6 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">Promotional Banners (3 Columns)</h3>
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              {config.theme01?.promoRow1?.map((banner, index) => (
                <div key={index} className="bg-slate-50 rounded-2xl p-4 border border-slate-100 space-y-4 relative overflow-hidden group">
                  <div className="absolute inset-0 bg-black/10 z-0">
                    <img src={banner.image} className="w-full h-full object-cover opacity-30" />
                  </div>
                  <div className="relative z-10 space-y-3 bg-white/90 p-4 rounded-xl backdrop-blur-sm">
                    <div>
                      <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Discount Tag</label>
                      <input type="text" value={banner.discount} onChange={(e) => {
                        const nu = [...(config.theme01?.promoRow1 || [])]; nu[index].discount = e.target.value; setConfig({ ...config, theme01: { ...config.theme01, promoRow1: nu } });
                      }} className="w-full border-b bg-transparent px-1 py-1 text-xs font-bold outline-none" />
                    </div>
                    <div>
                      <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Title</label>
                      <input type="text" value={banner.title} onChange={(e) => {
                        const nu = [...(config.theme01?.promoRow1 || [])]; nu[index].title = e.target.value; setConfig({ ...config, theme01: { ...config.theme01, promoRow1: nu } });
                      }} className="w-full border-b bg-transparent px-1 py-1 text-sm font-black outline-none" />
                    </div>
                    <div>
                      <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Subtitle</label>
                      <input type="text" value={banner.subtitle} onChange={(e) => {
                        const nu = [...(config.theme01?.promoRow1 || [])]; nu[index].subtitle = e.target.value; setConfig({ ...config, theme01: { ...config.theme01, promoRow1: nu } });
                      }} className="w-full border-b bg-transparent px-1 py-1 text-xs text-slate-600 outline-none" />
                    </div>
                    <label className="flex items-center justify-center gap-1 w-full bg-slate-200 hover:bg-slate-300 py-2 rounded font-bold text-[10px] cursor-pointer transition-colors mt-2">
                      {uploadingField === `t1p1-${index}` ? <RefreshCw className="animate-spin text-red-600" size={12} /> : <ImageIcon size={12} />}
                      Image
                      <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                        const nu = [...(config.theme01?.promoRow1 || [])]; nu[index].image = url; setConfig({ ...config, theme01: { ...config.theme01, promoRow1: nu } });
                      }, `t1p1-${index}`)} />
                    </label>
                  </div>
                </div>
              ))}
            </div>
          </div>
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-6 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">Grid Banners (4 Columns)</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              {config.theme01?.promoRow2?.map((banner, index) => (
                <div key={index} className="bg-slate-50 rounded-2xl p-4 border border-slate-100 space-y-4">
                  <div>
                    <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Title</label>
                    <input type="text" value={banner.title} onChange={(e) => {
                      const nu = [...(config.theme01?.promoRow2 || [])]; nu[index].title = e.target.value; setConfig({ ...config, theme01: { ...config.theme01, promoRow2: nu } });
                    }} className="w-full border-b bg-transparent px-1 py-1 text-sm font-black outline-none" />
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Subtitle</label>
                    <input type="text" value={banner.subtitle} onChange={(e) => {
                      const nu = [...(config.theme01?.promoRow2 || [])]; nu[index].subtitle = e.target.value; setConfig({ ...config, theme01: { ...config.theme01, promoRow2: nu } });
                    }} className="w-full border-b bg-transparent px-1 py-1 text-xs text-slate-600 outline-none" />
                  </div>
                </div>
              ))}
            </div>
          </div>
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm mt-8">
            <div className="flex justify-between items-center mb-6 border-b pb-4">
              <h3 className="text-xl font-black uppercase tracking-tight text-slate-800 dark:text-white">Blog Section Editor</h3>
              <button
                onClick={() => {
                  const newPost = { id: Date.now(), title: '', excerpt: '', image: '', date: new Date().toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }), author: 'Admin' };
                  const currentPosts = config.theme01?.blogPosts || [];
                  setConfig({ ...config, theme01: { ...config.theme01, blogPosts: [...currentPosts, newPost] } });
                }}
                className="bg-green-100 text-green-700 hover:bg-green-200 px-4 py-2 rounded-xl font-bold flex items-center gap-2 text-xs uppercase"
              >
                <Plus size={16} /> Add Blog Post
              </button>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {(config.theme01?.blogPosts || []).map((post, index) => (
                <div key={index} className="bg-slate-50 rounded-2xl p-4 border border-slate-100 space-y-4 relative">
                  <button
                    onClick={() => {
                      const newPosts = [...(config.theme01?.blogPosts || [])];
                      newPosts.splice(index, 1);
                      setConfig({ ...config, theme01: { ...config.theme01, blogPosts: newPosts } });
                    }}
                    className="absolute top-2 right-2 p-1.5 bg-white border rounded-full text-red-500 hover:bg-red-50"
                  >
                    <X size={14} />
                  </button>

                  {post.image ? (
                    <div className="relative h-32 w-full rounded-xl overflow-hidden">
                      <img src={post.image} className="w-full h-full object-cover" />
                      <label className="absolute bottom-2 right-2 bg-white/90 backdrop-blur px-3 py-1.5 rounded-lg text-xs font-bold cursor-pointer hover:bg-white shadow-sm flex items-center gap-1">
                        {uploadingField === `t1blog-${index}` ? <RefreshCw className="animate-spin text-themePrimary" size={12} /> : <ImageIcon size={12} />} Change
                        <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                          const nu = [...(config.theme01?.blogPosts || [])]; nu[index].image = url; setConfig({ ...config, theme01: { ...config.theme01, blogPosts: nu } });
                        }, `t1blog-${index}`)} />
                      </label>
                    </div>
                  ) : (
                    <label className="flex items-center justify-center gap-1 w-full bg-slate-200 hover:bg-slate-300 h-32 rounded-xl font-bold text-xs cursor-pointer transition-colors text-slate-500">
                      {uploadingField === `t1blog-${index}` ? <RefreshCw className="animate-spin" size={16} /> : <Upload size={16} />} Upload Cover
                      <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                        const nu = [...(config.theme01?.blogPosts || [])]; nu[index].image = url; setConfig({ ...config, theme01: { ...config.theme01, blogPosts: nu } });
                      }, `t1blog-${index}`)} />
                    </label>
                  )}

                  <div>
                    <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Title</label>
                    <input type="text" value={post.title} onChange={(e) => {
                      const nu = [...(config.theme01?.blogPosts || [])]; nu[index].title = e.target.value; setConfig({ ...config, theme01: { ...config.theme01, blogPosts: nu } });
                    }} className="w-full border-b bg-transparent px-1 py-1 text-sm font-black outline-none focus:border-themePrimary" placeholder="Post title..." />
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Excerpt</label>
                    <textarea rows={2} value={post.excerpt} onChange={(e) => {
                      const nu = [...(config.theme01?.blogPosts || [])]; nu[index].excerpt = e.target.value; setConfig({ ...config, theme01: { ...config.theme01, blogPosts: nu } });
                    }} className="w-full border bg-white rounded-lg px-2 py-1 text-xs text-slate-600 outline-none focus:border-themePrimary" placeholder="Short description..." />
                  </div>
                  <div className="flex gap-2">
                    <div className="flex-1">
                      <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Author</label>
                      <input type="text" value={post.author} onChange={(e) => {
                        const nu = [...(config.theme01?.blogPosts || [])]; nu[index].author = e.target.value; setConfig({ ...config, theme01: { ...config.theme01, blogPosts: nu } });
                      }} className="w-full border-b bg-transparent px-1 py-1 text-xs outline-none focus:border-themePrimary" />
                    </div>
                    <div className="flex-1">
                      <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Date</label>
                      <input type="text" value={post.date} onChange={(e) => {
                        const nu = [...(config.theme01?.blogPosts || [])]; nu[index].date = e.target.value; setConfig({ ...config, theme01: { ...config.theme01, blogPosts: nu } });
                      }} className="w-full border-b bg-transparent px-1 py-1 text-xs outline-none focus:border-themePrimary" />
                    </div>
                  </div>
                </div>
              ))}
              {(config.theme01?.blogPosts?.length || 0) === 0 && (
                <div className="col-span-full py-8 text-center bg-slate-50 rounded-2xl border border-dashed border-slate-300">
                  <p className="text-sm font-bold text-slate-500 mb-2">No blog posts available</p>
                  <p className="text-xs text-slate-400">Add posts to display them on your Blog Page.</p>
                </div>
              )}
            </div>
          </div>

                              <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm mt-8">
            <div className="flex justify-between items-center mb-6 border-b pb-4">
              <h3 className="text-xl font-black uppercase tracking-tight text-slate-800 dark:text-white">Trending Page Covers (Max 6)</h3>
              <button
                onClick={() => {
                  const currentSliders = config.theme01?.trendingBanners || [];
                  if (currentSliders.length >= 6) { alert('Maximum 6 covers allowed.'); return; }
                  setConfig({ ...config, theme01: { ...config.theme01, trendingBanners: [...currentSliders, { image: '' }] } });
                }}
                className="bg-indigo-100 text-indigo-700 hover:bg-indigo-200 px-4 py-2 rounded-xl font-bold flex items-center gap-2 text-xs uppercase"
              >
                <Plus size={16} /> Add Cover
              </button>
            </div>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-6">
              {(config.theme01?.trendingBanners || []).map((slider, index) => (
                <div key={index} className="bg-slate-50 rounded-2xl p-4 border border-slate-100 space-y-4 relative">
                  <button
                    onClick={() => {
                      const nu = [...(config.theme01?.trendingBanners || [])];
                      nu.splice(index, 1);
                      setConfig({ ...config, theme01: { ...config.theme01, trendingBanners: nu } });
                    }}
                    className="absolute top-2 right-2 p-1.5 bg-white border rounded-full text-red-500 hover:bg-red-50 z-10 shadow-sm"
                  >
                    <X size={14} />
                  </button>
                  {slider.image ? (
                     <div className="relative h-28 w-full rounded-xl overflow-hidden shadow-sm">
                       <img src={slider.image} className="w-full h-full object-cover" />
                       <label className="absolute bottom-2 right-2 bg-white/90 backdrop-blur px-3 py-1.5 rounded-lg text-xs font-bold cursor-pointer hover:bg-white shadow-sm flex items-center gap-1">
                         {uploadingField === `t1trend-${index}` ? <RefreshCw className="animate-spin text-[#634C9F]" size={12} /> : <ImageIcon size={12} />} Change
                         <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                           const nu = [...(config.theme01?.trendingBanners || [])]; nu[index].image = url; setConfig({ ...config, theme01: { ...config.theme01, trendingBanners: nu } });
                         }, `t1trend-${index}`)} />
                       </label>
                     </div>
                  ) : (
                     <label className="flex items-center justify-center gap-2 w-full bg-slate-200 hover:bg-slate-300 h-28 rounded-xl font-bold text-sm cursor-pointer transition-colors text-slate-500">
                       {uploadingField === `t1trend-${index}` ? <RefreshCw className="animate-spin" size={20} /> : <Upload size={20} />} Upload
                       <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                         const nu = [...(config.theme01?.trendingBanners || [])]; nu[index].image = url; setConfig({ ...config, theme01: { ...config.theme01, trendingBanners: nu } });
                       }, `t1trend-${index}`)} />
                     </label>
                  )}
                </div>
              ))}
              {(config.theme01?.trendingBanners?.length || 0) === 0 && (
                <div className="col-span-full py-8 text-center bg-slate-50 rounded-2xl border border-dashed border-slate-300">
                  <p className="text-sm font-bold text-slate-500 mb-2">No trending covers added</p>
                  <p className="text-xs text-slate-400">Add covers up to 6 images to display stunning banners on Trending Products page.</p>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Theme 02 Editor */}
      {config.theme === '02' && (
        <div className="space-y-8">
          {/* Color Scheme Picker */}
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-2 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">🎨 Color Scheme</h3>
            <p className="text-sm text-slate-500 mb-5">Choose a color palette for this homepage theme.</p>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
              {SCHEME_LABELS.map((scheme, idx) => {
                const isActive = config.theme02?.colorScheme === idx;
                return (
                  <button
                    key={idx}
                    onClick={() => setConfig({ ...config, theme02: { ...config.theme02, colorScheme: isActive ? undefined : idx } })}
                    className={`relative p-4 rounded-2xl border-2 transition-all text-left ${
                      isActive ? 'border-slate-800 bg-slate-50 shadow-lg' : 'border-slate-200 hover:border-slate-400'
                    }`}
                  >
                    <div className="flex gap-1.5 mb-3">
                      {scheme.preview.map((c, ci) => (
                        <div
                          key={ci}
                          className={`h-5 rounded-full shadow-sm border border-slate-100 ${ci === 2 ? 'flex-1' : 'w-5'}`}
                          style={{ backgroundColor: c }}
                        />
                      ))}
                    </div>
                    <p className="text-xs font-black text-slate-700">{scheme.label}</p>
                    {isActive && <div className="absolute top-2 right-2 w-5 h-5 bg-slate-800 rounded-full flex items-center justify-center"><Check size={10} className="text-white" /></div>}
                  </button>
                );
              })}
            </div>
          </div>
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <div className="flex justify-between items-center mb-6 border-b pb-4">
              <h3 className="text-xl font-black uppercase tracking-tight text-slate-800 dark:text-white">Hero Slider Covers (Max 4)</h3>
              <button
                onClick={() => {
                  const currentSliders = config.theme02?.heroSliders || [];
                  if (currentSliders.length >= 4) { alert('Maximum 4 sliders allowed.'); return; }
                  setConfig({ ...config, theme02: { ...config.theme02, heroSliders: [...currentSliders, { image: '' }] } });
                }}
                className="bg-purple-100 text-[#634C9F] hover:bg-purple-200 px-4 py-2 rounded-xl font-bold flex items-center gap-2 text-xs uppercase"
              >
                <Plus size={16} /> Add Slider
              </button>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {(config.theme02?.heroSliders || []).map((slider, index) => (
                <div key={index} className="bg-slate-50 rounded-2xl p-4 border border-slate-100 space-y-4 relative">
                  <button
                    onClick={() => {
                      const nu = [...(config.theme02?.heroSliders || [])];
                      nu.splice(index, 1);
                      setConfig({ ...config, theme02: { ...config.theme02, heroSliders: nu } });
                    }}
                    className="absolute top-2 right-2 p-1.5 bg-white border rounded-full text-red-500 hover:bg-red-50 z-10 shadow-sm"
                  >
                    <X size={14} />
                  </button>
                  {slider.image ? (
                    <div className="relative h-40 w-full rounded-xl overflow-hidden shadow-sm">
                      <img src={slider.image} className="w-full h-full object-cover" />
                      <label className="absolute bottom-2 right-2 bg-white/90 backdrop-blur px-3 py-1.5 rounded-lg text-xs font-bold cursor-pointer hover:bg-white shadow-sm flex items-center gap-1">
                        {uploadingField === `t2hero-${index}` ? <RefreshCw className="animate-spin text-themePrimary" size={12} /> : <ImageIcon size={12} />} Change
                        <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                          const nu = [...(config.theme02?.heroSliders || [])]; nu[index].image = url; setConfig({ ...config, theme02: { ...config.theme02, heroSliders: nu } });
                        }, `t2hero-${index}`)} />
                      </label>
                    </div>
                  ) : (
                    <label className="flex items-center justify-center gap-2 w-full bg-slate-200 hover:bg-slate-300 h-40 rounded-xl font-bold text-sm cursor-pointer transition-colors text-slate-500">
                      {uploadingField === `t2hero-${index}` ? <RefreshCw className="animate-spin" size={20} /> : <Upload size={20} />} Upload Cover Image
                      <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                        const nu = [...(config.theme02?.heroSliders || [])]; nu[index].image = url; setConfig({ ...config, theme02: { ...config.theme02, heroSliders: nu } });
                      }, `t2hero-${index}`)} />
                    </label>
                  )}
                </div>
              ))}
              {(config.theme02?.heroSliders?.length || 0) === 0 && (
                <div className="col-span-full py-8 text-center bg-slate-50 rounded-2xl border border-dashed border-slate-300">
                  <p className="text-sm font-bold text-slate-500 mb-2">No hero sliders added</p>
                  <p className="text-xs text-slate-400">Add cover images to display a sliding banner on the home page.</p>
                </div>
              )}
            </div>
          </div>

          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-6 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">Hero Section Text</h3>
            <div className="grid grid-cols-1 gap-6">
              <div>
                <label className="block text-xs font-bold text-slate-500 uppercase mb-2">Tagline</label>
                <input type="text" value={config.theme02?.heroTagline || ''} onChange={(e) => setConfig({ ...config, theme02: { ...config.theme02, heroTagline: e.target.value } })} className="w-full bg-slate-50 border border-slate-200 px-4 py-3 rounded-xl focus:ring-2 focus:ring-[#634C9F] text-slate-900 outline-none" />
              </div>
              <div>
                <label className="block text-xs font-bold text-slate-500 uppercase mb-2">Hero Title</label>
                <input type="text" value={config.theme02?.heroTitle || ''} onChange={(e) => setConfig({ ...config, theme02: { ...config.theme02, heroTitle: e.target.value } })} className="w-full bg-slate-50 border border-slate-200 px-4 py-3 rounded-xl focus:ring-2 focus:ring-[#634C9F] text-slate-900 outline-none font-bold text-lg" />
              </div>
              <div>
                <label className="block text-xs font-bold text-slate-500 uppercase mb-2">Hero Subtitle</label>
                <input type="text" value={config.theme02?.heroSubtitle || ''} onChange={(e) => setConfig({ ...config, theme02: { ...config.theme02, heroSubtitle: e.target.value } })} className="w-full bg-slate-50 border border-slate-200 px-4 py-3 rounded-xl focus:ring-2 focus:ring-[#634C9F] text-slate-900 outline-none" />
              </div>
            </div>
          </div>

          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-6 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">Featured Category Banners</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {/* Banner 1 */}
              <div className="bg-slate-50 rounded-2xl p-4 border border-slate-100 space-y-4">
                <h4 className="font-bold border-b pb-2 text-amber-600">Left Banner (Weekly Special)</h4>
                {config.theme02?.banner1?.image && <img src={config.theme02.banner1.image} className="w-full h-32 object-cover rounded-xl" />}
                <input type="text" value={config.theme02?.banner1?.subtitle || ''} placeholder="Subtitle / Tagline" onChange={(e) => setConfig({ ...config, theme02: { ...config.theme02, banner1: { ...(config.theme02?.banner1 || {} as any), subtitle: e.target.value } } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm" />
                <input type="text" value={config.theme02?.banner1?.title || ''} placeholder="Title" onChange={(e) => setConfig({ ...config, theme02: { ...config.theme02, banner1: { ...(config.theme02?.banner1 || {} as any), title: e.target.value } } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm" />
                <input type="text" value={config.theme02?.banner1?.buttonText || ''} placeholder="Button Text" onChange={(e) => setConfig({ ...config, theme02: { ...config.theme02, banner1: { ...(config.theme02?.banner1 || {} as any), buttonText: e.target.value } } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm" />
                <label className="flex items-center justify-center gap-1 w-full bg-slate-200 text-slate-700 hover:bg-slate-300 py-3 rounded-xl font-bold text-xs cursor-pointer transition-colors mt-2">
                  <ImageIcon size={14} /> Change Background Image
                  <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => setConfig({ ...config, theme02: { ...config.theme02, banner1: { ...(config.theme02?.banner1 || {} as any), image: url } } }), 't2b1')} />
                </label>
              </div>

              {/* Banner 2 */}
              <div className="bg-slate-50 rounded-2xl p-4 border border-slate-100 space-y-4">
                <h4 className="font-bold border-b pb-2 text-emerald-600">Right Banner (Daily Essentials)</h4>
                {config.theme02?.banner2?.image && <img src={config.theme02.banner2.image} className="w-full h-32 object-cover rounded-xl" />}
                <input type="text" value={config.theme02?.banner2?.subtitle || ''} placeholder="Subtitle / Tagline" onChange={(e) => setConfig({ ...config, theme02: { ...config.theme02, banner2: { ...(config.theme02?.banner2 || {} as any), subtitle: e.target.value } } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm" />
                <input type="text" value={config.theme02?.banner2?.title || ''} placeholder="Title" onChange={(e) => setConfig({ ...config, theme02: { ...config.theme02, banner2: { ...(config.theme02?.banner2 || {} as any), title: e.target.value } } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm" />
                <input type="text" value={config.theme02?.banner2?.buttonText || ''} placeholder="Button Text" onChange={(e) => setConfig({ ...config, theme02: { ...config.theme02, banner2: { ...(config.theme02?.banner2 || {} as any), buttonText: e.target.value } } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm" />
                <label className="flex items-center justify-center gap-1 w-full bg-slate-200 text-slate-700 hover:bg-slate-300 py-3 rounded-xl font-bold text-xs cursor-pointer transition-colors mt-2">
                  <ImageIcon size={14} /> Change Background Image
                  <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => setConfig({ ...config, theme02: { ...config.theme02, banner2: { ...(config.theme02?.banner2 || {} as any), image: url } } }), 't2b2')} />
                </label>
              </div>
            </div>
          </div>
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-6 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">Today Deals</h3>
            <p className="text-sm text-slate-500 mb-4">Select the products to be featured in the Today Deals section.</p>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 max-h-[500px] overflow-y-auto pr-2 custom-scrollbar">
              {products.map(product => {
                const isSelected = (config.theme02?.todayDealsProductIds || []).includes(product.id);
                return (
                  <div 
                    key={`td-${product.id}`}
                    onClick={() => {
                      let arr = [...(config.theme02?.todayDealsProductIds || [])];
                      if (isSelected) arr = arr.filter(id => id !== product.id);
                      else arr.push(product.id);
                      setConfig({ ...config, theme02: { ...config.theme02, todayDealsProductIds: arr } });
                    }}
                    className={`p-3 rounded-xl border-2 cursor-pointer transition flex items-center gap-3 ${isSelected ? 'border-amber-500 bg-amber-50' : 'border-slate-200 bg-white hover:border-slate-300'}`}
                  >
                    <div className="w-12 h-12 rounded-lg bg-gray-50 flex items-center justify-center p-1 shrink-0">
                      <img src={product.image} className="w-full h-full object-contain mix-blend-multiply" alt={product.name} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-xs font-bold text-slate-800 line-clamp-2 leading-tight">{product.name}</p>
                      <p className="text-[10px] text-red-600 font-black mt-1">৳{product.price}</p>
                    </div>
                    <div className={`w-5 h-5 rounded-full flex items-center justify-center shrink-0 border ${isSelected ? 'bg-amber-500 border-amber-500 text-white' : 'border-slate-300'}`}>
                      {isSelected && <Check size={12} strokeWidth={3} />}
                    </div>
                  </div>
                );
              })}
              {products.length === 0 && <div className="col-span-full py-8 text-center text-slate-500">No products available.</div>}
            </div>
          </div>

          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-6 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">Best Sellers & Hot Deal</h3>
            <p className="text-sm text-slate-500 mb-4">Select up to 9 products. The first selected product will be highlighted as the Hot Deal.</p>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 max-h-[500px] overflow-y-auto pr-2 custom-scrollbar">
              {products.map(product => {
                const isSelected = (config.theme02?.bestSellerProductIds || []).includes(product.id);
                return (
                  <div 
                    key={`bs-${product.id}`}
                    onClick={() => {
                      let arr = [...(config.theme02?.bestSellerProductIds || [])];
                      if (isSelected) arr = arr.filter(id => id !== product.id);
                      else if (arr.length < 9) arr.push(product.id);
                      else alert('Maximum 9 products allowed for Best Sellers section.');
                      setConfig({ ...config, theme02: { ...config.theme02, bestSellerProductIds: arr } });
                    }}
                    className={`p-3 rounded-xl border-2 cursor-pointer transition flex items-center gap-3 ${isSelected ? 'border-[#634C9F] bg-purple-50' : 'border-slate-200 bg-white hover:border-slate-300'}`}
                  >
                    <div className="w-12 h-12 rounded-lg bg-gray-50 flex items-center justify-center p-1 shrink-0">
                      <img src={product.image} className="w-full h-full object-contain mix-blend-multiply" alt={product.name} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-xs font-bold text-slate-800 line-clamp-2 leading-tight">{product.name}</p>
                      <p className="text-[10px] text-[#D93939] font-black mt-1">৳{product.price}</p>
                    </div>
                    <div className={`w-5 h-5 rounded-full flex items-center justify-center shrink-0 border ${isSelected ? 'bg-[#634C9F] border-[#634C9F] text-white' : 'border-slate-300'}`}>
                      {isSelected && <Check size={12} strokeWidth={3} />}
                    </div>
                  </div>
                );
              })}
              {products.length === 0 && <div className="col-span-full py-8 text-center text-slate-500">No products available.</div>}
            </div>
          </div>

          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <div className="flex justify-between items-center mb-6 border-b pb-4">
              <h3 className="text-xl font-black uppercase tracking-tight text-slate-800 dark:text-white">Our News Editor</h3>
              <button
                onClick={() => {
                  const newPost = { id: Date.now(), title: '', excerpt: '', image: '', category: 'UNCATEGORIZED', date: new Date().toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }), author: 'Admin' };
                  const currentPosts = config.theme02?.blogPosts || [];
                  setConfig({ ...config, theme02: { ...config.theme02, blogPosts: [...currentPosts, newPost] } });
                }}
                className="bg-green-100 text-green-700 hover:bg-green-200 px-4 py-2 rounded-xl font-bold flex items-center gap-2 text-xs uppercase"
              >
                <Plus size={16} /> Add News Article
              </button>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {(config.theme02?.blogPosts || []).map((post, index) => (
                <div key={`t2blog-${index}`} className="bg-slate-50 rounded-2xl p-4 border border-slate-100 space-y-4 relative">
                  <button
                    onClick={() => {
                      const newPosts = [...(config.theme02?.blogPosts || [])];
                      newPosts.splice(index, 1);
                      setConfig({ ...config, theme02: { ...config.theme02, blogPosts: newPosts } });
                    }}
                    className="absolute top-2 right-2 p-1.5 bg-white border rounded-full text-red-500 hover:bg-red-50"
                  >
                    <X size={14} />
                  </button>

                  {post.image ? (
                    <div className="relative h-32 w-full rounded-xl overflow-hidden">
                      <img src={post.image} className="w-full h-full object-cover" />
                      <label className="absolute bottom-2 right-2 bg-white/90 backdrop-blur px-3 py-1.5 rounded-lg text-xs font-bold cursor-pointer hover:bg-white shadow-sm flex items-center gap-1">
                        {uploadingField === `t2blog-${index}` ? <RefreshCw className="animate-spin text-themePrimary" size={12} /> : <ImageIcon size={12} />} Change
                        <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                          const nu = [...(config.theme02?.blogPosts || [])] as any[]; nu[index].image = url; setConfig({ ...config, theme02: { ...config.theme02, blogPosts: nu } });
                        }, `t2blog-${index}`)} />
                      </label>
                    </div>
                  ) : (
                    <label className="flex items-center justify-center gap-1 w-full bg-slate-200 hover:bg-slate-300 h-32 rounded-xl font-bold text-xs cursor-pointer transition-colors text-slate-500">
                      {uploadingField === `t2blog-${index}` ? <RefreshCw className="animate-spin" size={16} /> : <Upload size={16} />} Upload Image
                      <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                        const nu = [...(config.theme02?.blogPosts || [])] as any[]; nu[index].image = url; setConfig({ ...config, theme02: { ...config.theme02, blogPosts: nu } });
                      }, `t2blog-${index}`)} />
                    </label>
                  )}

                  <div>
                    <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Title</label>
                    <input type="text" value={post.title} onChange={(e) => {
                      const nu = [...(config.theme02?.blogPosts || [])] as any[]; nu[index].title = e.target.value; setConfig({ ...config, theme02: { ...config.theme02, blogPosts: nu } });
                    }} className="w-full border-b bg-transparent px-1 py-1 text-sm font-black outline-none focus:border-[#634C9F]" placeholder="Article Title..." />
                  </div>
                  <div>
                    <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Excerpt</label>
                    <textarea rows={2} value={post.excerpt} onChange={(e) => {
                      const nu = [...(config.theme02?.blogPosts || [])] as any[]; nu[index].excerpt = e.target.value; setConfig({ ...config, theme02: { ...config.theme02, blogPosts: nu } });
                    }} className="w-full border bg-white rounded-lg px-2 py-1 text-xs text-slate-600 outline-none focus:border-[#634C9F]" placeholder="Short text showing on card..." />
                  </div>
                  <div className="flex gap-2">
                    <div className="flex-1">
                      <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Category</label>
                      <input type="text" value={post.category || ''} onChange={(e) => {
                        const nu = [...(config.theme02?.blogPosts || [])] as any[]; nu[index].category = e.target.value; setConfig({ ...config, theme02: { ...config.theme02, blogPosts: nu } });
                      }} className="w-full border-b bg-transparent px-1 py-1 text-xs outline-none focus:border-[#634C9F]" placeholder="e.g. RECIPES" />
                    </div>
                    <div className="flex-1">
                      <label className="block text-[10px] font-bold text-slate-500 uppercase mb-1">Date</label>
                      <input type="text" value={post.date} onChange={(e) => {
                        const nu = [...(config.theme02?.blogPosts || [])] as any[]; nu[index].date = e.target.value; setConfig({ ...config, theme02: { ...config.theme02, blogPosts: nu } });
                      }} className="w-full border-b bg-transparent px-1 py-1 text-xs outline-none focus:border-[#634C9F]" />
                    </div>
                  </div>
                </div>
              ))}
              {(config.theme02?.blogPosts?.length || 0) === 0 && (
                <div className="col-span-full py-8 text-center bg-slate-50 rounded-2xl border border-dashed border-slate-300">
                  <p className="text-sm font-bold text-slate-500 mb-2">No news articles added</p>
                  <p className="text-xs text-slate-400">Add an article to show it in the Our News section.</p>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Theme 03 Editor */}
      {config.theme === '03' && (
        <div className="space-y-8">
          {/* Color Scheme Picker */}
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-2 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">🎨 Color Scheme</h3>
            <p className="text-sm text-slate-500 mb-5">Choose a color palette for this homepage theme.</p>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
              {SCHEME_LABELS.map((scheme, idx) => {
                const isActive = config.theme03?.colorScheme === idx;
                return (
                  <button
                    key={idx}
                    onClick={() => setConfig({ ...config, theme03: { ...config.theme03 as any, colorScheme: isActive ? undefined : idx } })}
                    className={`relative p-4 rounded-2xl border-2 transition-all text-left ${
                      isActive ? 'border-slate-800 bg-slate-50 shadow-lg' : 'border-slate-200 hover:border-slate-400'
                    }`}
                  >
                    <div className="flex gap-1.5 mb-3">
                      {scheme.preview.map((c, ci) => (
                        <div
                          key={ci}
                          className={`h-5 rounded-full shadow-sm border border-slate-100 ${ci === 2 ? 'flex-1' : 'w-5'}`}
                          style={{ backgroundColor: c }}
                        />
                      ))}
                    </div>
                    <p className="text-xs font-black text-slate-700">{scheme.label}</p>
                    {isActive && <div className="absolute top-2 right-2 w-5 h-5 bg-slate-800 rounded-full flex items-center justify-center"><Check size={10} className="text-white" /></div>}
                  </button>
                );
              })}
            </div>
          </div>
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <div className="flex justify-between items-center mb-6 border-b pb-4">
              <h3 className="text-xl font-black uppercase tracking-tight text-slate-800 dark:text-white">Hero Slider Covers (Max 4)</h3>
              <button
                onClick={() => {
                  const currentSliders = config.theme03?.heroSliders || [];
                  if (currentSliders.length >= 4) { alert('Maximum 4 sliders allowed.'); return; }
                  setConfig({ ...config, theme03: { ...config.theme03, heroSliders: [...currentSliders, { image: '' }] } });
                }}
                className="bg-pink-100 text-[#E91E63] hover:bg-pink-200 px-4 py-2 rounded-xl font-bold flex items-center gap-2 text-xs uppercase"
              >
                <Plus size={16} /> Add Slider
              </button>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {(config.theme03?.heroSliders || []).map((slider, index) => (
                <div key={index} className="bg-slate-50 rounded-2xl p-4 border border-slate-100 space-y-4 relative">
                  <button
                    onClick={() => {
                      const nu = [...(config.theme03?.heroSliders || [])];
                      nu.splice(index, 1);
                      setConfig({ ...config, theme03: { ...config.theme03, heroSliders: nu } });
                    }}
                    className="absolute top-2 right-2 p-1.5 bg-white border rounded-full text-red-500 hover:bg-red-50 z-10 shadow-sm"
                  >
                    <X size={14} />
                  </button>
                  {slider.image ? (
                    <div className="relative h-40 w-full rounded-xl overflow-hidden shadow-sm">
                      <img src={slider.image} className="w-full h-full object-cover" />
                      <label className="absolute bottom-2 right-2 bg-white/90 backdrop-blur px-3 py-1.5 rounded-lg text-xs font-bold cursor-pointer hover:bg-white shadow-sm flex items-center gap-1">
                        {uploadingField === `t3hero-${index}` ? <RefreshCw className="animate-spin text-[#E91E63]" size={12} /> : <ImageIcon size={12} />} Change
                        <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                          const nu = [...(config.theme03?.heroSliders || [])]; nu[index].image = url; setConfig({ ...config, theme03: { ...config.theme03, heroSliders: nu } });
                        }, `t3hero-${index}`)} />
                      </label>
                    </div>
                  ) : (
                    <label className="flex items-center justify-center gap-2 w-full bg-slate-200 hover:bg-slate-300 h-40 rounded-xl font-bold text-sm cursor-pointer transition-colors text-slate-500">
                      {uploadingField === `t3hero-${index}` ? <RefreshCw className="animate-spin" size={20} /> : <Upload size={20} />} Upload Cover Image
                      <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                        const nu = [...(config.theme03?.heroSliders || [])]; nu[index].image = url; setConfig({ ...config, theme03: { ...config.theme03, heroSliders: nu } });
                      }, `t3hero-${index}`)} />
                    </label>
                  )}
                </div>
              ))}
              {(config.theme03?.heroSliders?.length || 0) === 0 && (
                <div className="col-span-full py-8 text-center bg-slate-50 rounded-2xl border border-dashed border-slate-300">
                  <p className="text-sm font-bold text-slate-500 mb-2">No hero sliders added</p>
                  <p className="text-xs text-slate-400">Add cover images to display your hero slider.</p>
                </div>
              )}
            </div>
          </div>
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-6 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">Mega Deals Grid (8 Blocks)</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              {(config.theme03?.megaDeals || DEFAULT_CONFIG.theme03?.megaDeals || []).map((deal, index) => (
                <div key={index} className="bg-slate-50 rounded-2xl p-4 border border-slate-100 space-y-3 relative overflow-hidden" style={{ backgroundColor: deal.bg }}>
                  <div className="absolute top-0 right-0 p-2">
                    <input type="color" className="w-6 h-6 border-0 p-0 cursor-pointer rounded-full" value={deal.bg} onChange={(e) => {
                      const nu = [...(config.theme03?.megaDeals || DEFAULT_CONFIG.theme03?.megaDeals || [])];
                      nu[index].bg = e.target.value;
                      setConfig({ ...config, theme03: { ...config.theme03, megaDeals: nu } });
                    }} title="Change Background Color" />
                  </div>
                  <div className="flex gap-3">
                    {deal.image ? (
                     <div className="w-16 h-16 shrink-0 relative rounded-lg overflow-hidden border bg-white group">
                       <img src={deal.image} className="w-full h-full object-cover" />
                       <label className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 flex items-center justify-center cursor-pointer text-white">
                         <Upload size={14} />
                         <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                            const nu = [...(config.theme03?.megaDeals || DEFAULT_CONFIG.theme03?.megaDeals || [])];
                            nu[index].image = url;
                            setConfig({ ...config, theme03: { ...config.theme03, megaDeals: nu } });
                         }, `t3mega-${index}`)} />
                       </label>
                     </div>
                    ) : (
                     <label className="w-16 h-16 shrink-0 border-2 border-dashed rounded-lg flex items-center justify-center bg-white cursor-pointer hover:bg-slate-50">
                        {uploadingField === `t3mega-${index}` ? <RefreshCw className="animate-spin text-slate-400" size={16}/> : <ImageIcon className="text-slate-400" size={16}/>}
                        <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                           const nu = [...(config.theme03?.megaDeals || DEFAULT_CONFIG.theme03?.megaDeals || [])];
                           nu[index].image = url;
                           setConfig({ ...config, theme03: { ...config.theme03, megaDeals: nu } });
                        }, `t3mega-${index}`)} />
                     </label>
                    )}
                    <div className="flex-1 space-y-2">
                      <div>
                        <label className="block text-[9px] font-bold text-slate-500 uppercase mb-1">Category Title</label>
                        <input type="text" value={deal.title} onChange={(e) => {
                          const nu = [...(config.theme03?.megaDeals || DEFAULT_CONFIG.theme03?.megaDeals || [])];
                          nu[index].title = e.target.value;
                          setConfig({ ...config, theme03: { ...config.theme03, megaDeals: nu } });
                        }} className="w-full bg-white border border-slate-200 px-2 py-1.5 rounded focus:ring-1 focus:ring-[#E91E63] outline-none text-xs font-bold" />
                      </div>
                      <div>
                        <label className="block text-[9px] font-bold text-slate-500 uppercase mb-1">Discount Text</label>
                        <input type="text" value={deal.subtitle} onChange={(e) => {
                          const nu = [...(config.theme03?.megaDeals || DEFAULT_CONFIG.theme03?.megaDeals || [])];
                          nu[index].subtitle = e.target.value;
                          setConfig({ ...config, theme03: { ...config.theme03, megaDeals: nu } });
                        }} className="w-full bg-white border border-slate-200 px-2 py-1.5 rounded focus:ring-1 focus:ring-[#E91E63] outline-none text-xs" />
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-6 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">Promotional Banners (2 Blocks)</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {config.theme03?.promoBanners?.map((banner, index) => (
                <div key={index} className="bg-slate-50 rounded-2xl p-4 border border-slate-100 space-y-4">
                  {banner.image && <img src={banner.image} className="w-full h-32 object-cover rounded-xl" />}
                  <div>
                    <label className="block text-xs font-bold text-slate-500 uppercase mb-2">Title</label>
                    <input type="text" value={banner.title} onChange={(e) => {
                      const nu = [...(config.theme03?.promoBanners || [])]; nu[index].title = e.target.value; setConfig({ ...config, theme03: { ...config.theme03, promoBanners: nu } });
                    }} className="w-full bg-white border border-slate-200 px-4 py-2 rounded-xl focus:ring-2 focus:ring-pink-500 outline-none" />
                  </div>
                  <label className="flex items-center justify-center gap-1 w-full bg-slate-200 hover:bg-slate-300 py-3 rounded-xl font-bold text-xs cursor-pointer transition-colors mt-2">
                    {uploadingField === `t3p-${index}` ? <RefreshCw className="animate-spin text-pink-600" size={14} /> : <ImageIcon size={14} />} Change Image
                    <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                      const nu = [...(config.theme03?.promoBanners || [])]; nu[index].image = url; setConfig({ ...config, theme03: { ...config.theme03, promoBanners: nu } });
                    }, `t3p-${index}`)} />
                  </label>
                </div>
              ))}
            </div>
          </div>

          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-6 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">Middle Banners (2 Blocks)</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {/* Middle Banner 1 */}
              <div className="bg-slate-50 rounded-2xl p-4 border border-slate-100 space-y-4 relative">
                <h4 className="font-bold border-b pb-2 text-[#E91E63]">Left Banner</h4>
                <div className="absolute top-4 right-4 flex items-center gap-2">
                   <label className="text-xs text-slate-500 font-bold">Bg:</label>
                   <input type="color" className="w-6 h-6 border-0 p-0 cursor-pointer rounded-full" value={config.theme03?.middleBanner1?.bg || '#FCE7F3'} onChange={(e) => {
                      setConfig({ ...config, theme03: { ...config.theme03, middleBanner1: { ...(config.theme03?.middleBanner1 || {} as any), bg: e.target.value } } });
                   }} title="Change Background Color" />
                </div>
                <input type="text" value={config.theme03?.middleBanner1?.tag || ''} placeholder="Tag / Eyebrow text" onChange={(e) => setConfig({ ...config, theme03: { ...config.theme03, middleBanner1: { ...(config.theme03?.middleBanner1 || {} as any), tag: e.target.value } } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm" />
                <input type="text" value={config.theme03?.middleBanner1?.title || ''} placeholder="Title" onChange={(e) => setConfig({ ...config, theme03: { ...config.theme03, middleBanner1: { ...(config.theme03?.middleBanner1 || {} as any), title: e.target.value } } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm" />
                <input type="text" value={config.theme03?.middleBanner1?.subtitle || ''} placeholder="Subtitle" onChange={(e) => setConfig({ ...config, theme03: { ...config.theme03, middleBanner1: { ...(config.theme03?.middleBanner1 || {} as any), subtitle: e.target.value } } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm" />
                <input type="text" value={config.theme03?.middleBanner1?.buttonText || ''} placeholder="Button Text" onChange={(e) => setConfig({ ...config, theme03: { ...config.theme03, middleBanner1: { ...(config.theme03?.middleBanner1 || {} as any), buttonText: e.target.value } } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm" />
              </div>

              {/* Middle Banner 2 */}
              <div className="bg-slate-50 rounded-2xl p-4 border border-slate-100 space-y-4 relative">
                <h4 className="font-bold border-b pb-2 text-blue-600">Right Banner</h4>
                <div className="absolute top-4 right-4 flex items-center gap-2">
                   <label className="text-xs text-slate-500 font-bold">Bg:</label>
                   <input type="color" className="w-6 h-6 border-0 p-0 cursor-pointer rounded-full" value={config.theme03?.middleBanner2?.bg || '#DBEAFE'} onChange={(e) => {
                      setConfig({ ...config, theme03: { ...config.theme03, middleBanner2: { ...(config.theme03?.middleBanner2 || {} as any), bg: e.target.value } } });
                   }} title="Change Background Color" />
                </div>
                {config.theme03?.middleBanner2?.image && <img src={config.theme03.middleBanner2.image} className="w-full h-24 object-cover rounded-xl mt-2" />}
                <input type="text" value={config.theme03?.middleBanner2?.tag || ''} placeholder="Tag / Eyebrow text" onChange={(e) => setConfig({ ...config, theme03: { ...config.theme03, middleBanner2: { ...(config.theme03?.middleBanner2 || {} as any), tag: e.target.value } } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm" />
                <input type="text" value={config.theme03?.middleBanner2?.title || ''} placeholder="Title" onChange={(e) => setConfig({ ...config, theme03: { ...config.theme03, middleBanner2: { ...(config.theme03?.middleBanner2 || {} as any), title: e.target.value } } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm" />
                <input type="text" value={config.theme03?.middleBanner2?.subtitle || ''} placeholder="Subtitle" onChange={(e) => setConfig({ ...config, theme03: { ...config.theme03, middleBanner2: { ...(config.theme03?.middleBanner2 || {} as any), subtitle: e.target.value } } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm" />
                <input type="text" value={config.theme03?.middleBanner2?.buttonText || ''} placeholder="Button Text" onChange={(e) => setConfig({ ...config, theme03: { ...config.theme03, middleBanner2: { ...(config.theme03?.middleBanner2 || {} as any), buttonText: e.target.value } } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm" />
                <label className="flex items-center justify-center gap-1 w-full bg-slate-200 text-slate-700 hover:bg-slate-300 py-3 rounded-xl font-bold text-xs cursor-pointer transition-colors mt-2">
                  {uploadingField === 't3mb2' ? <RefreshCw className="animate-spin text-blue-600" size={14} /> : <ImageIcon size={14} />} Change Side Image
                  <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => setConfig({ ...config, theme03: { ...config.theme03, middleBanner2: { ...(config.theme03?.middleBanner2 || {} as any), image: url } } }), 't3mb2')} />
                </label>
              </div>
            </div>
          </div>
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-6 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">BUY ONE GET ONE Products</h3>
            <p className="text-sm text-slate-500 mb-4">Select the products to be featured in the BUY ONE GET ONE section.</p>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 max-h-[500px] overflow-y-auto pr-2 custom-scrollbar">
              {products.map(product => {
                const isSelected = (config.theme03?.bogoProductIds || []).includes(product.id);
                return (
                  <div 
                    key={`t3bogo-${product.id}`}
                    onClick={() => {
                      let arr = [...(config.theme03?.bogoProductIds || [])];
                      if (isSelected) arr = arr.filter(id => id !== product.id);
                      else arr.push(product.id);
                      setConfig({ ...config, theme03: { ...config.theme03, bogoProductIds: arr } });
                    }}
                    className={`p-3 rounded-xl border-2 cursor-pointer transition flex items-center gap-3 ${isSelected ? 'border-pink-500 bg-pink-50' : 'border-slate-200 bg-white hover:border-slate-300'}`}
                  >
                    <div className="w-12 h-12 rounded-lg bg-gray-50 flex items-center justify-center p-1 shrink-0">
                      <img src={product.image} className="w-full h-full object-contain mix-blend-multiply" alt={product.name} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-xs font-bold text-slate-800 line-clamp-2 leading-tight">{product.name}</p>
                      <p className="text-[10px] text-slate-500 font-medium">৳{product.price}</p>
                    </div>
                    {isSelected && <div className="w-5 h-5 rounded-full bg-pink-500 text-white flex items-center justify-center shrink-0 shadow-sm"><Check size={12} /></div>}
                  </div>
                );
              })}
            </div>
          </div>
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-6 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">Combo Offer Banner & Products</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
              <div className="space-y-4">
                <div>
                  <label className="block text-xs font-bold text-slate-500 uppercase mb-2">Tag Text</label>
                  <input type="text" value={config.theme03?.comboOffer?.tag || 'COMBO OFFER'} onChange={(e) => setConfig({ ...config, theme03: { ...config.theme03, comboOffer: { ...(config.theme03?.comboOffer || {}), tag: e.target.value } } })} className="w-full bg-white border border-slate-200 px-4 py-2 rounded-xl focus:ring-2 focus:ring-pink-500 text-slate-900 outline-none" />
                </div>
                <div>
                  <label className="block text-xs font-bold text-slate-500 uppercase mb-2">Title</label>
                  <input type="text" value={config.theme03?.comboOffer?.title || 'Buy 2 Get 1 Free'} onChange={(e) => setConfig({ ...config, theme03: { ...config.theme03, comboOffer: { ...(config.theme03?.comboOffer || {}), title: e.target.value } } })} className="w-full bg-white border border-slate-200 px-4 py-2 rounded-xl focus:ring-2 focus:ring-pink-500 text-slate-900 outline-none" />
                </div>
                <div>
                  <label className="block text-xs font-bold text-slate-500 uppercase mb-2">Subtitle</label>
                  <input type="text" value={config.theme03?.comboOffer?.subtitle || 'On selected beauty & personal care items'} onChange={(e) => setConfig({ ...config, theme03: { ...config.theme03, comboOffer: { ...(config.theme03?.comboOffer || {}), subtitle: e.target.value } } })} className="w-full bg-white border border-slate-200 px-4 py-2 rounded-xl focus:ring-2 focus:ring-pink-500 text-slate-900 outline-none" />
                </div>
                <div>
                  <label className="block text-xs font-bold text-slate-500 uppercase mb-2">Button Text</label>
                  <input type="text" value={config.theme03?.comboOffer?.buttonText || 'Shop Combos →'} onChange={(e) => setConfig({ ...config, theme03: { ...config.theme03, comboOffer: { ...(config.theme03?.comboOffer || {}), buttonText: e.target.value } } })} className="w-full bg-white border border-slate-200 px-4 py-2 rounded-xl focus:ring-2 focus:ring-pink-500 text-slate-900 outline-none" />
                </div>
                <div>
                  <label className="block text-xs font-bold text-slate-500 uppercase mb-2">Background Color</label>
                  <div className="flex items-center gap-3">
                    <input type="color" value={config.theme03?.comboOffer?.bgColor || '#FFF3E0'} onChange={(e) => setConfig({ ...config, theme03: { ...config.theme03, comboOffer: { ...(config.theme03?.comboOffer || {}), bgColor: e.target.value } } })} className="w-10 h-10 border-0 p-0 cursor-pointer rounded-lg" />
                    <span className="text-sm font-mono text-slate-500">{config.theme03?.comboOffer?.bgColor || '#FFF3E0'}</span>
                  </div>
                </div>
              </div>
              <div className="bg-slate-50 rounded-2xl p-6 border border-slate-100 flex flex-col justify-center">
                <p className="text-sm font-bold text-slate-500 mb-4 uppercase text-center">Live Preview</p>
                <div className="rounded-2xl p-6 flex flex-col items-center justify-center text-center" style={{ backgroundColor: config.theme03?.comboOffer?.bgColor || '#FFF3E0' }}>
                  <span className="text-orange-600 text-xs font-bold tracking-wider">{config.theme03?.comboOffer?.tag || 'COMBO OFFER'}</span>
                  <h3 className="text-xl font-bold text-gray-800 mt-2">{config.theme03?.comboOffer?.title || 'Buy 2 Get 1 Free'}</h3>
                  <p className="text-gray-600 mt-1 text-sm">{config.theme03?.comboOffer?.subtitle || 'On selected beauty & personal care items'}</p>
                  <button className="mt-4 bg-[#E91E63] text-white px-6 py-2 rounded-full font-semibold text-sm">{config.theme03?.comboOffer?.buttonText || 'Shop Combos →'}</button>
                </div>
              </div>
            </div>
            
            <p className="text-sm font-bold text-slate-800 mb-4 border-t pt-6">Select which products should appear under this Combo Offer</p>
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 max-h-[500px] overflow-y-auto pr-2 custom-scrollbar">
              {products.map(product => {
                const isSelected = (config.theme03?.comboOffer?.productIds || []).includes(product.id);
                return (
                  <div 
                    key={`t3combo-${product.id}`}
                    onClick={() => {
                      let arr = [...(config.theme03?.comboOffer?.productIds || [])];
                      if (isSelected) arr = arr.filter(id => id !== product.id);
                      else arr.push(product.id);
                      setConfig({ ...config, theme03: { ...config.theme03, comboOffer: { ...(config.theme03?.comboOffer || {}), productIds: arr } } });
                    }}
                    className={`p-3 rounded-xl border-2 cursor-pointer transition flex items-center gap-3 ${isSelected ? 'border-orange-500 bg-orange-50' : 'border-slate-200 bg-white hover:border-slate-300'}`}
                  >
                    <div className="w-12 h-12 rounded-lg bg-gray-50 flex items-center justify-center p-1 shrink-0">
                      <img src={product.image} className="w-full h-full object-contain mix-blend-multiply" alt={product.name} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-xs font-bold text-slate-800 line-clamp-2 leading-tight">{product.name}</p>
                      <p className="text-[10px] text-slate-500 font-medium">৳{product.price}</p>
                    </div>
                    {isSelected && <div className="w-5 h-5 rounded-full bg-orange-500 text-white flex items-center justify-center shrink-0 shadow-sm"><Check size={12} /></div>}
                  </div>
                );
              })}
            </div>
          </div>

          {/* Brands Editor */}
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <div className="flex justify-between items-center mb-6 border-b pb-4">
              <h3 className="text-xl font-black uppercase tracking-tight text-slate-800 dark:text-white">Brands Section</h3>
              <button 
                onClick={() => {
                  const nu = [...(config.theme03?.brands || [])];
                  nu.push({ id: Date.now().toString(), name: 'New Brand', logo: '' });
                  setConfig({ ...config, theme03: { ...config.theme03, brands: nu } });
                }}
                className="flex items-center gap-2 bg-[#E91E63] text-white px-4 py-2 rounded-lg text-sm font-bold hover:bg-[#C2185B] transition-colors"
               >
                <Plus size={16} /> Add Brand
              </button>
            </div>
            {(config.theme03?.brands?.length || 0) === 0 ? (
              <p className="text-slate-500 text-sm italic">No brands added yet. Click "Add Brand" to start.</p>
            ) : (
              <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
                {config.theme03?.brands?.map((brand, index) => (
                  <div key={brand.id || index} className="bg-slate-50 p-4 rounded-2xl border border-slate-100 flex flex-col items-center relative group">
                    <button 
                      onClick={() => {
                        const nu = config.theme03!.brands!.filter((_, i) => i !== index);
                        setConfig({ ...config, theme03: { ...config.theme03, brands: nu } });
                      }}
                      className="absolute -top-2 -right-2 bg-red-500 text-white p-1 rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
                    >
                      <X size={14} />
                    </button>
                    {brand.logo ? (
                      <div className="w-20 h-20 mb-3 bg-white rounded-xl shadow-sm overflow-hidden flex items-center justify-center p-2 group-hover:ring-2 ring-[#E91E63] transition-all relative">
                        <img src={brand.logo} className="w-full h-full object-contain mix-blend-multiply" />
                        <label className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 flex items-center justify-center cursor-pointer text-white">
                          <Upload size={14} />
                          <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                             const nu = [...config.theme03!.brands!]; nu[index].logo = url; setConfig({ ...config, theme03: { ...config.theme03, brands: nu } });
                          }, `t3brand-${index}`)} />
                        </label>
                      </div>
                    ) : (
                      <label className="w-20 h-20 mb-3 bg-white border-2 border-dashed border-slate-300 hover:border-[#E91E63] rounded-xl flex items-center justify-center cursor-pointer transition-colors text-slate-400 hover:text-[#E91E63]">
                        {uploadingField === `t3brand-${index}` ? <RefreshCw className="animate-spin" size={16}/> : <Plus size={20}/>}
                        <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                             const nu = [...(config.theme03?.brands || [])]; nu[index].logo = url; setConfig({ ...config, theme03: { ...config.theme03, brands: nu } });
                        }, `t3brand-${index}`)} />
                      </label>
                    )}
                    <input 
                      type="text" 
                      value={brand.name} 
                      onChange={(e) => {
                         const nu = [...config.theme03!.brands!]; nu[index].name = e.target.value; setConfig({ ...config, theme03: { ...config.theme03, brands: nu } });
                      }} 
                      placeholder="Brand Name"
                      className="w-full text-center text-xs font-bold bg-transparent border-b border-transparent hover:border-slate-300 focus:border-[#E91E63] focus:outline-none px-1"
                    />
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Blogs Editor */}
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <div className="flex justify-between items-center mb-6 border-b pb-4">
              <h3 className="text-xl font-black uppercase tracking-tight text-slate-800 dark:text-white">Blog Section</h3>
              <button 
                onClick={() => {
                  const nu = [...(config.theme03?.blogs || [])];
                  nu.push({ id: Date.now().toString(), title: '', excerpt: '', date: new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }), image: '' });
                  setConfig({ ...config, theme03: { ...config.theme03, blogs: nu } });
                }}
                className="flex items-center gap-2 bg-[#E91E63] text-white px-4 py-2 rounded-lg text-sm font-bold hover:bg-[#C2185B] transition-colors"
               >
                <Plus size={16} /> Add Blog
              </button>
            </div>
            {(config.theme03?.blogs?.length || 0) === 0 ? (
              <p className="text-slate-500 text-sm italic">No blog posts added yet. Click "Add Blog" to start.</p>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {config.theme03?.blogs?.map((blog, index) => (
                  <div key={blog.id || index} className="bg-slate-50 rounded-2xl overflow-hidden border border-slate-100 flex flex-col relative group shadow-sm hover:shadow-md transition-shadow delay-75">
                    <button 
                      onClick={() => {
                        const nu = config.theme03!.blogs!.filter((_, i) => i !== index);
                        setConfig({ ...config, theme03: { ...config.theme03, blogs: nu } });
                      }}
                      className="absolute top-2 right-2 z-10 bg-red-500 text-white p-1.5 rounded-full opacity-0 group-hover:opacity-100 transition-opacity shadow-sm hover:scale-110"
                    >
                      <X size={14} />
                    </button>
                    {blog.image ? (
                      <div className="relative aspect-[4/3] w-full">
                        <img src={blog.image} className="w-full h-full object-cover" />
                        <label className="absolute bottom-2 right-2 bg-white/90 backdrop-blur px-3 py-1.5 rounded-lg text-xs font-bold cursor-pointer hover:bg-white shadow-sm flex items-center gap-1">
                          {uploadingField === `t3blog-${index}` ? <RefreshCw className="animate-spin text-[#E91E63]" size={12}/> : <ImageIcon size={12}/>} Change
                          <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                             const nu = [...config.theme03!.blogs!]; nu[index].image = url; setConfig({ ...config, theme03: { ...config.theme03, blogs: nu } });
                          }, `t3blog-${index}`)} />
                        </label>
                      </div>
                    ) : (
                      <label className="aspect-[4/3] w-full bg-slate-200 hover:bg-slate-300 flex flex-col items-center justify-center cursor-pointer transition-colors text-slate-500">
                        {uploadingField === `t3blog-${index}` ? <RefreshCw className="animate-spin mb-2" size={24}/> : <Upload className="mb-2" size={24}/>}
                        <span className="text-sm font-bold">Upload Cover</span>
                        <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                             const nu = [...(config.theme03?.blogs || [])]; nu[index].image = url; setConfig({ ...config, theme03: { ...config.theme03, blogs: nu } });
                        }, `t3blog-${index}`)} />
                      </label>
                    )}
                    <div className="p-4 flex-1 flex flex-col space-y-3">
                      <input 
                        type="text" 
                        value={blog.title} 
                        onChange={(e) => {
                           const nu = [...config.theme03!.blogs!]; nu[index].title = e.target.value; setConfig({ ...config, theme03: { ...config.theme03, blogs: nu } });
                        }} 
                        placeholder="Blog Title"
                        className="w-full font-bold text-slate-800 bg-white border border-slate-200 px-3 py-2 rounded-lg focus:ring-1 focus:ring-[#E91E63] outline-none text-sm"
                      />
                      <input 
                        type="text" 
                        value={blog.date} 
                        onChange={(e) => {
                           const nu = [...config.theme03!.blogs!]; nu[index].date = e.target.value; setConfig({ ...config, theme03: { ...config.theme03, blogs: nu } });
                        }} 
                        placeholder="Date (e.g. Oct 12, 2024)"
                        className="w-full text-slate-500 bg-white border border-slate-200 px-3 py-1.5 rounded-lg focus:ring-1 focus:ring-[#E91E63] outline-none text-xs"
                      />
                      <textarea 
                        value={blog.excerpt} 
                        onChange={(e) => {
                           const nu = [...config.theme03!.blogs!]; nu[index].excerpt = e.target.value; setConfig({ ...config, theme03: { ...config.theme03, blogs: nu } });
                        }} 
                        placeholder="Short Excerpt..."
                        rows={2}
                        className="w-full text-slate-600 bg-white border border-slate-200 px-3 py-2 rounded-lg focus:ring-1 focus:ring-[#E91E63] outline-none text-xs resize-none flex-1"
                      />
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      )}

      {/* Theme 04 Editor */}
      {config.theme === '04' && (
        <div className="space-y-8">
          {/* Color Scheme Picker */}
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-2 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">🎨 Color Scheme</h3>
            <p className="text-sm text-slate-500 mb-5">Choose a color palette for this homepage theme.</p>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
              {SCHEME_LABELS.map((scheme, idx) => {
                const isActive = config.theme04?.colorScheme === idx;
                return (
                  <button
                    key={idx}
                    onClick={() => setConfig({ ...config, theme04: { ...config.theme04, colorScheme: isActive ? undefined : idx } })}
                    className={`relative p-4 rounded-2xl border-2 transition-all text-left ${
                      isActive ? 'border-slate-800 bg-slate-50 shadow-lg' : 'border-slate-200 hover:border-slate-400'
                    }`}
                  >
                    <div className="flex gap-1.5 mb-3">
                      {scheme.preview.map((c, ci) => (
                        <div
                          key={ci}
                          className={`h-5 rounded-full shadow-sm border border-slate-100 ${ci === 2 ? 'flex-1' : 'w-5'}`}
                          style={{ backgroundColor: c }}
                        />
                      ))}
                    </div>
                    <p className="text-xs font-black text-slate-700">{scheme.label}</p>
                    {isActive && <div className="absolute top-2 right-2 w-5 h-5 bg-slate-800 rounded-full flex items-center justify-center"><Check size={10} className="text-white" /></div>}
                  </button>
                );
              })}
            </div>
          </div>
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <div className="flex justify-between items-center border-b pb-4 mb-6">
              <h3 className="text-xl font-black uppercase tracking-tight text-slate-800 dark:text-white">Hero Sliders (Max 4)</h3>
              <button
                onClick={() => {
                  const currentSliders = config.theme04?.heroSliders || [];
                  if (currentSliders.length < 4) {
                    setConfig({ ...config, theme04: { ...config.theme04, heroSliders: [...currentSliders, { image: '' }] } });
                  } else {
                    alert('Maximum 4 sliders allowed.');
                  }
                }}
                className="bg-slate-800 text-white px-4 py-2 rounded-xl text-sm font-bold flex items-center gap-2 hover:bg-slate-700 transition"
              >
                + Add Slider
              </button>
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
              {(config.theme04?.heroSliders || []).map((slider, index) => (
                <div key={index} className="bg-slate-50 rounded-2xl p-4 border border-slate-100 space-y-4 relative">
                   <button 
                     onClick={() => {
                        const newSliders = [...(config.theme04?.heroSliders || [])];
                        newSliders.splice(index, 1);
                        setConfig({ ...config, theme04: { ...config.theme04, heroSliders: newSliders } });
                     }}
                     className="absolute top-2 right-2 bg-red-100 text-red-600 p-1.5 rounded-full hover:bg-red-200 transition"
                   >
                     <X size={14} />
                   </button>
                   <h4 className="font-bold border-b pb-2 text-sm text-slate-600">Slider {index + 1}</h4>
                   {slider.image ? (
                     <img src={slider.image} className="w-full h-32 object-cover rounded-xl" />
                   ) : (
                     <div className="w-full h-32 bg-slate-200 rounded-xl flex flex-col items-center justify-center text-slate-400">
                       <ImageIcon size={24} className="mb-2" />
                       <span className="text-xs">No Image</span>
                     </div>
                   )}
                   <label className="flex items-center justify-center gap-1 w-full bg-slate-200 text-slate-700 hover:bg-slate-300 py-3 rounded-xl font-bold text-xs cursor-pointer transition-colors mt-2">
                    {uploadingField === `t4hs-${index}` ? <RefreshCw className="animate-spin text-slate-600" size={14} /> : <ImageIcon size={14} />} {slider.image ? 'Change Image' : 'Upload Image'}
                    <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                      const newSliders = [...(config.theme04?.heroSliders || [])];
                      newSliders[index] = { ...newSliders[index], image: url };
                      setConfig({ ...config, theme04: { ...config.theme04, heroSliders: newSliders } });
                    }, `t4hs-${index}`)} />
                  </label>
                </div>
              ))}
            </div>

            <h3 className="text-xl font-black mb-6 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">Right Sidebar Banner</h3>
            <div className="bg-slate-50 rounded-2xl p-4 border border-slate-100 space-y-4 max-w-sm">
                <h4 className="font-bold border-b pb-2 text-sm text-slate-600">Fixed Side Cover</h4>
                {config.theme04?.rightBanner?.image && <img src={config.theme04.rightBanner.image} className="w-full h-48 object-cover rounded-xl" />}
                <label className="flex items-center justify-center gap-1 w-full bg-slate-200 text-slate-700 hover:bg-slate-300 py-3 rounded-xl font-bold text-xs cursor-pointer transition-colors mt-2">
                  {uploadingField === 't4rb' ? <RefreshCw className="animate-spin text-slate-600" size={14} /> : <ImageIcon size={14} />} Change Side Banner
                  <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => setConfig({ ...config, theme04: { ...config.theme04, rightBanner: { image: url } } }), 't4rb')} />
                </label>
            </div>

            {/* Top Selling Products Selector */}
            <h3 className="text-xl font-black mb-4 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4 mt-6">Top Selling Products</h3>
            <p className="text-sm text-slate-500 mb-4">Select up to 4 products to feature in the "Top Selling Products" section. If none selected, first 4 products are shown.</p>
            {products.length === 0 ? (
              <p className="text-sm text-slate-400 italic">No products found. Add products first.</p>
            ) : (
              <>
                <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
                  {products.map(product => {
                    const selected = (config.theme04?.topSellingProductIds || []).includes(product.id);
                    return (
                      <div
                        key={product.id}
                        onClick={() => {
                          const current = config.theme04?.topSellingProductIds || [];
                          const isSelected = current.includes(product.id);
                          if (!isSelected && current.length >= 4) return;
                          const updated = isSelected
                            ? current.filter((id: string) => id !== product.id)
                            : [...current, product.id];
                          setConfig({ ...config, theme04: { ...config.theme04, topSellingProductIds: updated } });
                        }}
                        className={`relative flex items-center gap-3 p-3 rounded-2xl border-2 cursor-pointer transition-all ${
                          selected
                            ? 'border-[#F37021] bg-orange-50 shadow-md'
                            : 'border-slate-100 bg-white hover:border-slate-300'
                        } ${!selected && (config.theme04?.topSellingProductIds || []).length >= 4 ? 'opacity-40 cursor-not-allowed' : ''}`}
                      >
                        {selected && (
                          <div className="absolute top-2 right-2 w-5 h-5 rounded-full bg-[#F37021] flex items-center justify-center">
                            <Check size={12} className="text-white" />
                          </div>
                        )}
                        <img src={product.image} alt={product.name} className="w-12 h-12 rounded-xl object-cover flex-shrink-0" />
                        <div className="min-w-0">
                          <p className="text-xs font-bold text-slate-800 line-clamp-2 leading-tight">{product.name}</p>
                          <p className="text-xs text-[#F37021] font-bold mt-0.5">৳{product.price}</p>
                        </div>
                      </div>
                    );
                  })}
                </div>
                {(config.theme04?.topSellingProductIds || []).length > 0 && (
                  <button
                    onClick={() => setConfig({ ...config, theme04: { ...config.theme04, topSellingProductIds: [] } })}
                    className="mt-3 text-xs text-red-500 hover:text-red-700 font-bold flex items-center gap-1"
                  >
                    <X size={12} /> Clear Selection ({(config.theme04?.topSellingProductIds || []).length}/4 selected)
                  </button>
                )}
              </>
            )}

            {/* Trusted Brands Manager */}
            <h3 className="text-xl font-black mb-4 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4 mt-6">Our Trusted Brands</h3>
            <p className="text-sm text-slate-500 mb-4">Add brand logos and names for the "Our Trusted Brands" section. If none added, default demo brands are shown.</p>
            <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4 mb-4">
              {(config.theme04?.trustedBrands || []).map((brand: any, index: number) => (
                <div key={index} className="bg-slate-50 rounded-2xl p-4 border border-slate-100 space-y-3 relative">
                  <button
                    onClick={() => {
                      const updated = [...(config.theme04?.trustedBrands || [])];
                      updated.splice(index, 1);
                      setConfig({ ...config, theme04: { ...config.theme04, trustedBrands: updated } });
                    }}
                    className="absolute top-2 right-2 bg-red-100 text-red-500 p-1 rounded-full hover:bg-red-200 transition"
                  >
                    <X size={12} />
                  </button>
                  {brand.logo ? (
                    <img src={brand.logo} alt={brand.name} className="w-full h-16 object-contain rounded-lg bg-white p-2" />
                  ) : (
                    <div className="w-full h-16 bg-slate-200 rounded-lg flex items-center justify-center text-slate-400 text-xs">No Logo</div>
                  )}
                  <input
                    type="text"
                    value={brand.name || ''}
                    placeholder="Brand Name"
                    onChange={(e) => {
                      const updated = [...(config.theme04?.trustedBrands || [])];
                      updated[index] = { ...updated[index], name: e.target.value };
                      setConfig({ ...config, theme04: { ...config.theme04, trustedBrands: updated } });
                    }}
                    className="w-full border border-slate-200 px-2 py-1.5 rounded-lg text-xs font-bold"
                  />
                  <label className="flex items-center justify-center gap-1 w-full bg-slate-200 text-slate-700 hover:bg-slate-300 py-2 rounded-xl font-bold text-xs cursor-pointer transition-colors">
                    {uploadingField === `t4brand-${index}` ? <RefreshCw className="animate-spin" size={12} /> : <ImageIcon size={12} />}
                    {brand.logo ? 'Change Logo' : 'Upload Logo'}
                    <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                      const updated = [...(config.theme04?.trustedBrands || [])];
                      updated[index] = { ...updated[index], logo: url };
                      setConfig({ ...config, theme04: { ...config.theme04, trustedBrands: updated } });
                    }, `t4brand-${index}`)} />
                  </label>
                </div>
              ))}
              <button
                onClick={() => {
                  const updated = [...(config.theme04?.trustedBrands || []), { name: '', logo: '' }];
                  setConfig({ ...config, theme04: { ...config.theme04, trustedBrands: updated } });
                }}
                className="bg-slate-50 rounded-2xl p-4 border-2 border-dashed border-slate-200 flex flex-col items-center justify-center gap-2 text-slate-400 hover:text-slate-600 hover:border-slate-400 transition cursor-pointer h-full min-h-[160px]"
              >
                <Plus size={24} />
                <span className="text-xs font-bold">Add Brand</span>
              </button>
            </div>

            {/* Section Product Selectors */}
            {[
              { label: 'Pure Honey Collection', key: 'honeyCollectionIds' as const, color: '#F59E0B' },
              { label: 'Cooking Essentials', key: 'cookingEssentialsIds' as const, color: '#10B981' },
              { label: 'Premium Dates', key: 'premiumDatesIds' as const, color: '#8B5CF6' },
            ].map(({ label, key, color }) => (
              <div key={key} className="mt-6">
                <h3 className="text-xl font-black mb-2 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-3">
                  {label} — Product Selection
                </h3>
                <p className="text-sm text-slate-500 mb-3">Select products for this slider. If none selected, auto-filled from product list.</p>
                <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-2">
                  {products.map(product => {
                    const selected = ((config.theme04 as any)?.[key] || []).includes(product.id);
                    return (
                      <div
                        key={product.id}
                        onClick={() => {
                          const current: string[] = (config.theme04 as any)?.[key] || [];
                          const isSelected = current.includes(product.id);
                          const updated = isSelected
                            ? current.filter((id: string) => id !== product.id)
                            : [...current, product.id];
                          setConfig({ ...config, theme04: { ...config.theme04, [key]: updated } });
                        }}
                        className={`relative flex items-center gap-2 p-2 rounded-xl border-2 cursor-pointer transition-all ${
                          selected ? 'border-slate-700 bg-slate-50 shadow-sm' : 'border-slate-100 bg-white hover:border-slate-300'
                        }`}
                      >
                        {selected && (
                          <div className="absolute top-1 right-1 w-4 h-4 rounded-full bg-slate-700 flex items-center justify-center">
                            <Check size={10} className="text-white" />
                          </div>
                        )}
                        <img src={product.image} alt={product.name} className="w-10 h-10 rounded-lg object-cover flex-shrink-0" />
                        <div className="min-w-0">
                          <p className="text-[10px] font-bold text-slate-700 line-clamp-2 leading-tight">{product.name}</p>
                          <p className="text-[10px] font-bold text-[#F37021] mt-0.5">৳{product.price}</p>
                        </div>
                      </div>
                    );
                  })}
                </div>
                {((config.theme04 as any)?.[key] || []).length > 0 && (
                  <button
                    onClick={() => setConfig({ ...config, theme04: { ...config.theme04, [key]: [] } })}
                    className="mt-2 text-xs text-red-400 hover:text-red-600 font-bold flex items-center gap-1"
                  >
                    <X size={11} /> Clear ({((config.theme04 as any)?.[key] || []).length} selected)
                  </button>
                )}
              </div>
            ))}

            {/* Customer Testimonials Manager */}
            <h3 className="text-xl font-black mb-4 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4 mt-6">What Our Customers Say</h3>
            <p className="text-sm text-slate-500 mb-4">Add customer reviews for the testimonials section. If none added, default demo reviews are shown.</p>
            <div className="space-y-4 mb-4">
              {(config.theme04?.testimonials || []).map((t: any, index: number) => (
                <div key={index} className="bg-slate-50 rounded-2xl p-5 border border-slate-100 relative">
                  <button
                    onClick={() => {
                      const updated = [...(config.theme04?.testimonials || [])];
                      updated.splice(index, 1);
                      setConfig({ ...config, theme04: { ...config.theme04, testimonials: updated } });
                    }}
                    className="absolute top-3 right-3 bg-red-100 text-red-500 p-1.5 rounded-full hover:bg-red-200 transition"
                  >
                    <X size={14} />
                  </button>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div className="space-y-3">
                      <div className="flex flex-col items-center gap-2">
                        {t.image ? (
                          <img src={t.image} alt={t.name} className="w-20 h-20 rounded-full object-cover border-2 border-[#F37021]/30" />
                        ) : (
                          <div className="w-20 h-20 rounded-full bg-orange-100 flex items-center justify-center text-[#F37021] font-black text-2xl">
                            {t.name?.charAt(0) || '?'}
                          </div>
                        )}
                        <label className="flex items-center gap-1 bg-slate-200 text-slate-700 hover:bg-slate-300 px-3 py-1.5 rounded-xl font-bold text-xs cursor-pointer transition-colors">
                          {uploadingField === `t4test-${index}` ? <RefreshCw className="animate-spin" size={12} /> : <ImageIcon size={12} />}
                          {t.image ? 'Change Photo' : 'Upload Photo'}
                          <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                            const updated = [...(config.theme04?.testimonials || [])];
                            updated[index] = { ...updated[index], image: url };
                            setConfig({ ...config, theme04: { ...config.theme04, testimonials: updated } });
                          }, `t4test-${index}`)} />
                        </label>
                      </div>
                    </div>
                    <div className="md:col-span-2 space-y-3">
                      <div className="grid grid-cols-2 gap-3">
                        <input
                          type="text"
                          value={t.name || ''}
                          placeholder="Customer Name"
                          onChange={(e) => {
                            const updated = [...(config.theme04?.testimonials || [])];
                            updated[index] = { ...updated[index], name: e.target.value };
                            setConfig({ ...config, theme04: { ...config.theme04, testimonials: updated } });
                          }}
                          className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm font-bold"
                        />
                        <input
                          type="text"
                          value={t.profession || ''}
                          placeholder="Profession (e.g. Housewife)"
                          onChange={(e) => {
                            const updated = [...(config.theme04?.testimonials || [])];
                            updated[index] = { ...updated[index], profession: e.target.value };
                            setConfig({ ...config, theme04: { ...config.theme04, testimonials: updated } });
                          }}
                          className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm"
                        />
                      </div>
                      <div className="flex items-center gap-2">
                        <span className="text-xs font-bold text-slate-500">Rating:</span>
                        {[1,2,3,4,5].map(star => (
                          <button
                            key={star}
                            onClick={() => {
                              const updated = [...(config.theme04?.testimonials || [])];
                              updated[index] = { ...updated[index], rating: star };
                              setConfig({ ...config, theme04: { ...config.theme04, testimonials: updated } });
                            }}
                            className={`text-lg transition ${(t.rating || 5) >= star ? 'text-amber-400' : 'text-slate-300'}`}
                          >
                            ★
                          </button>
                        ))}
                        <span className="text-xs text-slate-400 ml-1">{t.rating || 5}/5</span>
                      </div>
                      <textarea
                        value={t.text || ''}
                        placeholder="Customer review text..."
                        rows={3}
                        onChange={(e) => {
                          const updated = [...(config.theme04?.testimonials || [])];
                          updated[index] = { ...updated[index], text: e.target.value };
                          setConfig({ ...config, theme04: { ...config.theme04, testimonials: updated } });
                        }}
                        className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm resize-none"
                      />
                    </div>
                  </div>
                </div>
              ))}
            </div>
            <button
              onClick={() => {
                const newTestimonial = { name: '', profession: '', image: '', text: '', rating: 5 };
                const updated = [...(config.theme04?.testimonials || []), newTestimonial];
                setConfig({ ...config, theme04: { ...config.theme04, testimonials: updated } });
              }}
              className="w-full py-4 border-2 border-dashed border-slate-200 rounded-2xl text-slate-400 hover:text-slate-600 hover:border-slate-400 transition font-bold flex items-center justify-center gap-2"
            >
              <Plus size={18} /> Add Customer Review
            </button>
          </div>
        </div>
      )}

      {/* Theme 05 Editor */}
      {config.theme === '05' && (
        <div className="space-y-8">
          {/* Color Scheme Picker */}
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-2 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">🎨 Color Scheme</h3>
            <p className="text-sm text-slate-500 mb-5">Choose a color palette for this homepage theme.</p>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
              {SCHEME_LABELS.map((scheme, idx) => {
                const isActive = config.theme05?.colorScheme === idx;
                return (
                  <button
                    key={idx}
                    onClick={() => setConfig({ ...config, theme05: { ...config.theme05, colorScheme: isActive ? undefined : idx } })}
                    className={`relative p-4 rounded-2xl border-2 transition-all text-left ${
                      isActive ? 'border-slate-800 bg-slate-50 shadow-lg' : 'border-slate-200 hover:border-slate-400'
                    }`}
                  >
                    <div className="flex gap-1.5 mb-3">
                      {scheme.preview.map((c, ci) => (
                        <div
                          key={ci}
                          className={`h-5 rounded-full shadow-sm border border-slate-100 ${ci === 2 ? 'flex-1' : 'w-5'}`}
                          style={{ backgroundColor: c }}
                        />
                      ))}
                    </div>
                    <p className="text-xs font-black text-slate-700">{scheme.label}</p>
                    {isActive && <div className="absolute top-2 right-2 w-5 h-5 bg-slate-800 rounded-full flex items-center justify-center"><Check size={10} className="text-white" /></div>}
                  </button>
                );
              })}
            </div>
          </div>
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-6 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">Hero Section</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-4">
                <input type="text" value={config.theme05?.heroTagline || ''} placeholder="Tagline (e.g. Summer Collection)" onChange={(e) => setConfig({ ...config, theme05: { ...config.theme05, heroTagline: e.target.value } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm" />
                <input type="text" value={config.theme05?.heroTitle || ''} placeholder="Hero Title" onChange={(e) => setConfig({ ...config, theme05: { ...config.theme05, heroTitle: e.target.value } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm font-bold" />
                <textarea value={config.theme05?.heroSubtitle || ''} placeholder="Hero Subtitle" onChange={(e) => setConfig({ ...config, theme05: { ...config.theme05, heroSubtitle: e.target.value } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm" rows={3} />
              </div>
              <div className="space-y-4">
                {config.theme05?.heroImage && <img src={config.theme05.heroImage} className="w-full h-32 object-cover rounded-xl" />}
                <label className="flex items-center justify-center gap-1 w-full bg-slate-900 text-white hover:bg-slate-800 py-3 rounded-xl font-bold text-sm cursor-pointer transition-colors mt-2">
                  <Upload size={16} /> Upload Hero Image
                  <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => setConfig({ ...config, theme05: { ...config.theme05, heroImage: url } }), 't5hi')} />
                </label>
              </div>
            </div>
          </div>

          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-6 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">Promotional Section</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-4">
                <input type="text" value={config.theme05?.promoTagline || ''} placeholder="Tagline" onChange={(e) => setConfig({ ...config, theme05: { ...config.theme05, promoTagline: e.target.value } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm" />
                <input type="text" value={config.theme05?.promoTitle || ''} placeholder="Promo Title" onChange={(e) => setConfig({ ...config, theme05: { ...config.theme05, promoTitle: e.target.value } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm font-bold" />
                <input type="text" value={config.theme05?.promoSubtitle || ''} placeholder="Promo Subtitle" onChange={(e) => setConfig({ ...config, theme05: { ...config.theme05, promoSubtitle: e.target.value } })} className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm" />
              </div>
              <div className="space-y-4">
                {config.theme05?.promoImage && <img src={config.theme05.promoImage} className="w-full h-32 object-cover rounded-xl" />}
                <label className="flex items-center justify-center gap-1 w-full bg-slate-900 text-white hover:bg-slate-800 py-3 rounded-xl font-bold text-sm cursor-pointer transition-colors mt-2">
                  <Upload size={16} /> Upload Promo Image
                  <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => setConfig({ ...config, theme05: { ...config.theme05, promoImage: url } }), 't5pi')} />
                </label>
              </div>
            </div>
          </div>

          {/* Product Tab Selectors */}
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-2 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">Product Tab Selections</h3>
              <p className="text-sm text-slate-500 mb-6">Choose which products appear in each tab. If none selected, all products are shown.</p>
              <div className="space-y-8">
                {([
                  { label: 'Featured', key: 'featuredIds', badge: 'FEAT', color: 'bg-purple-100 text-purple-700' },
                  { label: 'Best Sellers', key: 'bestSellersIds', badge: 'BEST', color: 'bg-amber-100 text-amber-700' },
                  { label: 'New Arrivals', key: 'newArrivalsIds', badge: 'NEW', color: 'bg-green-100 text-green-700' },
                  { label: 'On Sale', key: 'onSaleIds', badge: 'SALE', color: 'bg-red-100 text-red-700' },
                ] as const).map(({ label, key, badge, color }) => {
                  const selectedIds: string[] = (config.theme05 as any)?.[key] || [];
                  return (
                    <div key={key}>
                      <div className="flex items-center justify-between mb-3">
                        <div className="flex items-center gap-2">
                          <span className={`text-[10px] font-black px-2 py-0.5 rounded-full ${color}`}>{badge}</span>
                          <span className="font-black text-slate-800 dark:text-white text-sm">{label}</span>
                          {selectedIds.length > 0 && <span className="text-[10px] bg-slate-100 text-slate-500 px-2 py-0.5 rounded-full font-bold">{selectedIds.length} selected</span>}
                        </div>
                        {selectedIds.length > 0 && (
                          <button onClick={() => setConfig({ ...config, theme05: { ...config.theme05, [key]: [] } })} className="text-xs text-red-400 hover:text-red-600 font-bold flex items-center gap-1">
                            <X size={11} /> Clear
                          </button>
                        )}
                      </div>
                      <div className="grid grid-cols-2 sm:grid-cols-3 gap-2 max-h-48 overflow-y-auto pr-1">
                        {products.map((p) => {
                          const isSelected = selectedIds.includes(p.id);
                          return (
                            <div
                              key={p.id}
                              onClick={() => {
                                const updated = isSelected
                                  ? selectedIds.filter((id: string) => id !== p.id)
                                  : [...selectedIds, p.id];
                                setConfig({ ...config, theme05: { ...config.theme05, [key]: updated } });
                              }}
                              className={`flex items-center gap-2 p-2 rounded-xl border-2 cursor-pointer transition-all ${isSelected ? 'border-[#1A1A1A] bg-gray-50' : 'border-transparent bg-slate-50 hover:border-slate-200'}`}
                            >
                              <img src={p.image} alt={p.name} className="w-10 h-10 rounded-lg object-cover shrink-0" onError={(e) => { (e.target as HTMLImageElement).src = 'https://via.placeholder.com/40'; }} />
                              <div className="min-w-0">
                                <p className="text-xs font-bold text-slate-700 truncate">{p.name}</p>
                                <p className="text-[10px] text-slate-400">৳{p.price}</p>
                              </div>
                              {isSelected && <div className="ml-auto w-4 h-4 rounded-full bg-[#1A1A1A] flex items-center justify-center shrink-0"><span className="text-white text-[8px]">✓</span></div>}
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  );
                })}
              </div>
          </div>

          {/* Testimonials Manager */}
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-2 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">What Our Customers Say</h3>
              <p className="text-sm text-slate-500 mb-5">Add customer reviews. If none added, default demo reviews are shown.</p>
              <div className="space-y-4 mb-4">
                {(config.theme05?.testimonials || []).map((t: any, index: number) => (
                  <div key={index} className="bg-slate-50 rounded-2xl p-5 border border-slate-100 relative">
                    <button
                      onClick={() => {
                        const updated = [...(config.theme05?.testimonials || [])];
                        updated.splice(index, 1);
                        setConfig({ ...config, theme05: { ...config.theme05, testimonials: updated } });
                      }}
                      className="absolute top-3 right-3 bg-red-100 text-red-500 p-1 rounded-full hover:bg-red-200 transition"
                    ><X size={12} /></button>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-3">
                      <input
                        type="text" value={t.name} placeholder="Customer Name"
                        onChange={(e) => {
                          const updated = [...(config.theme05?.testimonials || [])];
                          updated[index] = { ...updated[index], name: e.target.value };
                          setConfig({ ...config, theme05: { ...config.theme05, testimonials: updated } });
                        }}
                        className="border border-slate-200 px-3 py-2 rounded-lg text-sm"
                      />
                      <input
                        type="text" value={t.location} placeholder="Location (e.g. Dhaka, BD)"
                        onChange={(e) => {
                          const updated = [...(config.theme05?.testimonials || [])];
                          updated[index] = { ...updated[index], location: e.target.value };
                          setConfig({ ...config, theme05: { ...config.theme05, testimonials: updated } });
                        }}
                        className="border border-slate-200 px-3 py-2 rounded-lg text-sm"
                      />
                    </div>
                    <textarea
                      value={t.text} placeholder="Review text..." rows={2}
                      onChange={(e) => {
                        const updated = [...(config.theme05?.testimonials || [])];
                        updated[index] = { ...updated[index], text: e.target.value };
                        setConfig({ ...config, theme05: { ...config.theme05, testimonials: updated } });
                      }}
                      className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm mb-3"
                    />
                    <div className="flex items-center gap-3">
                      <div>
                        <label className="text-xs text-slate-500 font-bold block mb-1">Rating</label>
                        <select value={t.rating || 5} onChange={(e) => {
                          const updated = [...(config.theme05?.testimonials || [])];
                          updated[index] = { ...updated[index], rating: Number(e.target.value) };
                          setConfig({ ...config, theme05: { ...config.theme05, testimonials: updated } });
                        }} className="border border-slate-200 rounded-lg px-2 py-1 text-sm">
                          {[5,4,3,2,1].map(r => <option key={r} value={r}>{r} ★</option>)}
                        </select>
                      </div>
                      <div className="flex-1">
                        <label className="text-xs text-slate-500 font-bold block mb-1">Photo URL or Upload</label>
                        <div className="flex gap-2">
                          <input type="text" value={t.image || ''} placeholder="Photo URL" onChange={(e) => {
                            const updated = [...(config.theme05?.testimonials || [])];
                            updated[index] = { ...updated[index], image: e.target.value };
                            setConfig({ ...config, theme05: { ...config.theme05, testimonials: updated } });
                          }} className="flex-1 border border-slate-200 px-2 py-1 rounded-lg text-xs" />
                          {t.image && <img src={t.image} className="w-8 h-8 rounded-full object-cover" />}
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
              <button
                onClick={() => {
                  const updated = [...(config.theme05?.testimonials || []), { name: '', location: '', image: '', text: '', rating: 5 }];
                  setConfig({ ...config, theme05: { ...config.theme05, testimonials: updated } });
                }}
                className="w-full py-3 border-2 border-dashed border-slate-200 rounded-2xl text-slate-400 hover:text-slate-600 hover:border-slate-400 transition font-bold flex items-center justify-center gap-2 text-sm"
              >
                <Plus size={16} /> Add Review
              </button>
            </div>

          {/* Instagram Feed Manager */}
          <div className="bg-white dark:bg-slate-900 rounded-[32px] border p-8 shadow-sm">
            <h3 className="text-xl font-black mb-2 uppercase tracking-tight text-slate-800 dark:text-white border-b pb-4">Follow Us on Instagram</h3>
              <p className="text-sm text-slate-500 mb-5">Set your Instagram handle and upload up to 6 feed images.</p>
              <div className="mb-4">
                <label className="block text-xs font-bold text-slate-600 mb-1">Instagram Handle</label>
                <input
                  type="text"
                  value={config.theme05?.instagramHandle || ''}
                  placeholder="@yourhandle"
                  onChange={(e) => setConfig({ ...config, theme05: { ...config.theme05, instagramHandle: e.target.value } })}
                  className="w-full border border-slate-200 px-3 py-2 rounded-lg text-sm"
                />
              </div>
              <div className="grid grid-cols-3 md:grid-cols-6 gap-3 mb-4">
                {(config.theme05?.instagramImages || []).map((img: string, idx: number) => (
                  <div key={idx} className="relative aspect-square group">
                    <img src={img} className="w-full h-full object-cover rounded-xl" />
                    <button
                      onClick={() => {
                        const updated = [...(config.theme05?.instagramImages || [])];
                        updated.splice(idx, 1);
                        setConfig({ ...config, theme05: { ...config.theme05, instagramImages: updated } });
                      }}
                      className="absolute top-1 right-1 w-5 h-5 bg-red-500 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition"
                    ><X size={10} /></button>
                  </div>
                ))}
                {(config.theme05?.instagramImages || []).length < 6 && (
                  <label className="aspect-square border-2 border-dashed border-slate-200 rounded-xl flex flex-col items-center justify-center cursor-pointer hover:border-slate-400 transition">
                    <Plus size={20} className="text-slate-400" />
                    <span className="text-[10px] text-slate-400 mt-1">Add</span>
                    <input type="file" className="hidden" accept="image/*" onChange={(e) => handleImageUpload(e, (url) => {
                      const updated = [...(config.theme05?.instagramImages || []), url];
                      setConfig({ ...config, theme05: { ...config.theme05, instagramImages: updated } });
                    }, `t5ig-${Date.now()}`)} />
                  </label>
                )}
              </div>
            </div>

        </div>
      )}

      {/* Theme Preview Modal */}
      {isPreviewMode && (
        <div className="fixed inset-0 z-[100] bg-white flex flex-col overflow-hidden">
          {/* Preview Header Bar */}
          <div className="bg-slate-900 text-white px-6 py-3 flex justify-between items-center z-10 shadow-md">
            <div className="flex items-center gap-3">
              <Eye className="text-amber-400" size={20} />
              <span className="font-bold tracking-widest uppercase text-sm">Theme Preview Mode - Theme 0{config.theme || 1}</span>
            </div>
            <button
              onClick={() => setIsPreviewMode(false)}
              className="bg-red-600 hover:bg-red-700 text-white px-4 py-1.5 rounded font-bold text-xs uppercase tracking-wider flex items-center gap-1 transition"
            >
              <X size={16} /> Exit Preview
            </button>
          </div>

          <div className="flex-1 overflow-y-auto bg-gray-50 relative pointer-events-auto">
            <div className="pointer-events-none">
              <GlobalThemeHeader
                theme={config.theme || '01'}
                toggleTheme={() => { }}
                isDarkMode={false}
                cartCount={0}
                onCartClick={() => { }}
                logo={settings.logo || ''}
                onNavigate={() => { }}
                currentView="home"
                contactPhone={settings.phone || settings.contactPhone}
                settings={{ ...settings, homePageJson: JSON.stringify(config) }}
              />
            </div>

            <div className="pointer-events-none">
              {config.theme === '02' ? <HomePage02 settings={{ ...settings, homePageJson: JSON.stringify(config) }} featuredProducts={products} isProductsLoaded={true} navigateTo={() => { }} setDirectCheckoutProduct={() => { }} onSelectProduct={() => { }} /> :
                config.theme === '03' ? <HomePage03 settings={{ ...settings, homePageJson: JSON.stringify(config) }} featuredProducts={products} isProductsLoaded={true} navigateTo={() => { }} setDirectCheckoutProduct={() => { }} onSelectProduct={() => { }} /> :
                  config.theme === '04' ? <HomePage04 settings={{ ...settings, homePageJson: JSON.stringify(config) }} featuredProducts={products} isProductsLoaded={true} navigateTo={() => { }} setDirectCheckoutProduct={() => { }} onSelectProduct={() => { }} /> :
                    config.theme === '05' ? <HomePage05 settings={{ ...settings, homePageJson: JSON.stringify(config) }} featuredProducts={products} isProductsLoaded={true} navigateTo={() => { }} setDirectCheckoutProduct={() => { }} onSelectProduct={() => { }} /> :
                      <HomePage01 settings={{ ...settings, homePageJson: JSON.stringify(config) }} featuredProducts={products} isProductsLoaded={true} navigateTo={() => { }} setDirectCheckoutProduct={() => { }} onSelectProduct={() => { }} />
              }
            </div>

            <div className="pointer-events-none">
              <GlobalThemeFooter 
                theme={config.theme || '01'}
                settings={{ ...settings, homePageJson: JSON.stringify(config) }} 
                onNavigate={() => { }} 
              />
            </div>
          </div>
        </div>
      )}

    </div>
  );
};

export default HomePageEditor;
