/* Shared UI primitives for CiaoItalia prototype */

const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;

// =====================================================
// App context: route, device, theme, cart
// =====================================================
const AppCtx = createContext(null);
const useApp = () => useContext(AppCtx);

function AppProvider({ children }) {
  const [route, setRoute] = useState('home');
  const [routeParams, setRouteParams] = useState({});
  const [cartOpen, setCartOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [cart, setCart] = useState([
    { id: 'agv-pista-gp-rr', name: 'AGV Pista GP RR', variant: 'Mono Carbon · M', price: 34990, qty: 1, sku: 'AGV-PGP-CB-M' },
    { id: 'dainese-racing-4', name: 'Dainese Racing 4', variant: 'Negro/Rojo · 52', price: 18490, qty: 1, sku: 'DAI-RC4-BR-52' },
  ]);

  const go = (r, params = {}) => { setRoute(r); setRouteParams(params); window.scrollTo(0, 0); };
  const addToCart = (item) => setCart(c => {
    const ex = c.find(x => x.id === item.id && x.variant === item.variant);
    if (ex) return c.map(x => x === ex ? { ...x, qty: x.qty + 1 } : x);
    return [...c, { ...item, qty: 1 }];
  });
  const removeFromCart = (id, variant) => setCart(c => c.filter(x => !(x.id === id && x.variant === variant)));
  const updateQty = (id, variant, qty) => setCart(c => c.map(x => (x.id === id && x.variant === variant) ? { ...x, qty: Math.max(1, qty) } : x));

  return (
    <AppCtx.Provider value={{
      route, routeParams, go,
      cartOpen, setCartOpen,
      searchOpen, setSearchOpen,
      menuOpen, setMenuOpen,
      cart, addToCart, removeFromCart, updateQty,
    }}>
      {children}
    </AppCtx.Provider>
  );
}

// =====================================================
// Logo (recreates the ciao italia sailboat mark, original)
// =====================================================
function Logo({ size = 24, mono = false, wordmark = true }) {
  const gr = mono ? 'currentColor' : 'var(--it-green)';
  const rd = mono ? 'currentColor' : 'var(--it-red)';
  const ink = 'currentColor';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10, color: 'var(--ink)' }}>
      <svg viewBox="0 0 44 40" width={size * 1.8} height={size * 1.65} aria-hidden>
        {/* three sails — abstract boat silhouette */}
        <path d="M4 34 L14 4 L14 34 Z" fill={gr} opacity={mono ? 0.9 : 1}/>
        <path d="M16 34 L26 8 L26 34 Z" fill={mono ? 'none' : 'var(--bg)'} stroke={ink} strokeWidth="1"/>
        <path d="M28 34 L38 12 L38 34 Z" fill={rd} opacity={mono ? 0.9 : 1}/>
        <rect x="2" y="34" width="40" height="1.5" fill={ink}/>
      </svg>
      {wordmark && (
        <span style={{
          fontFamily: 'var(--font-display)',
          fontSize: size,
          fontWeight: 500,
          letterSpacing: '-0.01em',
          fontStyle: 'italic',
          lineHeight: 1,
        }}>ciao italia</span>
      )}
    </div>
  );
}

// =====================================================
// Placeholder image
// =====================================================
function PH({ label, tag, ratio = '1/1', style = {}, children, tall }) {
  const st = {
    aspectRatio: tall ? undefined : ratio,
    height: tall || undefined,
    width: '100%',
    ...style,
  };
  return (
    <div className="ph" style={st}>
      {tag && <span className="ph-tag">◇ {tag}</span>}
      {label && <span className="ph-label">{label}</span>}
      {children}
    </div>
  );
}

// =====================================================
// Price formatter (MXN)
// =====================================================
const fmtMXN = (n) => '$' + n.toLocaleString('es-MX', { minimumFractionDigits: 0 });

// =====================================================
// Announcement bar
// =====================================================
function AnnouncementBar() {
  const msgs = [
    'Envío gratis en pedidos superiores a $2,500 MXN',
    'Hasta 12 MSI con tarjetas participantes',
    'Boutique CDMX · Polanco — Lun a Sáb 11:00–20:00',
  ];
  const [i, setI] = useState(0);
  useEffect(() => { const t = setInterval(() => setI(x => (x + 1) % msgs.length), 4500); return () => clearInterval(t); }, []);
  return (
    <div style={{
      background: 'var(--ink)', color: 'var(--bg)',
      padding: '8px 24px', textAlign: 'center',
      fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase',
      position: 'relative', overflow: 'hidden',
    }}>
      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 16 }}>
        <span className="tricolor" style={{ gap: 1 }}>
          <span style={{ width: 4, height: 10 }}></span><span style={{ width: 4, height: 10, background: 'var(--bg)' }}></span><span style={{ width: 4, height: 10 }}></span>
        </span>
        {msgs[i]}
      </span>
    </div>
  );
}

// =====================================================
// Header
// =====================================================
function Header({ mobile }) {
  const { go, route, cart, setCartOpen, setSearchOpen, setMenuOpen } = useApp();
  const cartCount = cart.reduce((a, b) => a + b.qty, 0);

  const NavLink = ({ to, children, active }) => (
    <button onClick={() => go(to)} className="nav-link" style={{
      fontFamily: 'var(--font-sans)',
      fontSize: 13,
      fontWeight: 500,
      letterSpacing: '0.04em',
      textTransform: 'uppercase',
      color: active ? 'var(--ink)' : 'var(--ink-2)',
      padding: '8px 0',
      position: 'relative',
    }}>
      {children}
      {active && <span style={{ position: 'absolute', bottom: -2, left: 0, right: 0, height: 1, background: 'var(--ink)' }}/>}
    </button>
  );

  if (mobile) {
    return (
      <header style={{ position: 'sticky', top: 0, zIndex: 50, background: 'var(--bg)', borderBottom: '1px solid var(--rule)' }}>
        <AnnouncementBar />
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 16px' }}>
          <button onClick={() => setMenuOpen(true)} aria-label="Menu">
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M3 6h18M3 12h18M3 18h18"/></svg>
          </button>
          <button onClick={() => go('home')}><Logo size={18}/></button>
          <div style={{ display: 'flex', gap: 14 }}>
            <button onClick={() => setSearchOpen(true)} aria-label="Search">
              <svg width="20" height="20" 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>
            </button>
            <button onClick={() => setCartOpen(true)} aria-label="Cart" style={{ position: 'relative' }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M4 7h16l-1.5 12a2 2 0 0 1-2 1.8H7.5a2 2 0 0 1-2-1.8L4 7Z"/><path d="M9 7V5a3 3 0 0 1 6 0v2"/></svg>
              {cartCount > 0 && <span style={{ position: 'absolute', top: -4, right: -6, background: 'var(--it-red)', color: 'white', fontSize: 9, fontFamily: 'var(--font-mono)', padding: '1px 5px', borderRadius: 8, minWidth: 14, textAlign: 'center' }}>{cartCount}</span>}
            </button>
          </div>
        </div>
      </header>
    );
  }

  return (
    <header style={{ position: 'sticky', top: 0, zIndex: 50, background: 'var(--bg)' }}>
      <AnnouncementBar />
      <div style={{ borderBottom: '1px solid var(--rule)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center', padding: '18px 40px', gap: 32 }}>
          <nav style={{ display: 'flex', gap: 28 }}>
            <NavLink to="collection" active={route === 'collection'}>Moto</NavLink>
            <NavLink to="collection" active={false}>Ciclismo</NavLink>
            <NavLink to="collection" active={false}>Marcas</NavLink>
            <NavLink to="brand" active={route === 'brand'}>Editorial</NavLink>
          </nav>
          <button onClick={() => go('home')} style={{ justifySelf: 'center' }}>
            <Logo size={22}/>
          </button>
          <div style={{ display: 'flex', gap: 22, justifyContent: 'flex-end', alignItems: 'center' }}>
            <button onClick={() => setSearchOpen(true)} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--ink-2)' }}>
              <svg width="18" height="18" 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>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase' }}>Buscar</span>
            </button>
            <button style={{ color: 'var(--ink-2)' }} aria-label="Account">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/></svg>
            </button>
            <button onClick={() => setCartOpen(true)} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M4 7h16l-1.5 12a2 2 0 0 1-2 1.8H7.5a2 2 0 0 1-2-1.8L4 7Z"/><path d="M9 7V5a3 3 0 0 1 6 0v2"/></svg>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.1em' }}>({cartCount})</span>
            </button>
          </div>
        </div>
      </div>
    </header>
  );
}

// =====================================================
// Footer
// =====================================================
function Footer() {
  const col = (title, items) => (
    <div>
      <div className="eyebrow" style={{ marginBottom: 16 }}>{title}</div>
      <ul style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {items.map(x => <li key={x}><a style={{ fontSize: 13, color: 'var(--ink-2)' }} href="#">{x}</a></li>)}
      </ul>
    </div>
  );
  return (
    <footer style={{ background: 'var(--bg-sunk)', borderTop: '1px solid var(--rule)', marginTop: 80 }}>
      <div style={{ padding: '64px 40px 32px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr 1fr', gap: 48, paddingBottom: 56, borderBottom: '1px solid var(--rule)' }}>
          <div>
            <Logo size={22}/>
            <p style={{ marginTop: 20, maxWidth: 340, color: 'var(--ink-2)', fontSize: 14, lineHeight: 1.6 }}>
              Importadora oficial de las mejores marcas italianas de moto y ciclismo en México desde 1998.
            </p>
            <div style={{ marginTop: 24, display: 'flex', alignItems: 'center', gap: 12 }}>
              <div className="tricolor"><span/><span/><span/></div>
              <span className="font-mono" style={{ fontSize: 11, letterSpacing: '0.1em', color: 'var(--ink-3)' }}>MADE IN ITALY · SINCE 1998</span>
            </div>
          </div>
          {col('Tienda', ['Cascos', 'Chamarras', 'Guantes', 'Botas', 'Jerseys', 'Gafas'])}
          {col('Marcas', ['AGV', 'Dainese', 'Rudy Project', 'Sidi', 'Alpinestars', 'Ver todas'])}
          {col('Ayuda', ['Guía de tallas', 'Envíos', 'Devoluciones', 'Contacto', 'Garantía'])}
          {col('Compañía', ['Nosotros', 'Boutiques', 'Editorial', 'Prensa', 'Trabaja con nosotros'])}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr', gap: 32, padding: '32px 0', borderBottom: '1px solid var(--rule)', alignItems: 'end' }}>
          <div>
            <div className="font-display" style={{ fontSize: 28, fontStyle: 'italic', letterSpacing: '-0.01em' }}>Il Giornale</div>
            <p style={{ color: 'var(--ink-2)', fontSize: 13, marginTop: 8 }}>Editorial, lanzamientos y acceso anticipado a la newsletter.</p>
          </div>
          <div style={{ gridColumn: 'span 2', display: 'flex', gap: 0, borderBottom: '1px solid var(--ink)' }}>
            <input placeholder="tu@email.com" style={{ flex: 1, padding: '12px 0', border: 0, background: 'transparent', outline: 'none', fontSize: 14 }}/>
            <button className="btn btn-ghost" style={{ padding: '8px 0' }}>Suscribirme →</button>
          </div>
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 32, fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>
          <span>© 2026 CIAO ITALIA · CDMX</span>
          <div style={{ display: 'flex', gap: 20 }}>
            <a href="#">PRIVACIDAD</a>
            <a href="#">TÉRMINOS</a>
            <a href="#">COOKIES</a>
            <a href="#">INSTAGRAM</a>
          </div>
        </div>
      </div>
    </footer>
  );
}

// =====================================================
// Product Card
// =====================================================
function ProductCard({ product, mobile }) {
  const { go } = useApp();
  const [hover, setHover] = useState(false);
  return (
    <button
      onClick={() => go('pdp', { id: product.id })}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{ textAlign: 'left', display: 'block', width: '100%' }}
    >
      <div style={{ position: 'relative', background: 'var(--bg-sunk)', overflow: 'hidden' }}>
        <PH ratio="4/5" tag={product.brand} label={product.category} style={{ border: 0, transition: 'transform 500ms ease', transform: hover ? 'scale(1.03)' : 'scale(1)' }}/>
        {product.tag && (
          <span style={{
            position: 'absolute', top: 12, right: 12, background: 'var(--bg)', color: 'var(--ink)',
            fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.1em', padding: '4px 8px',
            textTransform: 'uppercase',
          }}>{product.tag}</span>
        )}
        {product.colors && (
          <div style={{ position: 'absolute', bottom: 12, left: 12, display: 'flex', gap: 4, opacity: hover ? 1 : 0, transition: 'opacity 200ms' }}>
            {product.colors.map((c, i) => (
              <span key={i} style={{ width: 14, height: 14, borderRadius: '50%', background: c, border: '1px solid var(--rule)' }}/>
            ))}
          </div>
        )}
      </div>
      <div style={{ paddingTop: 14, display: 'flex', justifyContent: 'space-between', gap: 8 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="eyebrow" style={{ fontSize: 10, marginBottom: 4 }}>{product.brand}</div>
          <div style={{ fontFamily: 'var(--font-serif)', fontSize: mobile ? 16 : 18, lineHeight: 1.2, marginBottom: 2, fontWeight: 500 }}>{product.name}</div>
          {product.subtitle && <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{product.subtitle}</div>}
        </div>
        <div style={{ textAlign: 'right', flexShrink: 0 }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13 }}>{fmtMXN(product.price)}</div>
          {product.oldPrice && <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ink-3)', textDecoration: 'line-through' }}>{fmtMXN(product.oldPrice)}</div>}
        </div>
      </div>
    </button>
  );
}

// =====================================================
// Cart Drawer
// =====================================================
function CartDrawer() {
  const { cartOpen, setCartOpen, cart, removeFromCart, updateQty, go } = useApp();
  const subtotal = cart.reduce((a, b) => a + b.price * b.qty, 0);
  return (
    <>
      <div onClick={() => setCartOpen(false)} style={{
        position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.3)',
        opacity: cartOpen ? 1 : 0, pointerEvents: cartOpen ? 'auto' : 'none',
        transition: 'opacity 200ms', zIndex: 100,
      }}/>
      <aside style={{
        position: 'fixed', top: 0, right: 0, bottom: 0, width: 440, maxWidth: '100vw',
        background: 'var(--bg)', zIndex: 101,
        transform: cartOpen ? 'translateX(0)' : 'translateX(100%)',
        transition: 'transform 300ms cubic-bezier(.2,.7,.2,1)',
        display: 'flex', flexDirection: 'column',
        boxShadow: '-20px 0 60px rgba(0,0,0,0.1)',
      }}>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--rule)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
            <span className="font-display" style={{ fontSize: 22, fontStyle: 'italic' }}>Il Carrello</span>
            <span className="font-mono" style={{ fontSize: 11, color: 'var(--ink-3)', letterSpacing: '0.1em' }}>({cart.length} ARTÍCULOS)</span>
          </div>
          <button onClick={() => setCartOpen(false)} aria-label="Close">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"><path d="M6 6l12 12M18 6L6 18"/></svg>
          </button>
        </div>

        <div style={{ flex: 1, overflow: 'auto', padding: '8px 24px' }}>
          {cart.length === 0 && (
            <div style={{ padding: '60px 0', textAlign: 'center', color: 'var(--ink-3)' }}>
              <div className="font-display" style={{ fontSize: 22, fontStyle: 'italic', marginBottom: 8, color: 'var(--ink)' }}>Tu carrito está vacío</div>
              <div style={{ fontSize: 13 }}>Explora nuestra colección</div>
            </div>
          )}
          {cart.map((it, i) => (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '88px 1fr', gap: 16, padding: '20px 0', borderBottom: '1px solid var(--rule)' }}>
              <PH ratio="4/5" tag="" label="" style={{ border: '1px solid var(--rule)' }}/>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                <div className="eyebrow" style={{ fontSize: 9 }}>{it.sku}</div>
                <div style={{ fontFamily: 'var(--font-serif)', fontSize: 16, fontWeight: 500 }}>{it.name}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{it.variant}</div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginTop: 8 }}>
                  <div style={{ display: 'flex', border: '1px solid var(--rule)' }}>
                    <button onClick={() => updateQty(it.id, it.variant, it.qty - 1)} style={{ padding: '4px 10px', fontSize: 14 }}>−</button>
                    <span style={{ padding: '4px 12px', fontFamily: 'var(--font-mono)', fontSize: 12, borderLeft: '1px solid var(--rule)', borderRight: '1px solid var(--rule)' }}>{it.qty}</span>
                    <button onClick={() => updateQty(it.id, it.variant, it.qty + 1)} style={{ padding: '4px 10px', fontSize: 14 }}>+</button>
                  </div>
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13 }}>{fmtMXN(it.price * it.qty)}</div>
                </div>
                <button onClick={() => removeFromCart(it.id, it.variant)} style={{ fontSize: 11, color: 'var(--ink-3)', textAlign: 'left', marginTop: 4, textDecoration: 'underline' }}>Eliminar</button>
              </div>
            </div>
          ))}
        </div>

        {cart.length > 0 && (
          <div style={{ padding: 24, borderTop: '1px solid var(--rule)', background: 'var(--bg-sunk)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6, fontSize: 13, color: 'var(--ink-2)' }}>
              <span>Subtotal</span>
              <span className="font-mono">{fmtMXN(subtotal)}</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16, fontSize: 13, color: 'var(--ink-2)' }}>
              <span>Envío</span>
              <span className="font-mono">{subtotal > 2500 ? 'Gratis' : fmtMXN(180)}</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 20, paddingTop: 12, borderTop: '1px solid var(--rule)' }}>
              <span className="font-display" style={{ fontSize: 20, fontStyle: 'italic' }}>Total</span>
              <span className="font-mono" style={{ fontSize: 18 }}>{fmtMXN(subtotal + (subtotal > 2500 ? 0 : 180))}</span>
            </div>
            <button onClick={() => { setCartOpen(false); go('checkout'); }} className="btn btn-primary btn-block btn-lg">Finalizar compra</button>
            <button onClick={() => { setCartOpen(false); go('cart'); }} className="btn btn-ghost btn-block" style={{ marginTop: 8 }}>Ver carrito completo</button>
            <div className="eyebrow" style={{ textAlign: 'center', marginTop: 16, fontSize: 10 }}>
              Hasta 12 MSI · Envío en 24–48 h
            </div>
          </div>
        )}
      </aside>
    </>
  );
}

// =====================================================
// Search Overlay
// =====================================================
function SearchOverlay() {
  const { searchOpen, setSearchOpen, go } = useApp();
  const [q, setQ] = useState('');
  useEffect(() => {
    if (searchOpen) {
      const t = setTimeout(() => document.getElementById('search-input')?.focus(), 100);
      return () => clearTimeout(t);
    }
  }, [searchOpen]);

  const trending = ['AGV Pista GP RR', 'Dainese Racing', 'Guantes ciclismo', 'Casco integral', 'Sidi Wire 2'];
  const suggestions = q ? [
    { brand: 'AGV', name: `${q} · K6 S`, price: 14990 },
    { brand: 'Dainese', name: `${q} · Racing 4`, price: 18490 },
    { brand: 'Rudy Project', name: `${q} · Cutline`, price: 5290 },
  ] : [];

  return (
    <>
      <div onClick={() => setSearchOpen(false)} style={{
        position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.3)',
        opacity: searchOpen ? 1 : 0, pointerEvents: searchOpen ? 'auto' : 'none',
        transition: 'opacity 200ms', zIndex: 100,
      }}/>
      <div style={{
        position: 'fixed', top: 0, left: 0, right: 0, background: 'var(--bg)', zIndex: 101,
        transform: searchOpen ? 'translateY(0)' : 'translateY(-100%)',
        transition: 'transform 300ms cubic-bezier(.2,.7,.2,1)',
        boxShadow: '0 20px 60px rgba(0,0,0,0.08)',
      }}>
        <div style={{ padding: '24px 40px', borderBottom: '1px solid var(--rule)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <svg width="22" height="22" 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>
            <input id="search-input" value={q} onChange={e => setQ(e.target.value)} placeholder="Buscar cascos, jerseys, marcas…" style={{
              flex: 1, border: 0, background: 'transparent', outline: 'none',
              fontFamily: 'var(--font-display)', fontSize: 32, fontStyle: 'italic',
            }}/>
            <button onClick={() => setSearchOpen(false)} className="eyebrow">ESC ✕</button>
          </div>
        </div>
        <div style={{ padding: '32px 40px 48px', maxHeight: '70vh', overflow: 'auto' }}>
          {!q && (
            <>
              <div className="eyebrow" style={{ marginBottom: 16 }}>Tendencias</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {trending.map(t => (
                  <button key={t} onClick={() => setQ(t)} style={{ padding: '8px 14px', border: '1px solid var(--rule)', fontSize: 13, borderRadius: 2 }}>{t}</button>
                ))}
              </div>
            </>
          )}
          {q && (
            <>
              <div className="eyebrow" style={{ marginBottom: 16 }}>{suggestions.length} resultados</div>
              <div style={{ display: 'grid', gap: 0 }}>
                {suggestions.map((s, i) => (
                  <button key={i} onClick={() => { setSearchOpen(false); go('pdp', { id: 's' + i }); }} style={{
                    display: 'grid', gridTemplateColumns: '60px 1fr auto', gap: 16, alignItems: 'center',
                    padding: '14px 0', borderBottom: '1px solid var(--rule)', textAlign: 'left',
                  }}>
                    <PH ratio="1/1" style={{ border: '1px solid var(--rule)' }}/>
                    <div>
                      <div className="eyebrow" style={{ fontSize: 9 }}>{s.brand}</div>
                      <div style={{ fontFamily: 'var(--font-serif)', fontSize: 16 }}>{s.name}</div>
                    </div>
                    <div className="font-mono" style={{ fontSize: 13 }}>{fmtMXN(s.price)}</div>
                  </button>
                ))}
              </div>
            </>
          )}
        </div>
      </div>
    </>
  );
}

// =====================================================
// Export to window
// =====================================================
Object.assign(window, {
  AppCtx, useApp, AppProvider, Logo, PH, fmtMXN,
  AnnouncementBar, Header, Footer, ProductCard, CartDrawer, SearchOverlay,
});
