// Shared components: Icons, Header, Footer, ProductCard
const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ─────── Icons ───────
const Icon = {
  Search: ({ size = 18 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>
    </svg>
  ),
  Heart: ({ size = 20, filled = false }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={filled ? "currentColor" : "none"} stroke="currentColor" strokeWidth="1.5">
      <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
    </svg>
  ),
  Bag: ({ size = 18 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <path d="M6 2L3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"/>
      <line x1="3" y1="6" x2="21" y2="6"/><path d="M16 10a4 4 0 0 1-8 0"/>
    </svg>
  ),
  Menu: ({ size = 22 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <line x1="4" y1="8" x2="20" y2="8"/><line x1="4" y1="16" x2="20" y2="16"/>
    </svg>
  ),
  X: ({ size = 22 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <line x1="6" y1="6" x2="18" y2="18"/><line x1="18" y1="6" x2="6" y2="18"/>
    </svg>
  ),
  Whatsapp: ({ size = 20 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor">
      <path d="M17.5 14.4c-.3-.1-1.7-.8-2-.9-.3-.1-.5-.1-.7.1-.2.3-.7.9-.9 1.1-.2.2-.3.2-.6.1-.3-.1-1.2-.5-2.3-1.4-.8-.7-1.4-1.6-1.6-1.9-.2-.3 0-.4.1-.6.1-.1.3-.3.4-.5.1-.2.2-.3.3-.5.1-.2 0-.4 0-.5 0-.1-.7-1.6-.9-2.2-.2-.6-.5-.5-.7-.5-.2 0-.4 0-.6 0-.2 0-.5.1-.8.4-.3.3-1.1 1.1-1.1 2.7 0 1.6 1.1 3.1 1.3 3.3.2.2 2.2 3.4 5.3 4.7.7.3 1.3.5 1.8.6.7.2 1.4.2 2 .1.6-.1 1.7-.7 2-1.4.2-.7.2-1.2.2-1.4-.1-.2-.3-.3-.6-.4zM12 2C6.5 2 2 6.5 2 12c0 1.8.5 3.5 1.3 5L2 22l5.2-1.3c1.4.8 3 1.3 4.8 1.3 5.5 0 10-4.5 10-10S17.5 2 12 2zm0 18.3c-1.5 0-3-.4-4.3-1.2l-.3-.2-3.2.8.9-3.1-.2-.3c-.9-1.4-1.3-3-1.3-4.6 0-4.6 3.7-8.3 8.3-8.3 4.6 0 8.3 3.7 8.3 8.3.1 4.6-3.6 8.6-8.2 8.6z"/>
    </svg>
  ),
  Instagram: ({ size = 20 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <rect x="3" y="3" width="18" height="18" rx="5"/>
      <circle cx="12" cy="12" r="4"/>
      <circle cx="17.5" cy="6.5" r="0.8" fill="currentColor"/>
    </svg>
  ),
  Mail: ({ size = 20 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <rect x="3" y="5" width="18" height="14" rx="1"/>
      <path d="m3 7 9 6 9-6"/>
    </svg>
  ),
  Arrow: ({ size = 16 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/>
    </svg>
  ),
  ChevronDown: ({ size = 14 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <polyline points="6 9 12 15 18 9"/>
    </svg>
  ),
};

// ─────── Helpers ───────
const fmtPrice = (n, lang) => {
  const num = new Intl.NumberFormat(lang === 'ar' ? 'ar-IQ' : 'en-US').format(n);
  const cur = lang === 'ar' ? 'د.ع' : 'IQD';
  return lang === 'ar' ? `${num} ${cur}` : `${num} ${cur}`;
};

const waUrl = (msg) => `https://wa.me/${window.WA_NUMBER || '9647700000000'}?text=${encodeURIComponent(msg)}`;

// ─────── Toast ───────
function useToast() {
  const [msg, setMsg] = useState(null);
  const show = (m) => {
    setMsg(m);
    clearTimeout(window._tt);
    window._tt = setTimeout(() => setMsg(null), 1800);
  };
  const node = msg ? <div className={`toast show`}>{msg}</div> : null;
  return [node, show];
}

// ─────── Reveal hook ───────
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) e.target.classList.add('in'); });
    }, { threshold: 0.1 });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  });
}

// ─────── Header ───────
function Header({ lang, setLang, page, navigate, wishlistCount, onMenu }) {
  const [scrolled, setScrolled] = useState(false);
  const t = I18N[lang];
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 10);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <>
      <div className="announce">
        <div className="announce-track">
          {[...t.announce, ...t.announce].map((a, i) => (
            <span className="announce-item" key={i}>{a}</span>
          ))}
        </div>
      </div>
      <header className={`header ${scrolled ? 'scrolled' : ''}`}>
        <div className="container">
          <nav className="nav">
            <div className="nav-links">
              <a className={page === 'home' ? 'active' : ''} onClick={() => navigate('home')}>{t.nav.home}</a>
              <a className={page === 'shop' ? 'active' : ''} onClick={() => navigate('shop')}>{t.nav.shop}</a>
              <a className={page === 'about' ? 'active' : ''} onClick={() => navigate('about')}>{t.nav.about}</a>
              <a className={page === 'contact' ? 'active' : ''} onClick={() => navigate('contact')}>{t.nav.contact}</a>
            </div>
            <button className="menu-toggle icon-btn" onClick={onMenu} aria-label="menu"><Icon.Menu/></button>
            <a className="brand" onClick={() => navigate('home')} style={{cursor:'pointer'}}>
              <img src="assets/logo-dark.png" alt="Hillo Banat"/>
              <span className="brand-name">Hillo<span className="it"> banat</span></span>
            </a>
            <div className="nav-actions">
              <button className="lang-switch" onClick={() => setLang(lang === 'ar' ? 'en' : 'ar')}>
                {lang === 'ar' ? 'EN' : 'ع'}
              </button>
              <button className="icon-btn" onClick={() => navigate('shop')} aria-label="search"><Icon.Search/></button>
              <button className="icon-btn" onClick={() => navigate('wishlist')} aria-label="wishlist">
                <Icon.Heart size={18}/>
                {wishlistCount > 0 && <span className="badge">{wishlistCount}</span>}
              </button>
            </div>
          </nav>
        </div>
      </header>
    </>
  );
}

// ─────── Mobile drawer ───────
function MobileDrawer({ open, onClose, lang, setLang, navigate }) {
  const t = I18N[lang];
  const go = (p) => { onClose(); navigate(p); };
  return (
    <>
      <div className={`drawer-overlay ${open ? 'open' : ''}`} onClick={onClose}/>
      <aside className={`drawer ${open ? 'open' : ''}`}>
        <div className="drawer-head">
          <span className="brand-name" style={{fontSize:'18px'}}>Hillo<span className="it"> banat</span></span>
          <button className="icon-btn" onClick={onClose}><Icon.X/></button>
        </div>
        <div className="drawer-links">
          <a onClick={() => go('home')}>{t.nav.home}</a>
          <a onClick={() => go('shop')}>{t.nav.shop}</a>
          <a onClick={() => go('about')}>{t.nav.about}</a>
          <a onClick={() => go('contact')}>{t.nav.contact}</a>
          <a onClick={() => go('wishlist')}>{t.nav.wishlist}</a>
        </div>
        <div className="drawer-foot">
          <button className="lang-switch in-drawer" onClick={() => setLang(lang === 'ar' ? 'en' : 'ar')} style={{alignSelf:'flex-start'}}>
            {lang === 'ar' ? 'English' : 'العربية'}
          </button>
        </div>
      </aside>
    </>
  );
}

// ─────── Footer ───────
function Footer({ lang, navigate }) {
  const t = I18N[lang];
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div className="footer-brand">
            <img src="assets/logo-white.png" alt=""/>
            <div className="footer-brand-name">Hillo<span style={{fontStyle:'italic',letterSpacing:0,textTransform:'none',fontFamily:'Cormorant Infant'}}> banat</span></div>
            <p>{t.footer.tagline}</p>
          </div>
          <div>
            <h4>{t.footer.shop}</h4>
            <ul>
              {CATEGORIES.slice(0, 5).map(c => (
                <li key={c.id}><a onClick={() => navigate('shop', { cat: c.id })}>{c[lang]}</a></li>
              ))}
            </ul>
          </div>
          <div>
            <h4>{t.footer.help}</h4>
            <ul>
              <li><a>{t.footer.links.size}</a></li>
              <li><a>{t.footer.links.shipping}</a></li>
              <li><a>{t.footer.links.returns}</a></li>
              <li><a>{t.footer.links.faq}</a></li>
              <li><a onClick={() => navigate('contact')}>{t.nav.contact}</a></li>
            </ul>
          </div>
          <div>
            <h4>{t.footer.follow}</h4>
            <ul>
              <li><a href={`https://instagram.com/${window.IG_HANDLE || 'hallo.banat'}`} target="_blank" rel="noreferrer">Instagram @{window.IG_HANDLE || 'hallo.banat'}</a></li>
              <li><a href={waUrl('مرحباً، أرغب بالاستفسار')} target="_blank" rel="noreferrer">WhatsApp</a></li>
              <li><a>TikTok</a></li>
              <li><a href={`mailto:${window.SITE_SETTINGS?.email || 'info@hillobanat.com'}`}>{window.SITE_SETTINGS?.email || 'info@hillobanat.com'}</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>{t.footer.rights}</span>
          <span style={{fontStyle:'italic',opacity:0.6}}>Made with love</span>
        </div>
      </div>
    </footer>
  );
}

// ─────── Product Card ───────
function ProductCard({ product, lang, variant = 'classic', onClick, wishlist, toggleWish, onWaOrder }) {
  const t = I18N[lang];
  const isWished = wishlist.includes(product.id);
  return (
    <div className={`pcard style-${variant}`} onClick={() => onClick(product)}>
      <div className="pcard-media">
        <img src={product.cover} alt={product.name[lang]} className="main-img" loading="lazy"/>
        <img src={product.hover} alt="" className="hover-img" loading="lazy"/>
        <div className="pcard-badges">
          {product.isNew && <span className="pbadge new">{lang === 'ar' ? 'جديد' : 'New'}</span>}
          {product.oldPrice && <span className="pbadge sale">{lang === 'ar' ? 'تخفيض' : 'Sale'}</span>}
        </div>
        <button
          className={`pcard-wish ${isWished ? 'active' : ''}`}
          onClick={(e) => { e.stopPropagation(); toggleWish(product.id); }}
          aria-label="wishlist"
        >
          <Icon.Heart filled={isWished}/>
        </button>
        <div className="pcard-quick" onClick={(e) => { e.stopPropagation(); onWaOrder(product); }}>
          {t.product.addToCart}
        </div>
      </div>
      {variant !== 'minimal' && (
        <div className="pcard-swatches">
          {product.colors.slice(0, 4).map((c, i) => (
            <span key={i} className="pcard-swatch" style={{background: c.hex}}/>
          ))}
        </div>
      )}
      <div className="pcard-info">
        <div>
          <div className="name">{product.name[lang]}</div>
          <div className="meta">{CATEGORIES.find(c => c.id === product.category)?.[lang]}</div>
        </div>
        <div className="price">
          {product.oldPrice && <span className="old">{fmtPrice(product.oldPrice, lang)}</span>}
          <span className={`now ${product.oldPrice ? 'sale' : ''}`}>{fmtPrice(product.price, lang)}</span>
        </div>
      </div>
    </div>
  );
}

// ─────── Floating WhatsApp button ───────
function FloatingWA({ lang }) {
  const msg = lang === 'ar' ? 'مرحباً، أرغب بالاستفسار عن منتجاتكم' : 'Hi, I want to ask about your products';
  return (
    <a className="fab-wa" href={waUrl(msg)} target="_blank" rel="noreferrer" aria-label="WhatsApp">
      <Icon.Whatsapp size={28}/>
    </a>
  );
}

Object.assign(window, {
  Icon, fmtPrice, waUrl, useToast, useReveal,
  Header, MobileDrawer, Footer, ProductCard, FloatingWA,
});
