/* Header with mega menu + search + cart */

// Build "Ver todas las Hidrolavadoras" / "Ver todos los Repuestos" / etc.
// Detect feminine plural by the first word ending in "as".
const verTodosLabel = (catName) => {
  const first = String(catName || '').split(' ')[0] || '';
  const fem = /as$/i.test(first);
  return (fem ? 'Ver todas las ' : 'Ver todos los ') + catName;
};

/* ── Mega menu — only rendered for categories that have segments (Hidrolavadoras) ── */
const MegaMenu = ({ cat, onNavigate, onClose }) => {
  const main = cat.segments.filter(s => ['domesticas', 'profesionales', 'industriales'].includes(s.id));
  const extras = cat.segments.filter(s => !['domesticas', 'profesionales', 'industriales'].includes(s.id));
  const MAX = 7;

  return (
    <div style={{
      position: 'fixed', top: 72, left: 0, right: 0, zIndex: 30,
      background: 'var(--surface)',
      borderBottom: '1px solid var(--line)',
      boxShadow: '0 8px 32px rgba(11,18,32,0.12)',
    }}>
      <div className="container" style={{ padding: '24px 0 18px' }}>

        {/* 3 columnas principales */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 32, marginBottom: 18 }}>
          {main.map(seg => (
            <div key={seg.id}>
              <button
                onClick={() => { onNavigate(`/categoria/${cat.slug}/${seg.slug}`); onClose(); }}
                style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  width: '100%', marginBottom: 8,
                  fontSize: 11, fontWeight: 700, color: 'var(--accent)',
                  textTransform: 'uppercase', letterSpacing: '0.08em',
                }}
                onMouseEnter={e => e.currentTarget.style.opacity = '0.75'}
                onMouseLeave={e => e.currentTarget.style.opacity = '1'}
              >
                {seg.name} <Icon name="arrowRight" size={11} />
              </button>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
                {seg.items.slice(0, MAX).map(item => (
                  <button key={item}
                    onClick={() => { onNavigate(`/categoria/${cat.slug}/${seg.slug}?uso=${encodeURIComponent(item)}`); onClose(); }}
                    style={{
                      textAlign: 'left', padding: '5px 8px', borderRadius: 5,
                      fontSize: 13, fontWeight: 500, color: 'var(--ink-2)',
                      transition: 'background .1s',
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-2)'}
                    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
                  >
                    {item}
                  </button>
                ))}
                {seg.items.length > MAX && (
                  <button
                    onClick={() => { onNavigate(`/categoria/${cat.slug}/${seg.slug}`); onClose(); }}
                    style={{
                      textAlign: 'left', padding: '5px 8px',
                      fontSize: 12, color: 'var(--ink-4)', fontWeight: 600,
                    }}
                    onMouseEnter={e => e.currentTarget.style.color = 'var(--accent)'}
                    onMouseLeave={e => e.currentTarget.style.color = 'var(--ink-4)'}
                  >
                    +{seg.items.length - MAX} más →
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>

        {/* Divisor */}
        <div style={{ height: 1, background: 'var(--line)', marginBottom: 14 }} />

        {/* Fila inferior: Accesorios, Repuestos + Ver todas */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', gap: 8 }}>
            {extras.map(seg => (
              <button key={seg.id}
                onClick={() => { onNavigate(`/categoria/${cat.slug}/${seg.slug}`); onClose(); }}
                style={{
                  padding: '6px 14px', borderRadius: 999,
                  border: '1px solid var(--line-2)',
                  fontSize: 13, fontWeight: 600, color: 'var(--ink-2)',
                  display: 'flex', alignItems: 'center', gap: 6,
                  transition: 'background .1s, border-color .1s',
                }}
                onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-2)'; e.currentTarget.style.borderColor = 'var(--ink-3)'; }}
                onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.borderColor = 'var(--line-2)'; }}
              >
                {seg.name} <Icon name="arrowRight" size={12} />
              </button>
            ))}
          </div>
          <button
            onClick={() => { onNavigate(`/categoria/${cat.slug}`); onClose(); }}
            style={{
              fontSize: 13, fontWeight: 700, color: 'var(--accent)',
              display: 'flex', alignItems: 'center', gap: 4,
            }}
            onMouseEnter={e => e.currentTarget.style.opacity = '0.75'}
            onMouseLeave={e => e.currentTarget.style.opacity = '1'}
          >
            {verTodosLabel(cat.name)} <Icon name="arrowRight" size={13} />
          </button>
        </div>

      </div>
    </div>
  );
};

const HeaderBar = ({ onNavigate, onOpenCart, cartCount, onOpenMenu, onOpenSearch, currentRoute }) => {
  const [open, setOpen] = React.useState(null);
  const [hoveredSeg, setHoveredSeg] = React.useState(null);
  const closeT = React.useRef(null);
  const segCloseT = React.useRef(null);
  const { CATEGORIES } = window.RC_DATA;

  const enter = (id) => { clearTimeout(closeT.current); setOpen(id); };
  const leave = () => { closeT.current = setTimeout(() => { setOpen(null); setHoveredSeg(null); }, 140); };
  const enterSeg = (id) => { clearTimeout(segCloseT.current); setHoveredSeg(id); };
  const leaveSeg = () => { segCloseT.current = setTimeout(() => setHoveredSeg(null), 80); };

  const nav = CATEGORIES.slice(0, 5);
  const isActive = (slug) => currentRoute?.startsWith(`/categoria/${slug}`) || currentRoute?.startsWith('/tienda');

  return (
    <React.Fragment>
      {/* Top announce strip — OUTSIDE sticky header so it scrolls away */}
      <div className="announce-strip" style={{ background: 'var(--ink)', color: '#fff', fontSize: 12, padding: '8px 0', position: 'relative' }}>
        {/* Desktop: two-group layout (unchanged) */}
        <div className="container announce-strip-inner announce-desktop" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', gap: 20, flexWrap: 'wrap', color: 'rgba(255,255,255,0.75)', fontFamily: '"Galano", var(--font-sans)', fontWeight: 400 }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon name="truck" size={13}/> Envío gratis CABA/GBA</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon name="credit" size={13}/> 12 cuotas sin interés</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Icon name="zap" size={13}/> 15% OFF transferencia</span>
          </div>
          <div style={{ display: 'flex', gap: 16, color: 'rgba(255,255,255,0.75)', fontFamily: '"Galano", var(--font-sans)', fontWeight: 400 }}>
            <a href="#" onClick={(e) => { e.preventDefault(); onNavigate('/reparaciones'); }} style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <Icon name="wrench" size={13}/> Service
            </a>
            <a href="#" onClick={(e) => { e.preventDefault(); onNavigate('/quienes-somos'); }} style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <Icon name="store" size={13}/> Quiénes somos
            </a>
            <a href={'https://www.google.com/maps/place/Powerclean+-+RC+Distribuidora/@-34.6422092,-58.6156195,17z/data=!3m1!4b1!4m6!3m5!1s0x95bcc7d9176eb0a5:0x7bf593a6e59ff4fb!8m2!3d-34.6422136!4d-58.6130446!16s%2Fg%2F1w456svm?entry=ttu&g_ep=EgoyMDI2MDUyMC4wIKXMDSoASAFQAw%3D%3D'}
              target="_blank" rel="noopener noreferrer"
              style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              <Icon name="pin" size={13}/> Tres Arroyos 456, Haedo
            </a>
          </div>
        </div>

        {/* Mobile: auto-scrolling marquee */}
        <div className="announce-marquee" aria-hidden="true">
          <div className="announce-track" style={{ color: 'rgba(255,255,255,0.85)', fontFamily: '"Galano", var(--font-sans)', fontWeight: 400 }}>
            {[0, 1].map(set => (
              <React.Fragment key={set}>
                <span><Icon name="truck" size={13}/> Envío gratis CABA/GBA</span>
                <span className="announce-sep">·</span>
                <span><Icon name="credit" size={13}/> 12 cuotas sin interés</span>
                <span className="announce-sep">·</span>
                <span><Icon name="zap" size={13}/> 15% OFF transferencia</span>
                <span className="announce-sep">·</span>
                <span><Icon name="wrench" size={13}/> Servicio técnico propio</span>
                <span className="announce-sep">·</span>
                <span><Icon name="shield" size={13}/> Garantía 12 meses</span>
                <span className="announce-sep">·</span>
                <span><Icon name="pin" size={13}/> Tres Arroyos 456, Haedo</span>
                <span className="announce-sep">·</span>
              </React.Fragment>
            ))}
          </div>
        </div>
      </div>

      <header style={{
        position: 'sticky', top: 0, zIndex: 40,
        background: 'var(--surface)',
        borderBottom: '1px solid var(--line)',
      }}>
      {/* Main bar */}
      <div className="container" style={{ display: 'flex', alignItems: 'center', gap: 18, height: 72 }}>
        <button onClick={() => onNavigate('/')} style={{ flexShrink: 0 }}>
          <Logo />
        </button>

        {/* Mobile inline search — fills remaining space between logo and icons */}
        <button onClick={onOpenSearch} className="hdr-mobile-search-inline"
          style={{
            display: 'none',
            flex: 1, minWidth: 0,
            alignItems: 'center', gap: 8,
            padding: '9px 14px',
            background: 'var(--bg-2)',
            border: '1px solid var(--line)',
            borderRadius: 999,
            fontSize: 13, color: 'var(--ink-3)',
            textAlign: 'left', cursor: 'pointer',
            overflow: 'hidden',
          }}>
          <Icon name="search" size={16}/>
          <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Buscar productos…</span>
        </button>

        <nav style={{ display: 'flex', gap: 4, flex: 1, justifyContent: 'center' }} className="hide-mobile">
          {nav.map(cat => (
            <div key={cat.id} style={{ position: 'relative' }}
                 onMouseEnter={() => enter(cat.id)}
                 onMouseLeave={leave}>
              <button
                onClick={() => onNavigate(`/categoria/${cat.slug}`)}
                style={{
                  padding: '26px 10px',
                  fontSize: 14, fontWeight: 600,
                  whiteSpace: 'nowrap',
                  color: open === cat.id || isActive(cat.slug) ? 'var(--accent)' : 'var(--ink-2)',
                  display: 'inline-flex', alignItems: 'center', gap: 4,
                  borderBottom: open === cat.id ? '2px solid var(--accent)' : '2px solid transparent',
                  marginBottom: -1,
                }}>
                {cat.name}
                <Icon name="chevronDown" size={13} className={open === cat.id ? 'rot' : ''} />
              </button>
              {open === cat.id && (
                cat.segments
                  ? (
                    <div style={{
                      position: 'absolute', top: '100%', left: 0,
                      background: 'var(--surface)',
                      border: '1px solid var(--line)',
                      borderRadius: 'var(--r-md)',
                      boxShadow: 'var(--shadow-3)',
                      minWidth: 220,
                      padding: 8,
                      zIndex: 10,
                    }}>
                      {cat.segments
                        .filter(s => ['domesticas','profesionales','industriales'].includes(s.id))
                        .map(seg => (
                          <div key={seg.id} style={{ position: 'relative' }}
                            onMouseEnter={() => enterSeg(seg.id)}
                            onMouseLeave={leaveSeg}>
                            <button
                              onClick={() => { onNavigate(`/categoria/${cat.slug}/${seg.slug}`); setOpen(null); setHoveredSeg(null); }}
                              style={{
                                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                                width: '100%', textAlign: 'left',
                                padding: '10px 12px', borderRadius: 6,
                                fontSize: 13, fontWeight: 500,
                                color: hoveredSeg === seg.id ? 'var(--ink)' : 'var(--ink-2)',
                                background: hoveredSeg === seg.id ? 'var(--bg-2)' : 'transparent',
                              }}>
                              {seg.name}
                              <Icon name="chevronDown" size={12} style={{ transform: 'rotate(-90deg)', opacity: 0.5 }}/>
                            </button>

                            {/* Flyout con los usos L3 */}
                            {hoveredSeg === seg.id && seg.items.length > 0 && (
                              <div
                                onMouseEnter={() => enterSeg(seg.id)}
                                onMouseLeave={leaveSeg}
                                style={{
                                  position: 'absolute', top: 0, left: '100%',
                                  marginLeft: 4,
                                  background: 'var(--surface)',
                                  border: '1px solid var(--line)',
                                  borderRadius: 'var(--r-md)',
                                  boxShadow: 'var(--shadow-3)',
                                  padding: 8,
                                  zIndex: 20,
                                  // 2 columnas para listas largas
                                  display: 'grid',
                                  gridTemplateColumns: seg.items.length > 7 ? '1fr 1fr' : '1fr',
                                  minWidth: seg.items.length > 7 ? 360 : 200,
                                  gap: '0 4px',
                                }}>
                                {seg.items.map(item => (
                                  <button key={item}
                                    onClick={() => { onNavigate(`/categoria/${cat.slug}/${seg.slug}?uso=${encodeURIComponent(item)}`); setOpen(null); setHoveredSeg(null); }}
                                    style={{
                                      display: 'flex', textAlign: 'left',
                                      padding: '8px 10px', borderRadius: 5,
                                      fontSize: 13, fontWeight: 500, color: 'var(--ink-2)',
                                      whiteSpace: 'nowrap',
                                    }}
                                    onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-2)'; e.currentTarget.style.color = 'var(--ink)'; }}
                                    onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--ink-2)'; }}>
                                    {item}
                                  </button>
                                ))}
                              </div>
                            )}
                          </div>
                        ))
                      }
                      <div style={{ height: 1, background: 'var(--line)', margin: '6px 8px' }}/>
                      <button onClick={() => { onNavigate(`/categoria/${cat.slug}`); setOpen(null); }}
                        style={{
                          display: 'flex', width: '100%', textAlign: 'left', alignItems: 'center', justifyContent: 'space-between',
                          padding: '10px 12px', borderRadius: 6,
                          fontSize: 13, fontWeight: 600, color: 'var(--accent)',
                          whiteSpace: 'nowrap',
                        }}>
                        {verTodosLabel(cat.name)}
                        <Icon name="arrowRight" size={14} />
                      </button>
                    </div>
                  )
                  : (
                    <div style={{
                      position: 'absolute', top: '100%', left: 0,
                      background: 'var(--surface)',
                      border: '1px solid var(--line)',
                      borderRadius: 'var(--r-md)',
                      boxShadow: 'var(--shadow-3)',
                      minWidth: 240,
                      padding: 8,
                      zIndex: 10,
                    }}>
                      {cat.sub.map(s => (
                        <button key={s} onClick={() => { onNavigate(`/categoria/${cat.slug}?sub=${encodeURIComponent(s)}`); setOpen(null); }}
                          style={{
                            display: 'flex', width: '100%', textAlign: 'left',
                            padding: '10px 12px', borderRadius: 6,
                            fontSize: 13, fontWeight: 500, color: 'var(--ink-2)',
                          }}
                          onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-2)'}
                          onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
                          {s}
                        </button>
                      ))}
                      <div style={{ height: 1, background: 'var(--line)', margin: '6px 8px' }}/>
                      <button onClick={() => { onNavigate(`/categoria/${cat.slug}`); setOpen(null); }}
                        style={{
                          display: 'flex', width: '100%', textAlign: 'left', alignItems: 'center', justifyContent: 'space-between',
                          padding: '10px 12px', borderRadius: 6,
                          fontSize: 13, fontWeight: 600, color: 'var(--accent)',
                          whiteSpace: 'nowrap',
                        }}>
                        {verTodosLabel(cat.name)}
                        <Icon name="arrowRight" size={14} />
                      </button>
                    </div>
                  )
              )}
            </div>
          ))}
          <button onClick={() => onNavigate('/reparaciones')}
            style={{ padding: '26px 10px', fontSize: 14, fontWeight: 600, color: 'var(--ink-2)', whiteSpace: 'nowrap' }}>
            Reparaciones
          </button>
        </nav>

        <div className="hdr-icons" style={{ display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0 }}>
          {/* Desktop inline search — hidden on mobile via .hdr-search-icon rule */}
          <InlineSearch onNavigate={onNavigate} className="hdr-search-icon" />
          <button onClick={onOpenCart} className="icon-btn" aria-label="Carrito" style={{ position: 'relative' }}>
            <Icon name="cart" size={20}/>
            {cartCount > 0 && (
              <span style={{
                position: 'absolute', top: 4, right: 2,
                background: 'var(--accent)', color: '#fff',
                fontSize: 10, fontWeight: 700,
                minWidth: 16, height: 16, borderRadius: 8,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                padding: '0 4px',
              }}>{cartCount}</span>
            )}
          </button>
          <button onClick={onOpenMenu} className="icon-btn show-mobile" aria-label="Menu">
            <Icon name="menu" size={22}/>
          </button>
        </div>
      </div>
      </header>
    </React.Fragment>
  );
};

// Mobile menu drawer — pro version
const MobileMenu = ({ open, onClose, onNavigate, anim = 'side' }) => {
  const { CATEGORIES } = window.RC_DATA;
  const [expanded, setExpanded] = React.useState(null);
  // Reset accordion when drawer closes
  React.useEffect(() => { if (!open) setExpanded(null); }, [open]);
  if (!open) return null;

  const go = (path) => { onNavigate(path); onClose(); };
  const toggle = (id) => setExpanded(prev => prev === id ? null : id);

  const isTop = anim === 'top';
  const drawerStyle = isTop ? {
    position: 'absolute', top: 0, left: 0, right: 0,
    height: 'min(85vh, 720px)',
    background: 'var(--surface)',
    display: 'flex', flexDirection: 'column',
    boxShadow: '0 14px 32px rgba(11,18,32,0.20)',
    animation: 'mm-slide-down .3s cubic-bezier(.2,.7,.2,1)',
    borderBottomLeftRadius: 18, borderBottomRightRadius: 18,
    overflow: 'hidden',
  } : {
    position: 'absolute', top: 0, right: 0, bottom: 0,
    width: 'min(440px, 85vw)',
    background: 'var(--surface)',
    display: 'flex', flexDirection: 'column',
    boxShadow: '-12px 0 36px rgba(11,18,32,0.18)',
    animation: 'mm-slide .28s cubic-bezier(.2,.7,.2,1)',
  };

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 60 }} role="dialog" aria-modal="true">
      {/* Backdrop */}
      <div onClick={onClose}
        style={{
          position: 'absolute', inset: 0,
          background: 'rgba(11,18,32,0.55)',
          backdropFilter: 'blur(2px)',
          animation: 'mm-fade .25s ease-out',
        }}/>

      {/* Drawer */}
      <aside style={drawerStyle}>
        {/* Header */}
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '18px 20px',
          borderBottom: '1px solid var(--line)',
          flexShrink: 0,
        }}>
          <button onClick={() => go('/')}><Logo height={32}/></button>
          <button onClick={onClose}
            aria-label="Cerrar"
            style={{
              width: 38, height: 38, borderRadius: 19,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              color: 'var(--ink-2)',
            }}>
            <Icon name="close" size={20}/>
          </button>
        </div>

        {/* Scrollable body */}
        <div style={{ flex: 1, overflowY: 'auto', WebkitOverflowScrolling: 'touch' }}>
          {/* Section: Categorías */}
          <div style={{ padding: '20px 4px 8px' }}>
            <div className="mono" style={{
              fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase',
              color: 'var(--ink-4)', padding: '0 16px 8px', fontWeight: 600,
            }}>Comprar por categoría</div>
            {CATEGORIES.map(c => {
              const isOpen = expanded === c.id;
              return (
                <div key={c.id}>
                  <button onClick={() => toggle(c.id)}
                    aria-expanded={isOpen}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 8,
                      width: 'calc(100% - 16px)', margin: '0 8px',
                      padding: '14px 12px',
                      borderRadius: 8,
                      textAlign: 'left',
                      background: isOpen ? 'var(--bg-2)' : 'transparent',
                      transition: 'background .15s ease',
                    }}>
                    <span style={{ flex: 1, fontSize: 15, fontWeight: 600, color: 'var(--ink)' }}>
                      {c.name}
                    </span>
                    <span className="mono" style={{ fontSize: 11, color: 'var(--ink-4)', fontWeight: 400 }}>
                      {c.count}
                    </span>
                    <span style={{
                      display: 'inline-flex', color: 'var(--ink-3)',
                      transform: isOpen ? 'rotate(180deg)' : 'rotate(0)',
                      transition: 'transform .2s ease',
                    }}>
                      <Icon name="chevronDown" size={14}/>
                    </span>
                  </button>

                  {/* Subcategorías — segmentos L2 para segmentadas, lista plana para el resto */}
                  {isOpen && c.segments ? (
                    <div style={{
                      margin: '2px 16px 6px',
                      padding: '4px 0 6px 12px',
                      borderLeft: '2px solid var(--accent)',
                      animation: 'mm-acc-in .22s ease-out',
                    }}>
                      {c.segments
                        .filter(s => ['domesticas','profesionales','industriales'].includes(s.id))
                        .map(seg => (
                          <button key={seg.id} onClick={() => go(`/categoria/${c.slug}/${seg.slug}`)}
                            style={{
                              display: 'block', width: '100%', textAlign: 'left',
                              padding: '8px 10px', borderRadius: 6,
                              fontSize: 13.5, fontWeight: 500, color: 'var(--ink-2)',
                            }}>
                            {seg.name}
                          </button>
                        ))
                      }
                      <button onClick={() => go(`/categoria/${c.slug}`)}
                        style={{
                          display: 'inline-flex', alignItems: 'center', gap: 6,
                          padding: '8px 10px',
                          fontSize: 12, fontWeight: 700, color: 'var(--accent)',
                          textTransform: 'uppercase', letterSpacing: '0.04em',
                          whiteSpace: 'nowrap',
                        }}>
                        {verTodosLabel(c.name).toLowerCase()} <Icon name="arrowRight" size={12}/>
                      </button>
                    </div>
                  ) : isOpen && c.sub?.length > 0 && (
                    <div style={{
                      margin: '2px 16px 6px',
                      padding: '4px 0 6px 12px',
                      borderLeft: '2px solid var(--accent)',
                      animation: 'mm-acc-in .22s ease-out',
                    }}>
                      {c.sub.map(s => (
                        <button key={s} onClick={() => go(`/categoria/${c.slug}?sub=${encodeURIComponent(s)}`)}
                          style={{
                            display: 'block', width: '100%', textAlign: 'left',
                            padding: '8px 10px', borderRadius: 6,
                            fontSize: 13.5, fontWeight: 500, color: 'var(--ink-2)',
                          }}>
                          {s}
                        </button>
                      ))}
                      <button onClick={() => go(`/categoria/${c.slug}`)}
                        style={{
                          display: 'inline-flex', alignItems: 'center', gap: 6,
                          padding: '8px 10px',
                          fontSize: 12, fontWeight: 700, color: 'var(--accent)',
                          textTransform: 'uppercase', letterSpacing: '0.04em',
                          whiteSpace: 'nowrap',
                        }}>
                        {verTodosLabel(c.name).toLowerCase()} <Icon name="arrowRight" size={12}/>
                      </button>
                    </div>
                  )}
                </div>
              );
            })}
          </div>

          <div style={{ height: 1, background: 'var(--line)', margin: '8px 16px 0' }}/>

          {/* Section: Servicios */}
          <div style={{ padding: '16px 4px 8px' }}>
            <div className="mono" style={{
              fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase',
              color: 'var(--ink-4)', padding: '0 16px 8px', fontWeight: 600,
            }}>Servicios</div>
            {[
              { i: 'wrench',  t: 'Servicio técnico',    s: 'Reparaciones todas las marcas', path: '/reparaciones' },
              { i: 'store',   t: 'Quiénes somos',       s: 'Conocé RC Powerclean',           path: '/quienes-somos' },
              { i: 'package', t: 'Mis pedidos',         s: 'Seguí tu compra',                path: '/mis-pedidos' },
              { i: 'pin',     t: 'Sucursal Haedo',      s: 'Lun a Vie 9–18 hs',              path: '/contacto' },
              { i: 'phone',   t: 'Atención al cliente', s: 'WhatsApp +54 11 2518-1264',      path: '/contacto' },
            ].map(it => (
              <button key={it.t} onClick={() => go(it.path)}
                style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  width: 'calc(100% - 16px)', margin: '0 8px',
                  padding: '12px 12px', borderRadius: 8,
                  textAlign: 'left',
                }}
                onMouseDown={(e) => e.currentTarget.style.background = 'var(--bg-2)'}
                onMouseUp={(e) => e.currentTarget.style.background = 'transparent'}>
                <span style={{
                  width: 36, height: 36, borderRadius: 8,
                  background: 'var(--bg-2)', color: 'var(--ink)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                }}>
                  <Icon name={it.i} size={16}/>
                </span>
                <span style={{ minWidth: 0 }}>
                  <span style={{ display: 'block', fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>{it.t}</span>
                  <span style={{ display: 'block', fontSize: 12, color: 'var(--ink-3)' }}>{it.s}</span>
                </span>
              </button>
            ))}
          </div>
        </div>

        {/* Footer CTA */}
        <div style={{
          flexShrink: 0,
          padding: 14,
          borderTop: '1px solid var(--line)',
          background: 'var(--bg-2)',
        }}>
          <a href="https://wa.me/541125181264" target="_blank" rel="noopener"
            style={{
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              padding: '12px 14px',
              background: '#25D366', color: '#fff',
              borderRadius: 10,
              fontSize: 14, fontWeight: 700,
              textDecoration: 'none',
            }}>
            <Icon name="whatsapp" size={18}/> Consultar por WhatsApp
          </a>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 12, fontSize: 11.5, color: 'var(--ink-3)' }}>
            <span>© RC Powerclean</span>
            <span>· Haedo, BA</span>
          </div>
        </div>
      </aside>

      {/* Animations */}
      <style>{`
        @keyframes mm-fade { from { opacity: 0; } to { opacity: 1; } }
        @keyframes mm-slide { from { transform: translateX(100%); } to { transform: translateX(0); } }
        @keyframes mm-slide-down { from { transform: translateY(-100%); } to { transform: translateY(0); } }
        @keyframes mm-acc-in { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: translateY(0); } }
      `}</style>
    </div>
  );
};

// Inline desktop search — pill input that lives in the header, dropdown of
// product matches appears directly below as the user types. Replaces the old
// search icon → modal flow on desktop. Hidden on mobile (mobile keeps the
// "hdr-mobile-search-inline" button + SearchModal).
const InlineSearch = ({ onNavigate, className = '' }) => {
  const { PRODUCTS, ARS } = window.RC_DATA;
  const [q, setQ] = React.useState('');
  const [focused, setFocused] = React.useState(false);
  const rootRef = React.useRef(null);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    if (!focused) return;
    const onDown = (e) => {
      if (rootRef.current && !rootRef.current.contains(e.target)) setFocused(false);
    };
    const onKey = (e) => { if (e.key === 'Escape') { setFocused(false); inputRef.current?.blur(); } };
    document.addEventListener('mousedown', onDown);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('mousedown', onDown);
      document.removeEventListener('keydown', onKey);
    };
  }, [focused]);

  const results = q.trim().length > 0
    ? PRODUCTS.filter((p) => (p.name + ' ' + p.brand + ' ' + p.sku).toLowerCase().includes(q.toLowerCase())).slice(0, 5)
    : [];
  const showDropdown = focused && q.trim().length > 0;

  return (
    <div ref={rootRef} className={'hdr-inline-search ' + className}
      style={{ position: 'relative', width: 240, flexShrink: 0 }}>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8,
        padding: '9px 14px',
        background: 'var(--surface)',
        border: '1px solid ' + (focused ? 'var(--ink-2)' : 'var(--line-2)'),
        borderRadius: 999,
        transition: 'border-color .15s',
        boxShadow: focused ? '0 4px 14px rgba(0,0,0,0.06)' : 'none'
      }}>
        <input
          ref={inputRef}
          value={q}
          onChange={(e) => setQ(e.target.value)}
          onFocus={() => setFocused(true)}
          placeholder="Buscar productos"
          style={{
            flex: 1, minWidth: 0,
            fontSize: 13, color: 'var(--ink)',
            border: 'none', outline: 'none', background: 'transparent'
          }} />
        <Icon name="search" size={16} />
      </div>

      {showDropdown &&
      <div style={{
        position: 'absolute', top: 'calc(100% + 8px)',
        right: 0, left: 'auto',
        width: 420,
        background: 'var(--surface)',
        borderRadius: 12, overflow: 'hidden',
        boxShadow: 'var(--shadow-3)',
        border: '1px solid var(--line)',
        maxHeight: 460, overflowY: 'auto',
        zIndex: 40
      }}>
          {results.length === 0 ?
        <div style={{ padding: 22, textAlign: 'center', color: 'var(--ink-4)', fontSize: 13 }}>
              Sin resultados para "{q}".
            </div> :
        results.map((p, idx) =>
        <button key={p.id}
        onClick={() => {onNavigate(`/producto/${p.id}`);setQ('');setFocused(false);}}
        style={{
          display: 'flex', alignItems: 'center', gap: 14,
          width: '100%', padding: '12px 16px', textAlign: 'left',
          borderTop: idx === 0 ? 'none' : '1px solid var(--line)',
          background: 'transparent'
        }}
        onMouseEnter={(e) => e.currentTarget.style.background = 'var(--bg-2)'}
        onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}>
              <div style={{
            width: 72, height: 72, flexShrink: 0,
            background: '#FFF', border: '1px solid var(--line)',
            borderRadius: 8,
            display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden'
          }}>
                {p.image ?
            <img src={p.image} alt={p.name} style={{ width: '100%', height: '100%', objectFit: 'contain', padding: 6 }} /> :
            <span className="mono t-xs" style={{ fontSize: 10 }}>{p.brand}</span>}
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{
                  fontWeight: 600, fontSize: 13, lineHeight: 1.3,
                  display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
                  overflow: 'hidden'
                }}>{p.name}</div>
              </div>
              <div style={{ fontWeight: 700, fontSize: 13, whiteSpace: 'nowrap' }}>{ARS(p.price)}</div>
            </button>
        )}
        </div>
      }
    </div>);

};

// Search modal — variant-driven (different layouts for desktop & mobile)
const SearchModal = ({ open, onClose, onNavigate, desktopStyle = 'centered', mobileStyle = 'modal' }) => {
  const [q, setQ] = React.useState('');
  const { PRODUCTS } = window.RC_DATA;
  // Track viewport so we can switch between desktop & mobile variants live.
  const [isMobile, setIsMobile] = React.useState(() => typeof window !== 'undefined' && window.innerWidth < 768);
  React.useEffect(() => {
    const onR = () => setIsMobile(window.innerWidth < 768);
    window.addEventListener('resize', onR);
    return () => window.removeEventListener('resize', onR);
  }, []);
  // Reset query on close.
  React.useEffect(() => { if (!open) setQ(''); }, [open]);

  const results = q.trim().length > 0
    ? PRODUCTS.filter(p => (p.name + ' ' + p.brand + ' ' + p.sku).toLowerCase().includes(q.toLowerCase())).slice(0, 8)
    : [];
  if (!open) return null;

  const variant = isMobile ? mobileStyle : desktopStyle;

  // ─────────────────────────── shared bits ────────────────────────────────
  const popularTerms = ['Karma K-160', 'Kärcher HD', 'IPC 3070', 'Pico turbo 015', 'Manguera 10m', 'Bomba AR'];

  const InputBar = ({ dark, mono, big }) => (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10,
      padding: big ? '22px 24px' : '16px 20px',
      borderBottom: '1px solid ' + (dark ? 'rgba(255,255,255,0.08)' : 'var(--line)'),
      background: dark ? '#0F1622' : 'transparent'
    }}>
      <Icon name="search" size={big ? 22 : 20} />
      <input
        autoFocus
        value={q} onChange={(e) => setQ(e.target.value)}
        placeholder={mono ? 'Search products, brands, SKUs…' : 'Buscar hidrolavadoras, repuestos, marcas…'}
        style={{
          flex: 1, fontSize: big ? 19 : 17, border: 'none', outline: 'none', background: 'transparent',
          color: dark ? '#fff' : 'var(--ink)',
          fontFamily: mono ? "'JetBrains Mono', ui-monospace, monospace" : undefined,
          letterSpacing: mono ? '-0.01em' : undefined
        }} />
      <button onClick={onClose} className="mono" style={{
        fontSize: 11,
        color: dark ? 'rgba(255,255,255,0.5)' : 'var(--ink-4)',
        border: '1px solid ' + (dark ? 'rgba(255,255,255,0.15)' : 'var(--line-2)'),
        padding: '3px 6px', borderRadius: 4
      }}>ESC</button>
    </div>);


  const PopularChips = ({ dark, label = 'Populares' }) => (
    <div style={{ padding: 20 }}>
      <div className="eyebrow" style={{ marginBottom: 10, color: dark ? 'rgba(255,255,255,0.5)' : undefined }}>{label}</div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        {popularTerms.map((t) =>
        <button key={t} onClick={() => setQ(t)}
        style={{
          fontSize: 13, padding: '6px 12px', borderRadius: 999,
          border: '1px solid ' + (dark ? 'rgba(255,255,255,0.15)' : 'var(--line-2)'),
          color: dark ? 'rgba(255,255,255,0.85)' : 'var(--ink-2)',
          background: dark ? 'rgba(255,255,255,0.04)' : 'transparent'
        }}>{t}</button>
        )}
      </div>
    </div>);


  const ResultRow = ({ p, dark }) =>
  <button key={p.id} onClick={() => {onNavigate(`/producto/${p.id}`);onClose();}}
  style={{
    display: 'flex', alignItems: 'center', gap: 14, width: '100%',
    padding: '12px 20px', textAlign: 'left',
    borderTop: '1px solid ' + (dark ? 'rgba(255,255,255,0.06)' : 'var(--line)'),
    color: dark ? '#fff' : 'inherit'
  }}>
      <div style={{
      width: 48, height: 48, flexShrink: 0,
      background: dark ? '#fff' : '#FFF',
      border: '1px solid ' + (dark ? 'rgba(255,255,255,0.08)' : 'var(--line)'),
      borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden'
    }}>
        {p.image ?
      <img src={p.image} alt={p.name} style={{ width: '100%', height: '100%', objectFit: 'contain', padding: 4 }} /> :
      <span className="mono t-xs" style={{ fontSize: 9, color: '#333' }}>{p.brand}</span>}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontWeight: 600, fontSize: 14, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.name}</div>
        <div className="mono t-xs" style={{ color: dark ? 'rgba(255,255,255,0.5)' : undefined }}>{p.sku} — {p.brand}</div>
      </div>
      <div style={{ fontWeight: 700, whiteSpace: 'nowrap' }}>{window.RC_DATA.ARS(p.price)}</div>
    </button>;


  const EmptyState = ({ dark }) =>
  <div style={{ padding: 30, textAlign: 'center', color: dark ? 'rgba(255,255,255,0.5)' : 'var(--ink-4)' }}>
      Sin resultados para "{q}".
    </div>;


  // ─────────────────────────── desktop variants ───────────────────────────
  if (!isMobile) {
    // dark "command palette" (Cmd-K) variant
    if (desktopStyle === 'command') {
      return (
        <div style={{ position: 'fixed', inset: 0, zIndex: 70 }}>
          <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(8,12,20,0.78)', backdropFilter: 'blur(4px)' }} />
          <div style={{
            position: 'absolute', top: 100, left: '50%', transform: 'translateX(-50%)',
            width: 'min(560px, 94vw)',
            background: '#0F1622', color: '#fff',
            borderRadius: 14, overflow: 'hidden',
            boxShadow: '0 30px 80px rgba(0,0,0,0.55), 0 0 0 1px rgba(255,255,255,0.06)'
          }}>
            <InputBar dark mono />
            <div style={{ maxHeight: 420, overflowY: 'auto', background: '#0B121E' }}>
              {q.trim().length === 0 && <PopularChips dark label="// Sugerencias" />}
              {results.map((p) => <ResultRow key={p.id} p={p} dark />)}
              {q.trim().length > 0 && results.length === 0 && <EmptyState dark />}
            </div>
            <div style={{
              padding: '10px 16px', borderTop: '1px solid rgba(255,255,255,0.06)',
              display: 'flex', gap: 14, justifyContent: 'flex-end',
              fontSize: 11, color: 'rgba(255,255,255,0.5)'
            }} className="mono">
              <span>↑↓ navegar</span><span>↵ abrir</span><span>esc cerrar</span>
            </div>
          </div>
        </div>);

    }

    // full-width top bar (Algolia-style)
    if (desktopStyle === 'fullbar') {
      return (
        <div style={{ position: 'fixed', inset: 0, zIndex: 70 }}>
          <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.45)' }} />
          <div style={{
            position: 'absolute', top: 0, left: 0, right: 0,
            background: 'var(--surface)',
            boxShadow: '0 12px 32px rgba(11,18,32,0.18)',
            animation: 'sm-slide-down .25s ease'
          }}>
            <style>{`@keyframes sm-slide-down { from { transform: translateY(-100%); } to { transform: translateY(0); } }`}</style>
            <div style={{ maxWidth: 980, margin: '0 auto' }}>
              <InputBar big />
              <div style={{ maxHeight: 'calc(100vh - 200px)', overflowY: 'auto' }}>
                {q.trim().length === 0 && <PopularChips />}
                {results.map((p) => <ResultRow key={p.id} p={p} />)}
                {q.trim().length > 0 && results.length === 0 && <EmptyState />}
              </div>
            </div>
          </div>
        </div>);

    }

    // big two-column variant (results left, popular/categories right)
    if (desktopStyle === 'bigsplit') {
      const { CATEGORIES } = window.RC_DATA;
      return (
        <div style={{ position: 'fixed', inset: 0, zIndex: 70 }}>
          <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.55)' }} />
          <div style={{
            position: 'absolute', top: 60, left: '50%', transform: 'translateX(-50%)',
            width: 'min(880px, 94vw)',
            background: 'var(--surface)', borderRadius: 14, overflow: 'hidden',
            boxShadow: 'var(--shadow-3)'
          }}>
            <InputBar />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 240px', maxHeight: 520 }}>
              <div style={{ overflowY: 'auto', borderRight: '1px solid var(--line)' }}>
                {q.trim().length === 0 && <PopularChips label="Búsquedas frecuentes" />}
                {results.map((p) => <ResultRow key={p.id} p={p} />)}
                {q.trim().length > 0 && results.length === 0 && <EmptyState />}
              </div>
              <div style={{ padding: 20, background: 'var(--bg-2)', overflowY: 'auto' }}>
                <div className="eyebrow" style={{ marginBottom: 10 }}>Categorías</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                  {CATEGORIES.map((c) =>
                  <button key={c.id} onClick={() => {onNavigate(`/categoria/${c.slug}`);onClose();}}
                  style={{
                    textAlign: 'left', padding: '8px 10px', borderRadius: 6,
                    fontSize: 13, fontWeight: 600, color: 'var(--ink-2)'
                  }}>
                      {c.name}<span className="mono t-xs" style={{ marginLeft: 6, opacity: 0.6 }}>({c.count})</span>
                    </button>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>);

    }

    // default — centered modal
    return (
      <div style={{ position: 'fixed', inset: 0, zIndex: 70 }}>
        <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.6)' }} />
        <div style={{
          position: 'absolute', top: 80, left: '50%', transform: 'translateX(-50%)',
          width: 'min(640px, 94vw)',
          background: 'var(--surface)', borderRadius: 'var(--r-lg)', overflow: 'hidden',
          boxShadow: 'var(--shadow-3)'
        }}>
          <InputBar />
          <div style={{ maxHeight: 420, overflowY: 'auto' }}>
            {q.trim().length === 0 && <PopularChips />}
            {results.map((p) => <ResultRow key={p.id} p={p} />)}
            {q.trim().length > 0 && results.length === 0 && <EmptyState />}
          </div>
        </div>
      </div>);

  }

  // ─────────────────────────── mobile variants ────────────────────────────

  // fullscreen takeover
  if (mobileStyle === 'fullscreen') {
    return (
      <div style={{ position: 'fixed', inset: 0, zIndex: 70, background: 'var(--surface)', display: 'flex', flexDirection: 'column', animation: 'sm-fade .2s ease' }}>
        <style>{`@keyframes sm-fade { from { opacity: 0; } to { opacity: 1; } }`}</style>
        <InputBar />
        <div style={{ flex: 1, overflowY: 'auto' }}>
          {q.trim().length === 0 && <PopularChips />}
          {results.map((p) => <ResultRow key={p.id} p={p} />)}
          {q.trim().length > 0 && results.length === 0 && <EmptyState />}
        </div>
      </div>);

  }

  // bottom sheet — slides up from the bottom
  if (mobileStyle === 'bottomsheet') {
    return (
      <div style={{ position: 'fixed', inset: 0, zIndex: 70 }}>
        <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.55)' }} />
        <div style={{
          position: 'absolute', left: 0, right: 0, bottom: 0,
          background: 'var(--surface)',
          borderTopLeftRadius: 18, borderTopRightRadius: 18,
          overflow: 'hidden', display: 'flex', flexDirection: 'column',
          maxHeight: '88vh',
          animation: 'sm-slide-up .25s cubic-bezier(.2,.7,.2,1)'
        }}>
          <style>{`@keyframes sm-slide-up { from { transform: translateY(100%); } to { transform: translateY(0); } }`}</style>
          <div style={{ display: 'flex', justifyContent: 'center', padding: '10px 0 4px' }}>
            <div style={{ width: 40, height: 4, borderRadius: 2, background: 'var(--line-2)' }} />
          </div>
          <InputBar />
          <div style={{ flex: 1, overflowY: 'auto' }}>
            {q.trim().length === 0 && <PopularChips />}
            {results.map((p) => <ResultRow key={p.id} p={p} />)}
            {q.trim().length > 0 && results.length === 0 && <EmptyState />}
          </div>
        </div>
      </div>);

  }

  // dropdown — drops from below the header, no backdrop card padding
  if (mobileStyle === 'dropdown') {
    return (
      <div style={{ position: 'fixed', inset: 0, zIndex: 70 }}>
        <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.4)' }} />
        <div style={{
          position: 'absolute', top: 0, left: 0, right: 0,
          background: 'var(--surface)',
          boxShadow: '0 8px 24px rgba(0,0,0,0.18)',
          animation: 'sm-drop .22s ease'
        }}>
          <style>{`@keyframes sm-drop { from { transform: translateY(-100%); } to { transform: translateY(0); } }`}</style>
          <InputBar />
          <div style={{ maxHeight: 'calc(100vh - 200px)', overflowY: 'auto' }}>
            {q.trim().length === 0 && <PopularChips />}
            {results.map((p) => <ResultRow key={p.id} p={p} />)}
            {q.trim().length > 0 && results.length === 0 && <EmptyState />}
          </div>
        </div>
      </div>);

  }

  // default mobile modal — same as desktop centered, but tighter
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 70 }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.6)' }} />
      <div style={{
        position: 'absolute', top: 60, left: '50%', transform: 'translateX(-50%)',
        width: 'min(640px, 94vw)',
        background: 'var(--surface)', borderRadius: 'var(--r-lg)', overflow: 'hidden',
        boxShadow: 'var(--shadow-3)'
      }}>
        <InputBar />
        <div style={{ maxHeight: '70vh', overflowY: 'auto' }}>
          {q.trim().length === 0 && <PopularChips />}
          {results.map((p) => <ResultRow key={p.id} p={p} />)}
          {q.trim().length > 0 && results.length === 0 && <EmptyState />}
        </div>
      </div>
    </div>);

};

Object.assign(window, { HeaderBar, MobileMenu, SearchModal, InlineSearch, verTodosLabel });
