// Reusable components — Pop Retail (Arcade)
const P = window.POP;

function StarBurst({ size = 80, fill = P.yellow, text, rotate = 0, spin = true }) {
  return (
    <div style={{ width: size, height: size, position: 'relative',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      transform: `rotate(${rotate}deg)` }}>
      <svg viewBox="0 0 100 100" className={spin ? 'pop-spin' : ''}
        style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
        <polygon fill={fill} stroke={P.ink} strokeWidth="2"
          points="50,0 60,30 92,18 75,46 100,55 70,62 88,90 58,72 50,100 42,72 12,90 30,62 0,55 25,46 8,18 40,30" />
      </svg>
      <div style={{ position: 'relative', color: P.ink, fontFamily: P.display, fontSize: size / 5.5,
        textAlign: 'center', lineHeight: 1, letterSpacing: -0.5, textTransform: 'uppercase',
        whiteSpace: 'pre-line', padding: size * 0.12 }}>{text}</div>
    </div>
  );
}

function PopButton({ children, variant = 'primary', size = 'md', onClick, style: extraStyle = {}, full = false, icon }) {
  const variants = {
    primary:   { bg: P.yellow, fg: P.ink },
    secondary: { bg: P.card,   fg: P.ink },
    danger:    { bg: P.red,    fg: P.card },
    success:   { bg: P.green,  fg: P.card },
    dark:      { bg: P.ink,    fg: '#ffffff' },
    blue:      { bg: P.blue,   fg: P.card },
  };
  const sizes = {
    sm: { padding: '7px 14px', fontSize: 11, radius: 8,  shadow: 2 },
    md: { padding: '10px 18px', fontSize: 13, radius: 10, shadow: 3 },
    lg: { padding: '14px 26px', fontSize: 15, radius: 12, shadow: 4 },
    xl: { padding: '16px 32px', fontSize: 17, radius: 14, shadow: 5 },
  };
  const v = variants[variant], sz = sizes[size];
  return (
    <button onClick={onClick} className="pop-press" style={{
      background: v.bg, color: v.fg,
      border: `2px solid ${P.ink}`,
      padding: sz.padding, borderRadius: sz.radius,
      fontFamily: P.display, fontSize: sz.fontSize, letterSpacing: 1,
      textTransform: 'uppercase',
      boxShadow: `${sz.shadow}px ${sz.shadow}px 0 ${P.ink}`,
      width: full ? '100%' : 'auto',
      display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      whiteSpace: 'nowrap',
      ...extraStyle,
    }}>
      {icon}{children}
    </button>
  );
}

function PopChip({ children, color = P.yellow, onClick, active = false, size = 'md', style: extraStyle = {} }) {
  const sizes = { sm: '6px 12px', md: '8px 16px', lg: '10px 18px' };
  return (
    <button onClick={onClick} style={{
      background: active ? P.ink : color, color: active ? '#ffffff' : P.ink,
      border: `2px solid ${P.ink}`, borderRadius: 999,
      padding: sizes[size], fontFamily: P.display, fontSize: size === 'sm' ? 11 : 13,
      letterSpacing: 0.5, textTransform: 'uppercase', whiteSpace: 'nowrap',
      boxShadow: active ? `inset 2px 2px 0 rgba(0,0,0,0.25)` : `2px 2px 0 ${P.ink}`,
      transition: 'all .12s', display: 'inline-flex', alignItems: 'center', gap: 6,
      ...extraStyle,
    }}>
      {children}
    </button>
  );
}

function PopBadge({ children, color = P.red, fg = P.card }) {
  return (
    <span style={{
      background: color, color: fg, border: `1.5px solid ${P.ink}`,
      padding: '2px 7px', borderRadius: 999,
      fontFamily: P.display, fontSize: 10, letterSpacing: 0.5,
      display: 'inline-flex', alignItems: 'center', minWidth: 18, justifyContent: 'center',
    }}>{children}</span>
  );
}

function PopRating({ rating = 4.8, count, size = 12 }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: size }}>
      <span style={{ color: '#f5a200' }}>★</span>
      <span style={{ fontWeight: 700 }}>{rating}</span>
      {count && <span style={{ color: P.dim, fontWeight: 400 }}>({count})</span>}
    </div>
  );
}

// Devuelve un color de fondo basado en la categoría del producto
function getCategoryTone(category) {
  const map = {
    'Celulares':      P.blueLight,
    'Laptops':        P.purple,
    'Consolas':       P.orange,
    'Audio':          P.pink,
    'Wearables':      P.green,
    'Tablets':        P.yellow,
    'Componentes':    P.cream2,
    'TV y Monitores': P.blueLight,
    'Cámaras':        P.pink,
    'Accesorios':     P.yellow,
    'Electrohogar':   P.cream2,
  };
  return map[category] || P.cream;
}

function ProductImage({ tone = P.cream, sku, discount, tag, productId, imageUrl }) {
  return (
    <div data-product-img={productId} style={{
      position: 'relative', aspectRatio: '4 / 3', background: tone,
      borderRadius: 8, overflow: 'hidden',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      border: `2px solid ${P.ink}`,
    }}>
      {imageUrl ? (
        <img src={imageUrl} alt={sku || ''} style={{
          width: '100%', height: '100%', objectFit: 'cover',
          position: 'absolute', inset: 0,
        }} onError={e => { e.currentTarget.style.display = 'none'; }} />
      ) : (
        <>
          <div className="pop-stripes" style={{ position: 'absolute', inset: 0 }}></div>
          <div className="pop-dots" style={{ position: 'absolute', inset: 0, opacity: 0.4 }}></div>
          <div style={{
            position: 'relative', fontFamily: 'ui-monospace, monospace',
            fontSize: 11, color: P.dim, letterSpacing: 1,
            background: P.card, padding: '4px 8px', borderRadius: 4, border: `1.5px solid ${P.line}`,
          }}>{sku}</div>
        </>
      )}
      {discount && (
        <div style={{ position: 'absolute', top: -8, right: -8 }}>
          <StarBurst size={56} fill={P.red} text={`-${discount}%`} rotate={8} />
        </div>
      )}
      {tag && !discount && (
        <div style={{ position: 'absolute', top: 10, left: 10, background: P.ink, color: '#ffffff',
          padding: '4px 10px', borderRadius: 4, fontFamily: P.display, fontSize: 11, letterSpacing: 1 }}>{tag}</div>
      )}
    </div>
  );
}

function ProductCard({ product, onClick, onAddToCart, compact = false }) {
  const { id, sku, brand, name, price, oldPrice, discount, tone, tag, rating, ratingCount, image_url, category } = product;
  const resolvedTone = tone || getCategoryTone(category);

  const handleAdd = (e) => {
    e.stopPropagation();
    const imgEl = e.currentTarget.closest('[data-product-card]')?.querySelector('[data-product-img]');
    const cartEl = document.querySelector('[data-cart-target]');
    if (imgEl && cartEl) flyToCart(imgEl, cartEl, resolvedTone);
    onAddToCart && onAddToCart(product);
  };

  return (
    <div data-product-card onClick={onClick} className="pop-lift" style={{
      background: P.card, border: `2px solid ${P.ink}`, borderRadius: 10,
      overflow: 'hidden', display: 'flex', flexDirection: 'column',
      boxShadow: `3px 3px 0 ${P.ink}`, cursor: 'pointer', minWidth: 0, width: '100%',
    }}>
      <div style={{ position: 'relative' }}>
        <ProductImage tone={resolvedTone} sku={sku} discount={discount} tag={tag} productId={id} imageUrl={image_url} />
        <div style={{ position: 'absolute', bottom: 8, right: 8, width: 26, height: 26,
          borderRadius: '50%', background: P.card, border: `1.5px solid ${P.ink}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12,
          boxShadow: `1px 1px 0 ${P.ink}` }}>♡</div>
      </div>
      <div style={{ padding: compact ? 8 : 10, display: 'flex', flexDirection: 'column', gap: 4, minWidth: 0, flex: 1 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 4, minWidth: 0 }}>
          <div style={{ fontSize: 9, color: P.blue, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase',
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', minWidth: 0, flex: 1 }}>{brand}</div>
          {ratingCount > 0 && <PopRating rating={rating} count={ratingCount} size={9} />}
        </div>
        <div style={{ fontSize: 12, color: P.ink, lineHeight: 1.3, fontWeight: 600,
          display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
          minHeight: 'calc(12px * 1.3 * 2)' }}>{name}</div>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, flexWrap: 'wrap', marginTop: 'auto', paddingTop: 2 }}>
          <div style={{ fontFamily: P.display, fontSize: 17, color: P.ink, letterSpacing: -0.5 }}>${price.toLocaleString('es-UY')}</div>
          {oldPrice && <div style={{ fontSize: 10, color: P.dim, textDecoration: 'line-through' }}>${oldPrice.toLocaleString('es-UY')}</div>}
        </div>
        <PopButton variant="primary" size="sm" full onClick={handleAdd} style={{ fontSize: 10, padding: '6px 10px' }}>+ Agregar</PopButton>
      </div>
    </div>
  );
}

function flyToCart(fromEl, toEl, tone) {
  const f = fromEl.getBoundingClientRect();
  const t = toEl.getBoundingClientRect();
  const ghost = document.createElement('div');
  ghost.style.cssText = `
    position:fixed;left:${f.left}px;top:${f.top}px;width:${f.width}px;height:${f.height}px;
    background:${tone || P.cream};border:2px solid ${P.ink};border-radius:12px;
    pointer-events:none;z-index:9999;overflow:hidden;
    --fly-end:translate(${t.left + t.width / 2 - f.left - f.width / 2}px, ${t.top + t.height / 2 - f.top - f.height / 2}px);
  `;
  // Copiar la imagen real del producto si existe
  const srcImg = fromEl.querySelector('img');
  if (srcImg && srcImg.src) {
    const img = document.createElement('img');
    img.src = srcImg.src;
    img.style.cssText = 'width:100%;height:100%;object-fit:cover;position:absolute;inset:0;';
    ghost.appendChild(img);
  }
  ghost.classList.add('pop-fly');
  document.body.appendChild(ghost);
  setTimeout(() => {
    ghost.remove();
    toEl.classList.remove('pop-jiggle');
    void toEl.offsetWidth;
    toEl.classList.add('pop-jiggle');
  }, 850);
}

function QtyStepper({ qty, setQty, min = 1, max = 99, size = 'md' }) {
  const s = size === 'lg' ? { btn: 40, fs: 18, w: 56 } : { btn: 32, fs: 14, w: 44 };
  const click = (delta) => () => setQty(Math.max(min, Math.min(max, qty + delta)));
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center',
      background: P.card, border: `2px solid ${P.ink}`, borderRadius: 10,
      boxShadow: `3px 3px 0 ${P.ink}`, overflow: 'hidden' }}>
      <button onClick={click(-1)} style={{ width: s.btn, height: s.btn, border: 'none',
        background: P.cream, fontFamily: P.display, fontSize: s.fs, borderRight: `2px solid ${P.ink}` }}>−</button>
      <div style={{ width: s.w, textAlign: 'center', fontFamily: P.display, fontSize: s.fs }}>{qty}</div>
      <button onClick={click(1)} style={{ width: s.btn, height: s.btn, border: 'none',
        background: P.cream, fontFamily: P.display, fontSize: s.fs, borderLeft: `2px solid ${P.ink}` }}>+</button>
    </div>
  );
}

function PopHeader({ route, navigate, cartCount, isMobile, onOpenCart, onOpenMenu, onOpenAccount, onOpenSearch, user }) {
  return (
    <>
      {/* Promo strip — marquee */}
      <div style={{ background: P.ink, color: '#ffffff', padding: '8px 0', overflow: 'hidden',
        borderBottom: `2px solid ${P.ink}` }}>
        <div className="pop-marquee" style={{ fontSize: 12, fontWeight: 600, letterSpacing: 0.5 }}>
          {Array.from({ length: 2 }).map((_, k) => (
            <React.Fragment key={k}>
              <span>🚚 ENVÍO GRATIS DESDE $50</span>
              <span>⚡ ENTREGA 24H · MONTEVIDEO</span>
              <span>💳 HASTA 12 CUOTAS</span>
              <span>🎁 HOT WEEK · HASTA -60% EN GAMING</span>
              <span>📞 · MAGIC CELL · 24/7</span>
              <span>🔁 30 DÍAS PARA DEVOLVER</span>
            </React.Fragment>
          ))}
        </div>
      </div>

      {/* Main header */}
      <div style={{
        padding: isMobile ? '12px 16px' : '16px 32px',
        display: 'flex', alignItems: 'center', gap: isMobile ? 10 : 20,
        background: P.bg, borderBottom: `2px solid ${P.ink}`,
        position: 'sticky', top: 0, zIndex: 50,
      }}>
        {isMobile && (
          <button onClick={onOpenMenu} className="pop-press" style={{
            width: 40, height: 40, borderRadius: 10, background: P.card, border: `2px solid ${P.ink}`,
            boxShadow: `2px 2px 0 ${P.ink}`, fontSize: 18,
          }}>☰</button>
        )}

        <div onClick={() => navigate('home')} className="pop-press" style={{ display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer' }}>
          <img src="assets/logo.png" alt="Magic Cell" style={{ height: isMobile ? 40 : 48, width: 'auto', display: 'block' }} />
          {!isMobile && <div>
            <div style={{ fontFamily: P.display, fontSize: isMobile ? 18 : 22, letterSpacing: -0.5 }}>MAGIC CELL</div>
            <div style={{ fontSize: 9, color: P.dim, letterSpacing: 1.5, textTransform: 'uppercase', marginTop: -2 }}>la tienda electrónica</div>
          </div>}
        </div>

        {!isMobile && (
          <div onClick={onOpenSearch} style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 10,
            background: P.card, border: `2px solid ${P.ink}`, borderRadius: 999, padding: '0 6px 0 18px',
            boxShadow: `3px 3px 0 ${P.ink}`, maxWidth: 560, margin: '0 auto', cursor: 'text' }}>
            <span style={{ fontSize: 16 }}>🔍</span>
            <span style={{ flex: 1, fontSize: 14, color: P.dim, padding: '13px 0', userSelect: 'none' }}>Buscar productos, marcas...</span>
            <PopButton variant="primary" size="sm" onClick={onOpenSearch}>Buscar</PopButton>
          </div>
        )}

        <div style={{ marginLeft: isMobile ? 'auto' : 0, display: 'flex', gap: isMobile ? 6 : 10, alignItems: 'center' }}>
          {!isMobile && (
            <button onClick={onOpenAccount} className="pop-press" style={{
              padding: '10px 14px', background: user ? P.pink : P.card, border: `2px solid ${P.ink}`, borderRadius: 10,
              fontSize: 12, fontWeight: 600, boxShadow: `2px 2px 0 ${P.ink}`, display: 'flex', gap: 6, alignItems: 'center',
            }}>
              {user ? (
                <>
                  <div style={{ width: 22, height: 22, borderRadius: '50%', background: P.ink, color: '#ffffff',
                    display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: P.display, fontSize: 11 }}>
                    {user.avatar}
                  </div>
                  <span style={{ maxWidth: 80, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{user.name.split(' ')[0]}</span>
                </>
              ) : <><span>👤</span><span>Cuenta</span></>}
            </button>
          )}
          {isMobile && (
            <button onClick={onOpenAccount} className="pop-press" style={{
              width: 40, height: 40, borderRadius: 10, background: user ? P.pink : P.card, border: `2px solid ${P.ink}`,
              boxShadow: `2px 2px 0 ${P.ink}`, fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              {user ? (
                <div style={{ width: 26, height: 26, borderRadius: '50%', background: P.ink, color: '#ffffff',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: P.display, fontSize: 12 }}>
                  {user.avatar}
                </div>
              ) : '👤'}
            </button>
          )}
          {isMobile && (
            <button onClick={onOpenSearch} className="pop-press" style={{
              width: 40, height: 40, borderRadius: 10, background: P.card, border: `2px solid ${P.ink}`,
              boxShadow: `2px 2px 0 ${P.ink}`, fontSize: 16,
            }}>🔍</button>
          )}
          <button onClick={onOpenCart} data-cart-target className="pop-press" style={{
            padding: isMobile ? '0' : '10px 14px',
            width: isMobile ? 40 : 'auto', height: isMobile ? 40 : 'auto',
            background: P.green, color: P.card, border: `2px solid ${P.ink}`,
            borderRadius: 10, fontSize: isMobile ? 16 : 12, fontWeight: 700, boxShadow: `2px 2px 0 ${P.ink}`,
            display: 'flex', gap: 6, alignItems: 'center', justifyContent: 'center', position: 'relative',
          }}>
            {isMobile ? '🛒' : <><span>🛒</span><span>Bolsa</span></>}
            <span style={{
              position: isMobile ? 'absolute' : 'static',
              top: isMobile ? -6 : 'auto', right: isMobile ? -6 : 'auto',
              background: P.yellow, color: P.ink, padding: '2px 7px', borderRadius: 999, fontSize: 11,
              border: isMobile ? `2px solid ${P.ink}` : 'none', minWidth: 18,
            }}>{cartCount}</span>
          </button>
        </div>
      </div>

      {/* Category nav — desktop only, driven by real product data */}
      {!isMobile && (
        <div style={{ padding: '14px 32px', display: 'flex', gap: 8,
          background: P.cream, borderBottom: `2px solid ${P.ink}`, flexWrap: 'wrap' }}>
          {(() => {
            const CAT_STYLE = {
              'Celulares':      ['📱', P.blueLight],
              'Laptops':        ['💻', P.purple],
              'Tablets':        ['📲', P.yellow],
              'Smartwatch':     ['⌚', '#a8d8ff'],
              'Wearables':      ['⌚', P.blueLight],
              'Sillas':         ['🪑', '#ffc88c'],
              'Teclados':       ['⌨️', P.cream2],
              'Audífonos':      ['🎧', '#8cffce'],
              'Joysticks':      ['🕹️', P.purple],
              'Audio':          ['🔊', '#8cffce'],
              'Consolas':       ['🎮', P.blueLight],
              'Componentes':    ['⚙️', P.cream2],
              'TV y Monitores': ['🖥', '#ffc88c'],
              'Cámaras':        ['📷', P.pink],
              'Electrohogar':   ['🏠', P.yellow],
              'Electrónica':    ['⚡', P.cream2],
            };
            const productCats = [...new Set((window.POP_PRODUCTS || []).map(p => p.category).filter(Boolean))].sort();
            const chips = [
              ['🔥', 'Ofertas Hot Week', P.red],
              ...productCats.map(cat => {
                const [emoji, color] = CAT_STYLE[cat] || ['🛍', P.cream];
                return [emoji, cat, color];
              }),
            ];
            return chips.map(([e, l, c]) => (
              <PopChip key={l} color={c} onClick={() => navigate('listing', { category: l })}>
                <span style={{ fontSize: 14 }}>{e}</span> {l}
              </PopChip>
            ));
          })()}
        </div>
      )}
    </>
  );
}

function PopFooter({ isMobile }) {
  return (
    <>
      <div style={{ padding: isMobile ? '20px 16px' : '24px 32px', background: P.ink, color: P.card,
        display: 'grid', gridTemplateColumns: isMobile ? 'repeat(2,1fr)' : 'repeat(4,1fr)', gap: isMobile ? 16 : 24 }}>
        {[
          ['🚚', 'Envío 24h', 'Montevideo y todo UY'],
          ['↩️', '30 días', 'Devolución gratis'],
          ['🛡', '2 años', 'Garantía oficial'],
          ['💳', '12 cuotas', 'Con tu banco'],
        ].map(([e, t, s]) => (
          <div key={t} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{ width: isMobile ? 40 : 48, height: isMobile ? 40 : 48, borderRadius: 12, background: P.red,
              display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: isMobile ? 18 : 22 }}>{e}</div>
            <div>
              <div style={{ fontFamily: P.display, fontSize: isMobile ? 13 : 16, letterSpacing: -0.5, color: '#ffffff' }}>{t}</div>
              <div style={{ fontSize: 10, color: '#d6cdb8', marginTop: 2 }}>{s}</div>
            </div>
          </div>
        ))}
      </div>

      <div style={{ padding: isMobile ? '32px 16px' : '40px 32px',
        display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.4fr repeat(4,1fr)', gap: isMobile ? 20 : 24, background: P.cream }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <img src="assets/logo.png" alt="Magic Cell" style={{ height: 44, width: 'auto', display: 'block' }} />
            <div style={{ fontFamily: P.display, fontSize: 22, letterSpacing: -0.5 }}>MAGIC CELL</div>
          </div>
          <div style={{ fontSize: 13, color: P.ink2, marginTop: 12, maxWidth: 260, lineHeight: 1.5 }}>
            Tu tienda de electrónica favorita. Mejor selección, mejor precio, mejor servicio.
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
            {['IG', 'TT', 'YT', 'FB', 'X'].map(s => (
              <div key={s} className="pop-press" style={{ width: 32, height: 32, borderRadius: 8, background: P.ink, color: '#ffffff',
                border: `2px solid ${P.ink}`, display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: P.display, fontSize: 11, letterSpacing: 0.5, cursor: 'pointer' }}>{s}</div>
            ))}
          </div>
        </div>
        {[
          ['TIENDA',  ['Novedades','Ofertas','Outlet','Bundles','Marcas']],
          ['AYUDA',   ['Centro de ayuda','Envíos','Devoluciones','Garantía','Contacto']],
          ['CUENTA',  ['Mi cuenta','Pedidos','Lista','Direcciones','MAGIC CELL PRO']],
          ['EMPRESA', ['Nosotros','Sucursales','Mayoristas','Empleo','Prensa']],
        ].map(([t, items]) => (
          <div key={t}>
            <div style={{ fontFamily: P.display, fontSize: 13, letterSpacing: 1, color: P.ink }}>{t}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 12, fontSize: 12, color: P.ink2 }}>
              {items.map(i => <span key={i} style={{ cursor: 'pointer' }}>{i}</span>)}
            </div>
          </div>
        ))}
      </div>
      <div style={{ padding: isMobile ? '12px 16px' : '14px 32px', borderTop: `2px solid ${P.ink}`, background: P.red,
        display: 'flex', justifyContent: 'space-between', fontSize: 11, fontWeight: 600, flexWrap: 'wrap', gap: 8 }}>
        <span>© 2026 MAGIC CELL!</span>
        <span>Términos · Privacidad · Cookies</span>
      </div>
    </>
  );
}

function CartDrawer({ open, onClose, cart, removeFromCart, updateQty, navigate }) {
  if (!open) return null;
  const subtotal = cart.reduce((s, it) => s + it.price * it.qty, 0);
  const shipping = subtotal > 50 ? 0 : 5;
  const total = subtotal + shipping;
  const fmt = n => n.toLocaleString('es-UY');
  return (
    <>
      <div onClick={onClose} className="pop-overlay-in" style={{
        position: 'fixed', inset: 0, background: 'rgba(26,20,16,0.5)', zIndex: 99 }}></div>
      <div className="pop-drawer-in" style={{
        position: 'fixed', top: 0, right: 0, bottom: 0, width: 'min(420px, 100vw)',
        background: P.bg, zIndex: 100, display: 'flex', flexDirection: 'column',
        borderLeft: `3px solid ${P.ink}`,
      }}>
        <div style={{ padding: '18px 20px', background: P.red, borderBottom: `3px solid ${P.ink}`,
          display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontFamily: P.display, fontSize: 22, letterSpacing: -0.5 }}>🛒 TU BOLSA</div>
            <div style={{ fontSize: 11, fontWeight: 600, marginTop: 2 }}>{cart.length} {cart.length === 1 ? 'producto' : 'productos'}</div>
          </div>
          <button onClick={onClose} className="pop-press" style={{
            width: 36, height: 36, borderRadius: 10, background: P.card, border: `2px solid ${P.ink}`,
            boxShadow: `2px 2px 0 ${P.ink}`, fontFamily: P.display, fontSize: 14,
          }}>✕</button>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: '16px 20px', display: 'flex', flexDirection: 'column', gap: 12 }}>
          {cart.length === 0 ? (
            <div style={{ textAlign: 'center', padding: '48px 16px' }}>
              <div style={{ fontSize: 48 }}>🛍</div>
              <div style={{ fontFamily: P.display, fontSize: 22, marginTop: 12 }}>Tu bolsa está vacía</div>
              <div style={{ fontSize: 13, color: P.dim, marginTop: 6 }}>Agrega productos para verlos aquí.</div>
              <div style={{ marginTop: 18 }}>
                <PopButton variant="primary" onClick={() => { onClose(); navigate('listing'); }}>Ver productos</PopButton>
              </div>
            </div>
          ) : cart.map((it, i) => (
            <div key={it.id} className="pop-fade-up" style={{
              display: 'grid', gridTemplateColumns: '80px 1fr auto', gap: 12,
              background: P.card, border: `2px solid ${P.ink}`, borderRadius: 12, padding: 10,
              boxShadow: `3px 3px 0 ${P.ink}`, animationDelay: `${i * 0.05}s`,
            }}>
              <div style={{ width: 80, height: 80 }}>
                <ProductImage tone={it.tone || getCategoryTone(it.category)} sku={it.sku} imageUrl={it.image_url} />
              </div>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 10, color: P.blue, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase' }}>{it.brand}</div>
                <div style={{ fontSize: 12, fontWeight: 600, lineHeight: 1.3, marginTop: 2,
                  display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>{it.name}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8 }}>
                  <QtyStepper qty={it.qty} setQty={q => updateQty(it.id, q)} size="sm" />
                  <button onClick={() => removeFromCart(it.id)} style={{
                    background: 'transparent', border: 'none', color: P.dim, fontSize: 11,
                    textDecoration: 'underline', padding: 0, cursor: 'pointer',
                  }}>Quitar</button>
                </div>
              </div>
              <div style={{ textAlign: 'right', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
                <div style={{ fontFamily: P.display, fontSize: 16, letterSpacing: -0.5 }}>${fmt(it.price * it.qty)}</div>
                {it.qty > 1 && <div style={{ fontSize: 10, color: P.dim }}>${fmt(it.price)} c/u</div>}
              </div>
            </div>
          ))}
        </div>

        {cart.length > 0 && (
          <div style={{ padding: '16px 20px', background: P.cream, borderTop: `3px solid ${P.ink}`, display: 'flex', flexDirection: 'column', gap: 10 }}>
            {subtotal < 50 && (
              <div style={{ background: P.card, border: `2px solid ${P.ink}`, borderRadius: 10, padding: 10, fontSize: 11, fontWeight: 600 }}>
                🚚 ¡Te faltan <span style={{ color: P.red }}>${fmt(50 - subtotal)}</span> para envío gratis!
                <div style={{ height: 6, background: P.line, borderRadius: 999, marginTop: 6, overflow: 'hidden', border: `1px solid ${P.ink}` }}>
                  <div style={{ height: '100%', background: P.green, width: `${Math.min(100, subtotal / 50 * 100)}%`, transition: 'width .4s' }}></div>
                </div>
              </div>
            )}
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
              <span>Subtotal</span><span style={{ fontWeight: 600 }}>${fmt(subtotal)}</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13 }}>
              <span>Envío</span>
              <span style={{ fontWeight: 600, color: shipping === 0 ? P.green : P.ink }}>
                {shipping === 0 ? '¡GRATIS!' : `$${fmt(shipping)}`}
              </span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
              borderTop: `2px dashed ${P.ink}`, paddingTop: 10 }}>
              <span style={{ fontFamily: P.display, fontSize: 18 }}>TOTAL</span>
              <span style={{ fontFamily: P.display, fontSize: 24, letterSpacing: -1 }}>${fmt(total)}</span>
            </div>
            <PopButton variant="dark" size="lg" full onClick={() => { onClose(); navigate('checkout'); }}>
              Ir al checkout →
            </PopButton>
            <PopButton variant="secondary" size="sm" full onClick={() => { onClose(); navigate('cart'); }}>
              Ver carrito completo
            </PopButton>
          </div>
        )}
      </div>
    </>
  );
}

function MobileMenu({ open, onClose, navigate }) {
  if (!open) return null;
  return (
    <>
      <div onClick={onClose} className="pop-overlay-in" style={{
        position: 'fixed', inset: 0, background: 'rgba(26,20,16,0.5)', zIndex: 99 }}></div>
      <div className="pop-menu-in" style={{
        position: 'fixed', top: 0, left: 0, bottom: 0, width: 'min(320px, 85vw)',
        background: P.bg, zIndex: 100, display: 'flex', flexDirection: 'column',
        borderRight: `3px solid ${P.ink}`,
      }}>
        <div style={{ padding: '18px 20px', background: P.red, borderBottom: `3px solid ${P.ink}`,
          display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <img src="assets/logo.png" alt="Magic Cell" style={{ height: 36, width: 'auto', display: 'block' }} />
            <div style={{ fontFamily: P.display, fontSize: 18, letterSpacing: -0.5 }}>MAGIC CELL</div>
          </div>
          <button onClick={onClose} className="pop-press" style={{
            width: 36, height: 36, borderRadius: 10, background: P.card, border: `2px solid ${P.ink}`,
            boxShadow: `2px 2px 0 ${P.ink}`, fontFamily: P.display, fontSize: 14,
          }}>✕</button>
        </div>
        <div style={{ padding: '16px 20px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {[
            ['🏠', 'Inicio', 'home'],
            ['🔥', 'Hot Week', 'listing'],
            ['🎮', 'Gaming', 'listing'],
            ['⚡', 'Carga', 'listing'],
            ['🎧', 'Audio', 'listing'],
            ['⌚', 'Wearables', 'listing'],
            ['🛍', 'Todas las categorías', 'listing'],
          ].map(([e, l, r]) => (
            <div key={l} onClick={() => { onClose(); navigate(r); }} className="pop-press" style={{
              padding: '12px 14px', background: P.card, border: `2px solid ${P.ink}`, borderRadius: 10,
              boxShadow: `2px 2px 0 ${P.ink}`, display: 'flex', alignItems: 'center', gap: 10,
              fontWeight: 600, fontSize: 13, cursor: 'pointer',
            }}>
              <span style={{ fontSize: 18 }}>{e}</span>{l}
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

// ─── Search Overlay ───────────────────────────────────────────────────────────
const SEARCH_CATEGORIES = [
  ['📱','Celulares'], ['💻','Laptops'], ['🎮','Consolas'], ['🎧','Audio'],
  ['⌚','Wearables'], ['🖥️','TV y Monitores'], ['🔧','Componentes'], ['📷','Cámaras'],
];

function SearchOverlay({ open, onClose, navigate, addToCart, isMobile }) {
  const [query, setQuery] = React.useState('');
  const [results, setResults] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [activeCategory, setActiveCategory] = React.useState('');
  const [recent, setRecent] = React.useState([]);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    if (open) {
      setQuery(''); setResults([]); setActiveCategory(''); setLoading(false);
      try { setRecent(JSON.parse(localStorage.getItem('voltio-recent-searches') || '[]')); } catch {}
      setTimeout(() => inputRef.current?.focus(), 80);
    }
  }, [open]);

  React.useEffect(() => {
    if (!open) return;
    const fn = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', fn);
    return () => window.removeEventListener('keydown', fn);
  }, [open]);

  React.useEffect(() => {
    const q = query.trim();
    if (!q) { setResults([]); setLoading(false); return; }
    setLoading(true);
    const t = setTimeout(() => doSearch(q), 300);
    return () => clearTimeout(t);
  }, [query]);

  const searchInMemory = (q) => {
    const lq = q.toLowerCase();
    return (window.POP_PRODUCTS || []).filter(p =>
      (p.name || '').toLowerCase().includes(lq) ||
      (p.brand || '').toLowerCase().includes(lq) ||
      (p.category || '').toLowerCase().includes(lq)
    ).slice(0, 24);
  };

  const doSearch = async (q) => {
    if (!window.sb) {
      setResults(searchInMemory(q)); setLoading(false); return;
    }
    try {
      const { data, error } = await window.sb.from('products')
        .select('id,name,brand,category,price,currency,image_url,in_stock')
        .or(`name.ilike.%${q}%,brand.ilike.%${q}%,category.ilike.%${q}%`)
        .neq('in_stock', false)
        .limit(24);
      if (error) throw error;
      // Si Supabase devuelve resultados úsalos; si no, complementa con los de memoria
      const supabaseResults = data || [];
      setResults(supabaseResults.length > 0 ? supabaseResults : searchInMemory(q));
    } catch {
      // Error de red o tabla no disponible → caer en búsqueda en memoria
      setResults(searchInMemory(q));
    } finally {
      setLoading(false);
    }
  };

  const saveRecent = (q) => {
    if (!q.trim()) return;
    const updated = [q, ...recent.filter(r => r !== q)].slice(0, 6);
    setRecent(updated);
    try { localStorage.setItem('voltio-recent-searches', JSON.stringify(updated)); } catch {}
  };

  const goToProduct = (p) => { saveRecent(query); onClose(); navigate('pdp', { id: p.id }); };
  const goToCategory = (cat) => { saveRecent(cat); onClose(); navigate('listing', { category: cat }); };

  const categories = [...new Set(results.map(r => r.category).filter(Boolean))];
  const filtered = activeCategory ? results.filter(r => r.category === activeCategory) : results;

  const fmt = (n) => Number(n).toLocaleString('es-MX');
  const highlight = (text, q) => {
    if (!q || !text) return text;
    const safe = q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    const parts = text.split(new RegExp(`(${safe})`, 'gi'));
    return parts.map((part, i) =>
      new RegExp(`^${safe}$`, 'i').test(part)
        ? <mark key={i} style={{ background: P.yellow, color: P.ink, borderRadius: 2, padding: '0 1px' }}>{part}</mark>
        : part
    );
  };

  if (!open) return null;

  // Desktop: outer div owns the transform-based positioning so the animation
  // class on the inner div can't clobber translateX(-50%) during keyframes.
  const positionStyle = isMobile ? null : {
    position: 'fixed', top: 0, left: '50%', transform: 'translateX(-50%)',
    width: 'min(780px, calc(100vw - 48px))', maxHeight: '90vh',
    zIndex: 301,
  };
  const panelStyle = isMobile ? {
    position: 'fixed', inset: 0, zIndex: 301,
    background: P.bg, display: 'flex', flexDirection: 'column', overflow: 'hidden',
  } : {
    background: P.bg,
    border: `3px solid ${P.ink}`, borderTop: 'none',
    borderRadius: '0 0 20px 20px',
    boxShadow: `6px 6px 0 ${P.ink}`,
    display: 'flex', flexDirection: 'column', overflow: 'hidden',
    maxHeight: '90vh',
  };

  const panel = (
    <div className={isMobile ? 'pop-page-in' : 'pop-fade-up'} style={panelStyle}>

        {/* ── Barra de búsqueda ── */}
        <div style={{
          padding: isMobile ? '12px 14px' : '14px 20px',
          background: P.red, borderBottom: `3px solid ${P.ink}`,
          display: 'flex', gap: 10, alignItems: 'center',
          position: 'relative', overflow: 'hidden', flexShrink: 0,
        }}>
          <div className="pop-dots" style={{ position: 'absolute', inset: 0, opacity: 0.3, pointerEvents: 'none' }}/>
          {isMobile && (
            <button onClick={onClose} className="pop-press" style={{
              width: 40, height: 40, flexShrink: 0, borderRadius: 10,
              background: P.card, border: `2px solid ${P.ink}`, boxShadow: `2px 2px 0 ${P.ink}`,
              fontSize: 18, cursor: 'pointer',
            }}>←</button>
          )}
          <div style={{
            flex: 1, position: 'relative', display: 'flex', alignItems: 'center',
            background: P.card, border: `2px solid ${P.ink}`, borderRadius: 12,
            boxShadow: `3px 3px 0 ${P.ink}`, padding: '0 14px', gap: 10,
          }}>
            <span style={{ fontSize: 18, flexShrink: 0 }}>{loading ? '⏳' : '🔍'}</span>
            <input
              ref={inputRef}
              type="search"
              value={query}
              onChange={e => setQuery(e.target.value)}
              placeholder="Buscar productos, marcas, categorías..."
              autoComplete="off"
              style={{
                flex: 1, border: 'none', outline: 'none', background: 'transparent',
                fontFamily: P.font, fontSize: isMobile ? 16 : 17, fontWeight: 500,
                padding: isMobile ? '13px 0' : '14px 0', color: P.ink,
              }}
            />
            {query && (
              <button onClick={() => { setQuery(''); setResults([]); inputRef.current?.focus(); }}
                style={{ background: 'transparent', border: 'none', cursor: 'pointer',
                  fontSize: 20, color: P.dim, flexShrink: 0, lineHeight: 1, padding: 0 }}>✕</button>
            )}
          </div>
          {!isMobile && (
            <button onClick={onClose} className="pop-press" style={{
              padding: '10px 14px', flexShrink: 0, borderRadius: 10,
              background: P.card, border: `2px solid ${P.ink}`, boxShadow: `2px 2px 0 ${P.ink}`,
              fontFamily: P.display, fontSize: 12, cursor: 'pointer', letterSpacing: 0.5,
            }}>ESC</button>
          )}
        </div>

        {/* ── Chips de categoría (solo cuando hay resultados y varias categorías) ── */}
        {!loading && results.length > 0 && categories.length > 1 && (
          <div style={{
            padding: '10px 16px', borderBottom: `2px solid ${P.line2}`,
            display: 'flex', gap: 6, overflowX: 'auto', flexShrink: 0,
          }}>
            <PopChip active={!activeCategory} size="sm" onClick={() => setActiveCategory('')}>
              Todo ({results.length})
            </PopChip>
            {categories.map(cat => (
              <PopChip key={cat} active={activeCategory === cat} size="sm"
                onClick={() => setActiveCategory(c => c === cat ? '' : cat)}>
                {cat} ({results.filter(r => r.category === cat).length})
              </PopChip>
            ))}
          </div>
        )}

        {/* ── Cuerpo scrollable ── */}
        <div style={{ flex: 1, overflowY: 'auto', padding: isMobile ? 14 : 20 }}>

          {/* Estado vacío: recientes + categorías populares */}
          {!query.trim() && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 22 }}>

              {recent.length > 0 && (
                <div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
                    <div style={{ fontFamily: P.display, fontSize: 12, letterSpacing: 0.5 }}>🕐 BÚSQUEDAS RECIENTES</div>
                    <button onClick={() => { setRecent([]); localStorage.removeItem('voltio-recent-searches'); }}
                      style={{ background: 'none', border: 'none', color: P.dim, fontSize: 12, cursor: 'pointer', textDecoration: 'underline' }}>
                      Borrar
                    </button>
                  </div>
                  <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                    {recent.map(term => (
                      <button key={term} onClick={() => setQuery(term)} className="pop-press" style={{
                        padding: '7px 14px', background: P.cream, border: `2px solid ${P.ink}`,
                        borderRadius: 8, boxShadow: `2px 2px 0 ${P.ink}`, fontFamily: P.font,
                        fontSize: 13, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6,
                      }}>
                        <span style={{ opacity: 0.45, fontSize: 11 }}>↩</span> {term}
                      </button>
                    ))}
                  </div>
                </div>
              )}

              <div>
                <div style={{ fontFamily: P.display, fontSize: 12, letterSpacing: 0.5, marginBottom: 10 }}>📂 EXPLORAR POR CATEGORÍA</div>
                <div style={{ display: 'grid', gridTemplateColumns: isMobile ? 'repeat(2,1fr)' : 'repeat(4,1fr)', gap: 8 }}>
                  {SEARCH_CATEGORIES.map(([emoji, cat]) => (
                    <button key={cat} onClick={() => goToCategory(cat)} className="pop-press" style={{
                      padding: isMobile ? '12px 10px' : '14px 12px',
                      background: P.card, border: `2px solid ${P.ink}`,
                      borderRadius: 12, boxShadow: `3px 3px 0 ${P.ink}`, cursor: 'pointer',
                      display: 'flex', alignItems: 'center', gap: 10, textAlign: 'left',
                    }}>
                      <span style={{ fontSize: isMobile ? 20 : 24 }}>{emoji}</span>
                      <span style={{ fontFamily: P.display, fontSize: isMobile ? 11 : 12, letterSpacing: 0.5 }}>
                        {cat.toUpperCase()}
                      </span>
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* Skeletons de carga */}
          {loading && (
            <div style={{ display: 'grid', gridTemplateColumns: isMobile ? 'repeat(2,1fr)' : 'repeat(4,1fr)', gap: 10 }}>
              {[...Array(8)].map((_, i) => (
                <div key={i} style={{
                  background: P.cream, border: `2px solid ${P.line2}`, borderRadius: 12, overflow: 'hidden',
                  opacity: 0.7, animation: `pop-pulse 1.2s ${i * 0.1}s ease-in-out infinite`,
                }}>
                  <div style={{ aspectRatio: '1/1', background: P.line2 }}/>
                  <div style={{ padding: 10 }}>
                    <div style={{ height: 10, background: P.line2, borderRadius: 4, marginBottom: 6 }}/>
                    <div style={{ height: 10, background: P.line2, borderRadius: 4, width: '65%' }}/>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Sin resultados */}
          {!loading && query.trim() && results.length === 0 && (
            <div style={{ textAlign: 'center', padding: isMobile ? '48px 16px' : '56px 24px' }}>
              <div style={{ fontSize: 60 }}>🔍</div>
              <div style={{ fontFamily: P.display, fontSize: isMobile ? 22 : 28, letterSpacing: -1, marginTop: 12 }}>Sin resultados</div>
              <div style={{ fontSize: 13, color: P.dim, marginTop: 8, lineHeight: 1.6 }}>
                Nada para <strong>"{query}"</strong>. Intenta con otro término o explora por categoría.
              </div>
              <div style={{ marginTop: 18, display: 'flex', gap: 8, justifyContent: 'center', flexWrap: 'wrap' }}>
                {SEARCH_CATEGORIES.slice(0, 4).map(([emoji, cat]) => (
                  <button key={cat} onClick={() => goToCategory(cat)} className="pop-press" style={{
                    padding: '8px 14px', background: P.cream, border: `2px solid ${P.ink}`,
                    borderRadius: 8, fontSize: 13, cursor: 'pointer',
                  }}>{emoji} {cat}</button>
                ))}
              </div>
            </div>
          )}

          {/* Resultados */}
          {!loading && filtered.length > 0 && (
            <div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
                <div style={{ fontFamily: P.display, fontSize: 12, letterSpacing: 0.5, color: P.dim }}>
                  {filtered.length} RESULTADO{filtered.length !== 1 ? 'S' : ''}
                  {activeCategory ? ` · ${activeCategory.toUpperCase()}` : ''}
                </div>
                {!isMobile && (
                  <button onClick={() => { saveRecent(query); onClose(); navigate('listing', {}); }}
                    style={{ background: 'none', border: 'none', color: P.blue, fontSize: 12, fontWeight: 700, cursor: 'pointer', textDecoration: 'underline' }}>
                    Ver todos en listado →
                  </button>
                )}
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: isMobile ? 'repeat(2,1fr)' : 'repeat(4,1fr)', gap: isMobile ? 10 : 12 }}>
                {filtered.map((p, i) => (
                  <div key={p.id} className="pop-fade-up" style={{
                    background: P.card, border: `2px solid ${P.ink}`, borderRadius: 14,
                    boxShadow: `3px 3px 0 ${P.ink}`, overflow: 'hidden',
                    display: 'flex', flexDirection: 'column',
                    animationDelay: `${Math.min(i, 7) * 0.04}s`,
                  }}>
                    {/* Imagen */}
                    <div onClick={() => goToProduct(p)} style={{
                      position: 'relative', aspectRatio: '1/1', cursor: 'pointer',
                      background: p.image_url ? P.cream : P.yellow,
                      borderBottom: `2px solid ${P.ink}`,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>
                      {p.image_url ? (
                        <img src={p.image_url} alt={p.name}
                          style={{ width: '100%', height: '100%', objectFit: 'contain', padding: 8 }}
                          onError={e => { e.currentTarget.style.display = 'none'; }}/>
                      ) : (
                        <span style={{ fontFamily: P.display, fontSize: 30 }}>📦</span>
                      )}
                      {p.category && (
                        <div style={{
                          position: 'absolute', top: 6, left: 6,
                          background: P.ink, color: '#ffffff',
                          padding: '2px 7px', borderRadius: 4,
                          fontFamily: P.display, fontSize: 8, letterSpacing: 0.5,
                        }}>{p.category.toUpperCase()}</div>
                      )}
                    </div>

                    {/* Info */}
                    <div style={{ padding: isMobile ? '8px 10px' : '10px 12px', flex: 1, display: 'flex', flexDirection: 'column', gap: 3 }}>
                      {p.brand && (
                        <div style={{ fontSize: 9, color: P.blue, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase' }}>{p.brand}</div>
                      )}
                      <div onClick={() => goToProduct(p)} style={{
                        fontSize: isMobile ? 11 : 12, fontWeight: 600, lineHeight: 1.35, cursor: 'pointer', flex: 1,
                        display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
                      }}>
                        {highlight(p.name, query.trim())}
                      </div>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 6, gap: 4 }}>
                        <div style={{ fontFamily: P.display, fontSize: isMobile ? 13 : 15, letterSpacing: -0.5, lineHeight: 1 }}>
                          {p.currency || 'USD'} {fmt(p.price)}
                        </div>
                        <button onClick={e => { e.stopPropagation(); addToCart(p); }} className="pop-press" style={{
                          background: P.yellow, border: `2px solid ${P.ink}`, borderRadius: 6,
                          boxShadow: `2px 2px 0 ${P.ink}`, padding: '4px 7px',
                          fontFamily: P.display, fontSize: 9, cursor: 'pointer', letterSpacing: 0.5,
                          flexShrink: 0,
                        }}>+ BOLSA</button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>

              {isMobile && (
                <div style={{ marginTop: 16, textAlign: 'center' }}>
                  <button onClick={() => { saveRecent(query); onClose(); navigate('listing', {}); }} className="pop-press" style={{
                    padding: '12px 24px', background: P.ink, color: '#ffffff', border: `2px solid ${P.ink}`,
                    borderRadius: 10, boxShadow: `3px 3px 0 rgba(0,0,0,0.2)`,
                    fontFamily: P.display, fontSize: 13, cursor: 'pointer', letterSpacing: 0.5,
                  }}>Ver todos en listado →</button>
                </div>
              )}
            </div>
          )}
        </div>
      </div>
  );

  return (
    <>
      {/* Backdrop */}
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, background: 'rgba(26,20,16,0.65)',
        zIndex: 300, backdropFilter: 'blur(5px)',
      }}/>
      {/* Mobile: panel has position:fixed inset:0, no transform conflict.
          Desktop: outer wrapper owns translateX(-50%) so pop-fade-up's
          translateY() keyframe can't clobber it during the animation. */}
      {isMobile ? panel : (
        <div style={positionStyle}>{panel}</div>
      )}
    </>
  );
}

Object.assign(window, {
  StarBurst, PopButton, PopChip, PopBadge, PopRating,
  ProductImage, ProductCard, QtyStepper,
  PopHeader, PopFooter, CartDrawer, MobileMenu,
  SearchOverlay, flyToCart,
});
