import React, { useState, useEffect, useRef } from 'react';
import { 
  Search, User, Heart, ShoppingCart, ChevronDown, 
  Menu, X, Clock, MapPin, Mail, Phone,
  ShoppingBag, Facebook, Instagram, Youtube, Truck,
  LogOut, Building2
} from 'lucide-react';
import { SiteSettings, CustomPage } from '../types';
import { CustomerUser } from './AuthModal';

export interface GlobalHeaderProps {
  theme?: string;
  toggleTheme: () => void;
  isDarkMode: boolean;
  cartCount: number;
  onCartClick: () => void;
  logo: string;
  onNavigate: (view: string) => void;
  currentView: string;
  contactPhone?: string;
  settings: SiteSettings;
  customerUser?: CustomerUser | null;
  onOpenAuth?: (tab?: 'login' | 'register') => void;
  onCustomerLogout?: () => void;
}

export function getActiveCustomPages(settings: SiteSettings, themeId: string): CustomPage[] {
  try {
    if (settings?.customPagesJson) {
      const pages: CustomPage[] = JSON.parse(settings.customPagesJson);
      return pages.filter(p => p.status === 'published' && p.assignedThemes.includes(themeId as any));
    }
  } catch (e) {}
  return [];
}

// ------------------------------------
// UserButton — shared across all themes
// ------------------------------------
const UserButton: React.FC<{
  customerUser?: CustomerUser | null;
  onOpenAuth?: (tab?: 'login' | 'register') => void;
  onCustomerLogout?: () => void;
  accentColor?: string;
}> = ({ customerUser, onOpenAuth, onCustomerLogout, accentColor = '#634C9F' }) => {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  if (!customerUser) {
    return (
      <button
        onClick={() => onOpenAuth?.('login')}
        className="hidden md:flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-semibold transition-all"
        style={{ background: accentColor, color: '#fff', boxShadow: `0 4px 12px ${accentColor}55` }}
      >
        <User size={15} /> Login
      </button>
    );
  }

  return (
    <div ref={ref} className="relative hidden md:block">
      <button
        onClick={() => setOpen(!open)}
        className="flex items-center gap-2 px-3 py-1.5 rounded-full text-sm font-semibold transition-all"
        style={{ background: `${accentColor}18`, color: accentColor, border: `1.5px solid ${accentColor}40` }}
      >
        <div className="w-6 h-6 rounded-full flex items-center justify-center text-white text-[10px] font-black"
          style={{ background: accentColor }}>
          {customerUser.name.charAt(0).toUpperCase()}
        </div>
        <span className="max-w-[80px] truncate">{customerUser.name.split(' ')[0]}</span>
        <ChevronDown size={13} className={`transition-transform ${open ? 'rotate-180' : ''}`} />
      </button>

      {open && (
        <div className="absolute right-0 top-full mt-2 w-56 bg-white rounded-2xl shadow-2xl border border-gray-100 overflow-hidden z-50"
          style={{ animation: 'fadeInDown 0.15s ease' }}>
          {/* Profile info */}
          <div className="px-4 py-3 border-b border-gray-50" style={{ background: `${accentColor}08` }}>
            <div className="flex items-center gap-2.5">
              <div className="w-10 h-10 rounded-full flex items-center justify-center text-white font-black text-sm flex-shrink-0"
                style={{ background: `linear-gradient(135deg,${accentColor},${accentColor}cc)` }}>
                {customerUser.name.charAt(0).toUpperCase()}
              </div>
              <div className="min-w-0">
                <p className="font-bold text-gray-800 text-sm truncate">{customerUser.name}</p>
                <p className="text-gray-400 text-[10px] truncate">{customerUser.phone}</p>
              </div>
            </div>
            {customerUser.business_name && (
              <div className="flex items-center gap-1.5 mt-2 px-2 py-1 rounded-lg bg-white/70 text-xs text-gray-600">
                <Building2 size={11} style={{ color: accentColor }} />
                <span className="truncate">{customerUser.business_name}</span>
              </div>
            )}
          </div>
          {/* Logout */}
          <button
            onClick={() => { setOpen(false); onCustomerLogout?.(); }}
            className="w-full flex items-center gap-2.5 px-4 py-3 text-sm font-medium text-red-500 hover:bg-red-50 transition"
          >
            <LogOut size={15} /> Logout
          </button>
        </div>
      )}

      <style>{`@keyframes fadeInDown{ from{opacity:0;transform:translateY(-6px)} to{opacity:1;transform:translateY(0)} }`}</style>
    </div>
  );
};

// ------------------------------------
// Theme 01 Header
// ------------------------------------
const ThemeHeader01: React.FC<GlobalHeaderProps> = ({ cartCount, onCartClick, onNavigate, settings, logo, customerUser, onOpenAuth, onCustomerLogout }) => {
  let activeCategories: string[] = [];
  try {
    if (settings?.categoriesJson) {
      const parsed = JSON.parse(settings.categoriesJson);
      if (Array.isArray(parsed)) {
        activeCategories = parsed.map((cat: any) => typeof cat === 'string' ? cat : cat.name).filter(Boolean);
      }
    }
  } catch (e) {}

  const [wishlistCount] = useState(2);
  const [liveTimer, setLiveTimer] = useState('12 : 45 : 30');

  useEffect(() => {
    const timer = setInterval(() => {
      const now = new Date();
      const hours = 23 - now.getHours();
      const minutes = 59 - now.getMinutes();
      const seconds = 59 - now.getSeconds();
      setLiveTimer(`${String(hours).padStart(2, '0')} : ${String(minutes).padStart(2, '0')} : ${String(seconds).padStart(2, '0')}`);
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  return (
    <div className="bg-white font-sans" style={{ fontFamily: "'Inter', 'Poppins', sans-serif" }}>
      {/* ── Mobile compact header (phone only) ── */}
      <div
        className="md:hidden sticky top-0 z-50 flex items-center justify-between px-4 pb-2 pt-[max(0.5rem,env(safe-area-inset-top))] shadow-sm backdrop-blur-md"
        style={{ background: '#634C9F', boxShadow: '0 2px 12px rgba(99,76,159,0.3)' }}
      >
        <div className="flex-shrink-0 cursor-pointer" onClick={() => onNavigate('home')}>
          {logo
            ? <img src={logo} alt={settings?.siteName || ''} className="max-h-8 object-contain brightness-200" />
            : <span className="text-white font-black text-lg tracking-tight">{settings?.siteName || 'ShophyFast'}</span>
          }
        </div>
        <form onSubmit={e => { e.preventDefault(); onNavigate('shop'); }} className="flex-1 mx-3">
          <div className="relative">
            <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-white/60" />
            <input type="text" placeholder="Search products..." className="w-full bg-white/20 rounded-full pl-8 pr-3 py-1.5 text-sm text-white placeholder-white/60 outline-none border border-white/20 focus:border-white/50" />
          </div>
        </form>
        <button onClick={onCartClick} className="relative p-1">
          <ShoppingCart size={22} className="text-white" />
          {cartCount > 0 && (
            <span className="absolute -top-1 -right-1 min-w-[16px] h-4 bg-amber-400 text-[#634C9F] text-[8px] font-black rounded-full flex items-center justify-center px-0.5">{cartCount}</span>
          )}
        </button>
      </div>

      {/* Top Bar with Countdown — hidden on mobile */}
      <div className="hidden md:block bg-[#202342] text-white py-2.5 px-4">
        <div className="max-w-[1300px] mx-auto flex justify-between items-center text-sm">
          <div className="flex items-center gap-2">
            <span className="hidden md:inline-block">🎉</span>
            <span className="text-xs md:text-sm font-medium">Biggest Sale of the Year! Up to 50% off on groceries</span>
          </div>
          <div className="flex items-center gap-2 bg-white/10 px-3 py-1 rounded-full">
            <Clock size={14} className="text-amber-400" />
            <span className="text-xs font-mono font-bold tracking-wider">LIVE: {liveTimer}</span>
          </div>
        </div>
      </div>

      {/* Secondary Header — desktop only */}
      <div className="hidden md:block sticky top-0 z-40 bg-white shadow-sm border-b">
        <div className="max-w-[1300px] mx-auto px-4 py-4">
          <div className="flex flex-wrap items-center justify-between gap-4">
                        {/* Logo */}
            <div className="flex-shrink-0 cursor-pointer" onClick={() => onNavigate('home')}>
              {logo ? (
                <img src={logo} alt={settings?.siteName || 'shophyfast'} className="max-h-12 object-contain" />
              ) : (
                <div className="text-2xl font-black">
                  <span className="text-[#634C9F]">{settings?.siteName ? settings.siteName.split(' ')[0] : 'shophyfast'}</span>
                  <span className="text-[#202342]">{settings?.siteName && settings.siteName.split(' ').length > 1 ? settings.siteName.split(' ').slice(1).join(' ') : ''}</span>
                </div>
              )}
            </div>

            {/* Modern Search Bar */}
            <div className="flex-1 max-w-2xl w-full lg:mx-8">
              <form 
                onSubmit={(e) => { e.preventDefault(); onNavigate('shop'); }}
                className="relative flex items-center w-full h-12 bg-white rounded-full border-2 border-themePrimary/20 hover:border-themePrimary/50 focus-within:border-themePrimary focus-within:ring-4 focus-within:ring-themePrimary/10 transition-all duration-300 overflow-hidden shadow-sm"
              >
                {activeCategories.length > 0 && (
                  <div className="hidden sm:flex items-center h-full border-r border-gray-200 bg-slate-50">
                    <select className="h-full bg-transparent text-sm text-slate-700 font-medium px-4 outline-none cursor-pointer tracking-tight appearance-none pr-8 relative">
                      <option value="all">All Categories</option>
                      {activeCategories.map(cat => (
                        <option key={cat} value={cat}>{cat}</option>
                      ))}
                    </select>
                    <div className="pointer-events-none absolute left-[125px]">
                      <ChevronDown size={14} className="text-slate-400" />
                    </div>
                  </div>
                )}
                <input 
                  type="text" 
                  placeholder="I'm shopping for..." 
                  className="flex-1 h-full bg-transparent text-sm px-5 outline-none text-slate-700 placeholder-slate-400"
                />
                <button 
                  type="submit"
                  className="h-full px-6 bg-themePrimary text-white font-bold flex items-center justify-center gap-2 hover:bg-themeHover transition-colors"
                >
                  <Search size={18} />
                  <span className="hidden sm:inline">Search</span>
                </button>
              </form>
            </div>

            {/* Right Icons */}
            <div className="flex items-center gap-4">
              <UserButton customerUser={customerUser} onOpenAuth={onOpenAuth} onCustomerLogout={onCustomerLogout} accentColor="#634C9F" />
              <button className="relative text-gray-600 hover:text-[#634C9F] transition">
                <Heart size={20} />
                <span className="absolute -top-2 -right-2 bg-[#634C9F] text-white text-[10px] font-bold rounded-full w-4 h-4 flex items-center justify-center">{wishlistCount}</span>
              </button>
              <button className="relative text-gray-600 hover:text-[#634C9F] transition" onClick={onCartClick}>
                <ShoppingCart size={20} />
                <span className="absolute -top-2 -right-2 bg-[#634C9F] text-white text-[10px] font-bold rounded-full w-4 h-4 flex items-center justify-center">{cartCount}</span>
              </button>
            </div>
          </div>

          {/* Navigation Menu */}
          <div className="flex items-center justify-between mt-4 pb-1">
            <div className="flex items-center gap-6 text-sm font-medium">
              <div className="relative group">
                <button className="flex items-center gap-2 bg-themePrimary text-white px-4 py-2 rounded-full hover:bg-themeHover transition whitespace-nowrap" onClick={() => onNavigate('shop')}>
                  <Menu size={16} /> All Categories <ChevronDown size={14} />
                </button>
                {activeCategories.length > 0 && (
                  <div className="absolute top-full left-0 mt-2 w-48 bg-white border border-gray-100 rounded-xl shadow-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-300 z-50 flex flex-col py-2">
                    {activeCategories.map(cat => (
                      <button 
                        key={cat} 
                        className="text-left px-4 py-2 hover:bg-slate-50 hover:text-themePrimary transition text-sm font-medium text-slate-700"
                        onClick={() => onNavigate('shop', { category: cat })}
                      >
                        {cat}
                      </button>
                    ))}
                  </div>
                )}
              </div>
              <button className="text-gray-700 hover:text-themePrimary transition whitespace-nowrap" onClick={() => onNavigate('home')}>Home</button>
              <button className="text-gray-700 hover:text-themePrimary transition whitespace-nowrap" onClick={() => onNavigate('shop')}>Shop</button>
              <button className="text-gray-700 hover:text-themePrimary transition whitespace-nowrap" onClick={() => onNavigate('shop', { category: 'Fruits & Vegetables' })}>Fruits & Vegetables</button>
              <button className="text-gray-700 hover:text-themePrimary transition whitespace-nowrap" onClick={() => onNavigate('shop', { category: 'Beverages' })}>Beverages</button>
              <button className="text-gray-700 hover:text-themePrimary transition whitespace-nowrap" onClick={() => onNavigate('blog')}>Blog</button>
              <button className="text-gray-700 hover:text-themePrimary transition whitespace-nowrap" onClick={() => onNavigate('contact')}>Contact</button>
              {getActiveCustomPages(settings, '01').length > 0 && (
                <div className="relative group">
                  <button className="flex items-center gap-1 text-gray-700 hover:text-themePrimary transition whitespace-nowrap">
                    Pages <ChevronDown size={14} />
                  </button>
                  <div className="absolute top-full left-0 mt-2 w-48 bg-white border border-gray-100 rounded-xl shadow-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-300 z-50 flex flex-col py-2">
                    {getActiveCustomPages(settings, '01').map(page => (
                      <button 
                        key={page.id} 
                        className="text-left px-4 py-2 hover:bg-slate-50 hover:text-themePrimary transition text-sm font-medium text-slate-700"
                        onClick={() => onNavigate(`page/${page.slug}`)}
                      >
                        {page.title}
                      </button>
                    ))}
                  </div>
                </div>
              )}
              
              <button className="text-themePrimary font-bold whitespace-nowrap" onClick={() => onNavigate('trending')}>Trending Products</button>
              <button className="bg-red-500 text-white px-4 py-1.5 rounded-full text-xs font-bold whitespace-nowrap">Almost Finished</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ------------------------------------
// Theme 02 Header
// ------------------------------------
const ThemeHeader02: React.FC<GlobalHeaderProps> = ({ cartCount, onCartClick, onNavigate, settings, logo, customerUser, onOpenAuth, onCustomerLogout }) => {
  const [liveTimer, setLiveTimer] = useState('12 : 45 : 30');

  useEffect(() => {
    const timer = setInterval(() => {
      const now = new Date();
      const hours = 23 - now.getHours();
      const minutes = 59 - now.getMinutes();
      const seconds = 59 - now.getSeconds();
      setLiveTimer(`${String(hours).padStart(2, '0')} : ${String(minutes).padStart(2, '0')} : ${String(seconds).padStart(2, '0')}`);
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  return (
    <div className="bg-white font-sans">
      {/* ── Mobile compact header (phone only) ── */}
      <div
        className="md:hidden sticky top-0 z-50 flex items-center justify-between px-4 pb-2 pt-[max(0.5rem,env(safe-area-inset-top))] shadow-sm backdrop-blur-md"
        style={{ background: '#1E1B4B', boxShadow: '0 2px 12px rgba(30,27,75,0.35)' }}
      >
        <div className="flex-shrink-0 cursor-pointer" onClick={() => onNavigate('home')}>
          {logo
            ? <img src={logo} alt={settings?.siteName || ''} className="max-h-8 object-contain brightness-200" />
            : <span className="text-white font-black text-lg tracking-tight">{settings?.siteName || 'ShophyFast'}</span>
          }
        </div>
        <form onSubmit={e => { e.preventDefault(); onNavigate('shop'); }} className="flex-1 mx-3">
          <div className="relative">
            <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-white/60" />
            <input type="text" placeholder="Search products..." className="w-full bg-white/20 rounded-full pl-8 pr-3 py-1.5 text-sm text-white placeholder-white/60 outline-none border border-white/20 focus:border-white/40" />
          </div>
        </form>
        <button onClick={onCartClick} className="relative p-1">
          <ShoppingCart size={22} className="text-white" />
          {cartCount > 0 && (
            <span className="absolute -top-1 -right-1 min-w-[16px] h-4 bg-amber-400 text-[#1E1B4B] text-[8px] font-black rounded-full flex items-center justify-center px-0.5">{cartCount}</span>
          )}
        </button>
      </div>

      {/* TOP BAR — desktop only */}
      <div className="hidden md:block bg-[#1E1B4B] text-white py-2.5 px-4">
        <div className="max-w-[1400px] mx-auto flex justify-between items-center text-sm">
          <div className="flex items-center gap-2">
            <span className="hidden md:inline-block">🎉</span>
            <span className="text-xs md:text-sm font-medium">Biggest Sale of the Year! Up to 50% off on groceries</span>
          </div>
          <div className="flex items-center gap-2 bg-black/20 px-3 py-1 rounded-full">
            <Clock size={14} className="text-amber-400" />
            <span className="text-xs font-mono font-bold tracking-wider">LIVE: {liveTimer}</span>
          </div>
        </div>
      </div>
      
      {/* Navigation — desktop only */}
      <div className="hidden md:block sticky top-0 z-40 bg-white shadow-sm border-b px-4 py-4">
        <div className="max-w-[1400px] mx-auto flex flex-wrap items-center justify-between gap-4">
          <div className="flex-shrink-0 cursor-pointer" onClick={() => onNavigate('home')}>
            {logo ? (
              <img src={logo} alt={settings?.siteName || 'shophyfast'} className="max-h-12 object-contain" />
            ) : (
              <div className="text-2xl font-black text-[#1E1B4B]">{settings?.siteName || 'shophyfast'}</div>
            )}
          </div>
          <div className="hidden md:flex flex-1 max-w-lg w-full">
            <div className="relative w-full">
              <input type="text" placeholder="Search..." className="w-full border border-gray-300 rounded-full py-2.5 px-5 pr-12 text-sm focus:outline-none focus:border-[#634C9F]" />
              <button className="absolute right-2 top-1/2 -translate-y-1/2 p-2 hover:bg-gray-100 rounded-full transition"><Search size={16}/></button>
            </div>
          </div>
          <div className="flex items-center gap-4 text-sm font-bold">
             <button className="text-gray-700 hover:text-[#634C9F] transition" onClick={() => onNavigate('home')}>Home</button>
             <button className="text-gray-700 hover:text-[#634C9F] transition" onClick={() => onNavigate('shop')}>Shop</button>
             {getActiveCustomPages(settings, '02').length > 0 && (
                <div className="relative group">
                  <button className="flex items-center gap-1 text-gray-700 hover:text-[#634C9F] transition whitespace-nowrap">
                    Pages <ChevronDown size={14} />
                  </button>
                  <div className="absolute top-full left-0 mt-2 w-48 bg-white border border-gray-100 rounded-xl shadow-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-300 z-50 flex flex-col py-2">
                    {getActiveCustomPages(settings, '02').map(page => (
                      <button 
                        key={page.id} 
                        className="text-left px-4 py-2 hover:bg-slate-50 hover:text-[#634C9F] transition text-sm font-medium text-slate-700"
                        onClick={() => onNavigate(`page/${page.slug}`)}
                      >
                        {page.title}
                      </button>
                    ))}
                  </div>
                </div>
              )}
             <button className="relative p-2 text-gray-700 hover:text-[#634C9F] transition" onClick={onCartClick}>
                <ShoppingCart size={20} />
                <span className="absolute -top-1 -right-1 bg-[#E53935] text-white text-[10px] font-bold rounded-full w-4 h-4 flex items-center justify-center">{cartCount}</span>
             </button>
             <UserButton customerUser={customerUser} onOpenAuth={onOpenAuth} onCustomerLogout={onCustomerLogout} accentColor="#1E1B4B" />
          </div>
        </div>
      </div>
    </div>
  );
};


// ------------------------------------
// Theme 03 Header
// ------------------------------------
const ThemeHeader03: React.FC<GlobalHeaderProps> = ({ cartCount, onCartClick, onNavigate, contactPhone, settings, logo, customerUser, onOpenAuth, onCustomerLogout }) => {
  const [wishlistCount] = useState(2);
  const NAV_ITEMS = [
    { name: 'Skin', color: 'default' },
    { name: 'Health & Hygiene', color: 'default' },
    { name: 'Body', color: 'default' },
    { name: 'Hair', color: 'default' },
    { name: 'Mom & Baby', color: 'default' },
    { name: 'BUY ONE GET ONE', color: 'green' },
    { name: 'BRANDS', color: 'magenta' },
    { name: 'BLOG', color: 'purple' },
  ];

  return (
    <div className="bg-white font-sans relative">
      {/* ── Mobile compact header (phone only) ── */}
      <div
        className="md:hidden sticky top-0 z-50 flex items-center justify-between px-4 pb-2 pt-[max(0.5rem,env(safe-area-inset-top))] shadow-sm backdrop-blur-md"
        style={{ background: '#E91E63', boxShadow: '0 2px 12px rgba(233,30,99,0.35)' }}
      >
        <div className="flex-shrink-0 cursor-pointer" onClick={() => onNavigate('home')}>
          {logo
            ? <img src={logo} alt={settings?.siteName || ''} className="max-h-8 object-contain brightness-200" />
            : <span className="text-white font-black text-lg" style={{ fontFamily: 'Georgia, serif' }}>{settings?.siteName || 'ShophyFast'}</span>
          }
        </div>
        <form onSubmit={e => { e.preventDefault(); onNavigate('shop'); }} className="flex-1 mx-3">
          <div className="relative">
            <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-white/60" />
            <input type="text" placeholder="Search beauty & care..." className="w-full bg-white/20 rounded-full pl-8 pr-3 py-1.5 text-sm text-white placeholder-white/60 outline-none border border-white/20" />
          </div>
        </form>
        <button onClick={onCartClick} className="relative p-1">
          <ShoppingBag size={22} className="text-white" />
          {cartCount > 0 && (
            <span className="absolute -top-1 -right-1 min-w-[16px] h-4 bg-white text-[#E91E63] text-[8px] font-black rounded-full flex items-center justify-center px-0.5">{cartCount}</span>
          )}
        </button>
      </div>

      {/* Top pink bar — desktop only */}
      <div className="hidden md:block bg-[#E91E63] text-white py-2.5 px-4 text-sm">
        <div className="max-w-[1280px] mx-auto flex justify-between items-center">
          <div className="flex items-center gap-2">
            <Phone size={14} />
            <span className="text-xs md:text-sm">Hotline: {contactPhone || '+880 1234 567890'}</span>
          </div>
          <div className="flex gap-4 text-xs">
            <button className="hover:underline" onClick={() => onNavigate('faq')}>FAQ</button>
            <button className="hover:underline" onClick={() => onNavigate('help')}>Help</button>
            {customerUser
              ? <button className="hover:underline font-bold" onClick={() => onCustomerLogout?.()}>{customerUser.name.split(' ')[0]} (Logout)</button>
              : <button className="hover:underline" onClick={() => onOpenAuth?.('login')}>Sign In</button>}
          </div>
        </div>
      </div>
      <div className="hidden md:block sticky top-0 z-40 bg-white shadow-sm border-b">
        <div className="max-w-[1280px] mx-auto px-4 py-4">
          <div className="flex flex-wrap items-center justify-between gap-4">
            <div className="flex-shrink-0 cursor-pointer" onClick={() => onNavigate('home')}>
              {logo ? (
                <img src={logo} alt={settings?.siteName || 'shophyfast'} className="max-h-12 object-contain" />
              ) : (
                <div className="text-2xl font-serif font-black text-[#E91E63]">{settings?.siteName || 'shophyfast'}</div>
              )}
            </div>
            <div className="flex-1 max-w-lg w-full">
              <div className="relative">
                <input type="text" placeholder="Search for products, brands or categories..." className="w-full border border-gray-300 rounded-full py-2.5 px-5 pr-12 text-sm focus:outline-none focus:border-[#E91E63]" />
                <button className="absolute right-2 top-1/2 -translate-y-1/2 bg-gray-100 p-2 rounded-full hover:bg-[#E91E63] hover:text-white transition">
                  <Search size={16} />
                </button>
              </div>
            </div>
            <div className="flex items-center gap-4">
              <button className="relative p-2 hover:bg-gray-100 rounded-full transition">
                <Heart size={22} className="text-gray-700" />
                <span className="absolute -top-1 -right-1 bg-[#E91E63] text-white text-[10px] font-bold rounded-full w-5 h-5 flex items-center justify-center">{wishlistCount}</span>
              </button>
              <button className="relative p-2 hover:bg-gray-100 rounded-full transition" onClick={onCartClick}>
                <ShoppingBag size={22} className="text-gray-700" />
                <span className="absolute -top-1 -right-1 bg-[#E91E63] text-white text-[10px] font-bold rounded-full w-5 h-5 flex items-center justify-center">{cartCount}</span>
              </button>
            </div>
          </div>
          <div className="flex items-center justify-between mt-4 gap-4">
            <div className="flex items-center gap-5 text-sm font-medium flex-wrap">
              {NAV_ITEMS.map((item, idx) => (
                <button
                  key={idx}
                  className={`whitespace-nowrap transition hover:opacity-80 ${item.color === 'green' ? 'text-green-600 font-bold' : item.color === 'magenta' ? 'text-[#E91E63] font-bold' : item.color === 'purple' ? 'text-purple-600 font-bold' : 'text-gray-700'}`}
                  onClick={() => {
                    if (item.name === 'BRANDS') onNavigate('brands');
                    else if (item.name === 'BLOG') onNavigate('blog');
                    else onNavigate('shop');
                  }}
                >
                  {item.name}
                </button>
              ))}
              {getActiveCustomPages(settings, '03').length > 0 && (
                <div className="relative group">
                  <button className="flex items-center gap-1 text-gray-700 hover:text-black transition whitespace-nowrap">
                    Pages <ChevronDown size={14} />
                  </button>
                  <div className="absolute top-full left-0 mt-2 w-48 bg-white border border-gray-100 rounded-xl shadow-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-300 z-50 flex flex-col py-2">
                    {getActiveCustomPages(settings, '03').map(page => (
                      <button 
                        key={page.id} 
                        className="text-left px-4 py-2 hover:bg-slate-50 hover:text-black transition text-sm font-medium text-slate-700"
                        onClick={() => onNavigate(`page/${page.slug}`)}
                      >
                        {page.title}
                      </button>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ------------------------------------
// Theme 04 Header
// ------------------------------------
const ThemeHeader04: React.FC<GlobalHeaderProps> = ({ cartCount, onCartClick, onNavigate, settings, logo, customerUser, onOpenAuth, onCustomerLogout }) => {
  const [wishlistCount] = useState(3);
  const NAV_ITEMS = [
    { name: 'Oil & Ghee', hasDropdown: true },
    { name: 'Honey', hasDropdown: true },
    { name: 'Dates', hasDropdown: true },
    { name: 'Spices', hasDropdown: true },
    { name: 'Nuts & Seeds', hasDropdown: true },
    { name: 'Herbal Products', hasDropdown: false },
    { name: 'Organic Foods', hasDropdown: false },
    { name: 'Gift Packs', hasDropdown: false },
  ];

  return (
    <div className="bg-white font-sans relative" style={{ fontFamily: "'Poppins', 'Hind Siliguri', sans-serif" }}>
      {/* ── Mobile compact header (phone only) ── */}
      <div
        className="md:hidden sticky top-0 z-50 flex items-center justify-between px-4 pb-2 pt-[max(0.5rem,env(safe-area-inset-top))] shadow-sm backdrop-blur-md"
        style={{ background: '#F37021', boxShadow: '0 2px 12px rgba(243,112,33,0.35)' }}
      >
        <div className="flex-shrink-0 cursor-pointer" onClick={() => onNavigate('home')}>
          {logo
            ? <img src={logo} alt={settings?.siteName || ''} className="max-h-8 object-contain brightness-200" />
            : <span className="text-white font-black text-lg tracking-tight">{settings?.siteName || 'ShophyFast'}</span>
          }
        </div>
        <form onSubmit={e => { e.preventDefault(); onNavigate('shop'); }} className="flex-1 mx-3">
          <div className="relative">
            <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-white/60" />
            <input type="text" placeholder="Search natural products..." className="w-full bg-white/20 rounded-full pl-8 pr-3 py-1.5 text-sm text-white placeholder-white/60 outline-none border border-white/20" />
          </div>
        </form>
        <button onClick={onCartClick} className="relative p-1">
          <ShoppingCart size={22} className="text-white" />
          {cartCount > 0 && (
            <span className="absolute -top-1 -right-1 min-w-[16px] h-4 bg-white text-[#F37021] text-[8px] font-black rounded-full flex items-center justify-center px-0.5">{cartCount}</span>
          )}
        </button>
      </div>

      {/* Desktop sticky nav */}
      <div className="hidden md:block sticky top-0 z-40 bg-white shadow-sm border-b">
        <div className="max-w-[1280px] mx-auto px-4 py-4">
          <div className="flex flex-wrap items-center justify-between gap-4">
            <div className="flex-shrink-0 cursor-pointer" onClick={() => onNavigate('home')}>
              {logo ? (
                <img src={logo} alt={settings?.siteName || 'shophyfast'} className="max-h-12 object-contain" />
              ) : (
                <div className="text-2xl font-black text-[#F37021] tracking-tight">{settings?.siteName || 'shophyfast'}</div>
              )}
            </div>
            <div className="flex-1 max-w-xl w-full">
              <div className="relative">
                <input type="text" placeholder="Search for products, brands or categories..." className="w-full border border-gray-300 rounded-full py-2.5 px-5 pr-12 text-sm focus:outline-none focus:border-[#F37021]" />
                <button className="absolute right-2 top-1/2 -translate-y-1/2 bg-[#F37021] text-white p-2 rounded-full hover:bg-[#E05A10] transition">
                  <Search size={16} />
                </button>
              </div>
            </div>
            <div className="flex items-center gap-5">
              <button className="hidden md:flex items-center gap-1 text-gray-600 hover:text-[#F37021] transition text-sm">
                <Truck size={18} /> Track Order
              </button>
              <UserButton customerUser={customerUser} onOpenAuth={onOpenAuth} onCustomerLogout={onCustomerLogout} accentColor="#F37021" />
              <button className="relative text-gray-600 hover:text-[#F37021] transition">
                <Heart size={20} />
                <span className="absolute -top-2 -right-2 bg-[#F37021] text-white text-[10px] font-bold rounded-full w-4 h-4 flex items-center justify-center">{wishlistCount}</span>
              </button>
              <button className="relative text-gray-600 hover:text-[#F37021] transition" onClick={onCartClick}>
                <ShoppingCart size={20} />
                <span className="absolute -top-2 -right-2 bg-[#F37021] text-white text-[10px] font-bold rounded-full w-4 h-4 flex items-center justify-center">{cartCount}</span>
              </button>
            </div>
          </div>
          <div className="flex items-center justify-between mt-4">
            <div className="flex items-center gap-6 text-sm font-medium flex-wrap">
              {NAV_ITEMS.map((item, idx) => (
                <button key={idx} onClick={() => onNavigate('shop')} className="flex items-center gap-1 text-gray-700 hover:text-[#F37021] transition whitespace-nowrap">
                  {item.name}
                  {item.hasDropdown && <ChevronDown size={14} />}
                </button>
              ))}
              {getActiveCustomPages(settings, '04').length > 0 && (
                <div className="relative group">
                  <button className="flex items-center gap-1 text-gray-700 hover:text-[#F37021] transition whitespace-nowrap">
                    Pages <ChevronDown size={14} />
                  </button>
                  <div className="absolute top-full left-0 mt-2 w-48 bg-white border border-gray-100 rounded-xl shadow-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-300 z-50 flex flex-col py-2">
                    {getActiveCustomPages(settings, '04').map(page => (
                      <button 
                        key={page.id} 
                        className="text-left px-4 py-2 hover:bg-slate-50 hover:text-[#F37021] transition text-sm font-medium text-slate-700"
                        onClick={() => onNavigate(`page/${page.slug}`)}
                      >
                        {page.title}
                      </button>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ------------------------------------
// Theme 05 Header
// ------------------------------------
const ThemeHeader05: React.FC<GlobalHeaderProps> = ({ cartCount, onCartClick, onNavigate, settings, logo, customerUser, onOpenAuth, onCustomerLogout }) => {
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [wishlistCount] = useState(3);
  const NAV_ITEMS = [
    { name: 'New Arrivals', hasDropdown: false },
    { name: 'Women', hasDropdown: true },
    { name: 'Men', hasDropdown: true },
    { name: 'Kids', hasDropdown: true },
    { name: 'Accessories', hasDropdown: true },
    { name: 'Sale', hasDropdown: false, highlight: true },
    { name: 'Brands', hasDropdown: false },
  ];

  return (
    <div className="bg-white font-sans relative" style={{ fontFamily: "'Inter', 'Poppins', sans-serif" }}>
      {/* ── Mobile compact header (phone only) ── */}
      <div
        className="md:hidden sticky top-0 z-50 flex items-center justify-between px-4 pb-2 pt-[max(0.5rem,env(safe-area-inset-top))] shadow-sm backdrop-blur-md"
        style={{ background: '#1A1A1A', boxShadow: '0 2px 12px rgba(0,0,0,0.3)' }}
      >
        <div className="flex-shrink-0 cursor-pointer" onClick={() => onNavigate('home')}>
          {logo
            ? <img src={logo} alt={settings?.siteName || ''} className="max-h-8 object-contain brightness-200" />
            : <span className="text-white font-black text-lg tracking-tight">{settings?.siteName || 'ShophyFast'}</span>
          }
        </div>
        <form onSubmit={e => { e.preventDefault(); onNavigate('shop'); }} className="flex-1 mx-3">
          <div className="relative">
            <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-white/60" />
            <input type="text" placeholder="Search fashion..." className="w-full bg-white/15 rounded-full pl-8 pr-3 py-1.5 text-sm text-white placeholder-white/50 outline-none border border-white/15" />
          </div>
        </form>
        <button onClick={onCartClick} className="relative p-1">
          <ShoppingBag size={22} className="text-white" />
          {cartCount > 0 && (
            <span className="absolute -top-1 -right-1 min-w-[16px] h-4 bg-white text-[#1A1A1A] text-[8px] font-black rounded-full flex items-center justify-center px-0.5">{cartCount}</span>
          )}
        </button>
      </div>

      {/* Desktop top bar */}
      <div className="hidden md:block bg-[#1A1A1A] text-white py-2 px-4 text-xs">
        <div className="max-w-[1400px] mx-auto flex justify-between items-center">
          <div className="flex items-center gap-4">
            <span>Free Shipping on orders over $100</span>
            <span className="hidden md:inline">|</span>
            <span className="hidden md:inline">30-Day Easy Returns</span>
          </div>
          <div className="flex gap-4">
            <button className="hover:opacity-80 transition" onClick={() => onNavigate('help')}>Help</button>
            {customerUser
              ? <button className="hover:opacity-80 transition font-semibold" onClick={() => onCustomerLogout?.()}>{customerUser.name.split(' ')[0]} (Logout)</button>
              : <button className="hover:opacity-80 transition" onClick={() => onOpenAuth?.('login')}>Sign In</button>}
          </div>
        </div>
      </div>
      <div className="hidden md:block sticky top-0 z-40 bg-white shadow-sm border-b">
        <div className="max-w-[1400px] mx-auto px-4 py-4">
          <div className="flex items-center justify-between gap-4">
            <button className="md:hidden p-2" onClick={() => setMobileMenuOpen(!mobileMenuOpen)}>
              {mobileMenuOpen ? <X size={24} /> : <Menu size={24} />}
            </button>
            <div className="flex-shrink-0 cursor-pointer" onClick={() => onNavigate('home')}>
              {logo ? (
                <img src={logo} alt={settings?.siteName || 'shophyfast'} className="max-h-12 object-contain" />
              ) : (
                <div className="text-2xl font-bold tracking-tight">
                  <span className="text-[#1A1A1A]">{settings?.siteName ? settings.siteName.split(' ')[0] : 'shophyfast'}</span>
                  <span className="text-gray-400">{settings?.siteName && settings.siteName.split(' ').length > 1 ? '|' + settings.siteName.split(' ').slice(1).join(' ') : ''}</span>
                </div>
              )}
            </div>
            <div className="hidden md:flex items-center gap-8">
              {NAV_ITEMS.map((item, idx) => (
                <button 
                  key={idx} 
                  className={`flex items-center gap-1 text-sm font-medium transition whitespace-nowrap ${
                    item.highlight ? 'text-red-500 hover:text-red-600' : 'text-gray-700 hover:text-[#1A1A1A]'
                  }`}
                  onClick={() => onNavigate('shop')}
                >
                  {item.name}
                  {item.hasDropdown && <ChevronDown size={14} />}
                </button>
              ))}
              {getActiveCustomPages(settings, '05').length > 0 && (
                <div className="relative group">
                  <button className="flex items-center gap-1 text-sm font-medium text-gray-700 hover:text-[#1A1A1A] transition whitespace-nowrap">
                    Pages <ChevronDown size={14} />
                  </button>
                  <div className="absolute top-full left-0 mt-2 w-48 bg-white border border-gray-100 rounded-xl shadow-lg opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-300 z-50 flex flex-col py-2">
                    {getActiveCustomPages(settings, '05').map(page => (
                      <button 
                        key={page.id} 
                        className="text-left px-4 py-2 hover:bg-slate-50 hover:text-[#1A1A1A] transition text-sm font-medium text-slate-700"
                        onClick={() => onNavigate(`page/${page.slug}`)}
                      >
                        {page.title}
                      </button>
                    ))}
                  </div>
                </div>
              )}
            </div>
            <div className="flex items-center gap-5">
              <button className="hidden md:block text-gray-600 hover:text-[#1A1A1A] transition">
                <Search size={20} />
              </button>
              <button className="relative text-gray-600 hover:text-[#1A1A1A] transition">
                <Heart size={20} />
                <span className="absolute -top-2 -right-2 bg-[#1A1A1A] text-white text-[10px] font-bold rounded-full w-4 h-4 flex items-center justify-center">{wishlistCount}</span>
              </button>
              <button className="relative text-gray-600 hover:text-[#1A1A1A] transition" onClick={onCartClick}>
                <ShoppingBag size={20} />
                <span className="absolute -top-2 -right-2 bg-[#1A1A1A] text-white text-[10px] font-bold rounded-full w-4 h-4 flex items-center justify-center">{cartCount}</span>
              </button>
              <UserButton customerUser={customerUser} onOpenAuth={onOpenAuth} onCustomerLogout={onCustomerLogout} accentColor="#1A1A1A" />
            </div>
          </div>
          {mobileMenuOpen && (
            <div className="md:hidden mt-4 pb-4 border-t pt-4">
              <div className="flex flex-col gap-3">
                {NAV_ITEMS.map((item, idx) => (
                  <button key={idx} className={`text-left py-2 text-sm font-medium ${item.highlight ? 'text-red-500' : 'text-gray-700'}`} onClick={() => { onNavigate('shop'); setMobileMenuOpen(false); }}>
                    {item.name}
                  </button>
                ))}
                {getActiveCustomPages(settings, '05').map(page => (
                  <button key={'mob-'+page.id} className="text-left py-2 text-sm font-medium text-gray-700" onClick={() => { onNavigate(`page/${page.slug}`); setMobileMenuOpen(false); }}>
                    {page.title}
                  </button>
                ))}
                <button className="text-left py-2 text-sm text-gray-700" onClick={() => onNavigate('login')}>Sign In</button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

// ------------------------------------
// Global Export
// ------------------------------------
export const GlobalThemeHeader: React.FC<GlobalHeaderProps> = (props) => {
  const theme = props.theme || '01';
  switch (theme) {
    case '02': return <ThemeHeader02 {...props} />;
    case '03': return <ThemeHeader03 {...props} />;
    case '04': return <ThemeHeader04 {...props} />;
    case '05': return <ThemeHeader05 {...props} />;
    case '01':
    default: return <ThemeHeader01 {...props} />;
  }
};
