// Top + nav

function useNavWidth() {
  const [w, setW] = React.useState(window.innerWidth);
  React.useEffect(() => {
    const h = () => setW(window.innerWidth);
    window.addEventListener('resize', h);
    return () => window.removeEventListener('resize', h);
  }, []);
  return w;
}

function Topbar() {
  const items = window.TICKER;
  const list = [...items, ...items, ...items];
  return (
    <div style={{
      background: '#0a0a0a',
      borderBottom: '1px solid rgba(255,255,255,0.06)',
      color: 'rgba(255,255,255,0.7)',
      fontSize: 12,
      letterSpacing: '0.04em',
      overflow: 'hidden',
      position: 'relative',
    }}>
      <div className="sat-marquee" style={{
        display: 'flex', gap: 48, padding: '10px 0',
        whiteSpace: 'nowrap', width: 'max-content',
        animation: 'sat-marquee 38s linear infinite',
      }}>
        {list.map((t, i) => (
          <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 10 }}>
            <span style={{
              width: 5, height: 5, borderRadius: 999, background: '#2ECC71',
              boxShadow: '0 0 8px #2ECC71',
            }}/>
            {t}
          </span>
        ))}
      </div>
    </div>
  );
}

const NAV_ITEMS = [
  { label: 'Categorías',           dropdown: true,  page: 'categorias' },
  { label: 'Ofertas',              dropdown: false, gold: true, page: 'ofertas' },
  { label: 'Marcas',               dropdown: false, page: 'marcas' },
  { label: 'Ubicación y contacto', dropdown: false, page: 'ubicacion' },
  { label: 'Consultas frecuentes', dropdown: false, page: 'consultas' },
];

function Navbar({ cartCount, onOpenCart, onSearch, onNavigate, currentPage }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [catOpen, setCatOpen] = React.useState(false);
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const [q, setQ] = React.useState('');
  const vw = useNavWidth();
  const isMobile = vw < 900;

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  React.useEffect(() => {
    if (!isMobile) setMobileOpen(false);
  }, [isMobile]);

  return (
    <header
      onMouseLeave={() => !isMobile && setCatOpen(false)}
      style={{
        position: 'sticky', top: 0, zIndex: 50,
        background: scrolled ? 'rgba(17,17,17,0.92)' : 'rgba(17,17,17,0.6)',
        backdropFilter: 'blur(18px) saturate(140%)',
        WebkitBackdropFilter: 'blur(18px) saturate(140%)',
        borderBottom: '1px solid ' + (scrolled ? 'rgba(255,255,255,0.08)' : 'rgba(255,255,255,0.04)'),
        transition: 'all 240ms ease',
      }}>

      {/* ── Barra principal ── */}
      <div style={{
        maxWidth: 1320, margin: '0 auto',
        padding: isMobile ? '12px 20px' : '14px 32px',
        display: 'flex', alignItems: 'center',
        justifyContent: 'space-between',
        gap: 16,
      }}>
        <div onClick={() => onNavigate && onNavigate('home')} style={{ cursor: 'pointer' }}>
          <window.Logo size={isMobile ? 20 : 22} />
        </div>

        {/* Nav central — solo desktop */}
        {!isMobile && (
          <nav style={{ display: 'flex', justifyContent: 'center', gap: 4 }}>
            {NAV_ITEMS.map(({ label, dropdown, gold, page }) => {
              const isActive = currentPage === page;
              return (
                <button
                  key={label}
                  onMouseEnter={() => setCatOpen(dropdown)}
                  onClick={() => {
                    if (dropdown) setCatOpen(!catOpen);
                    onNavigate && onNavigate(page);
                  }}
                  style={{
                    background: isActive ? 'rgba(46,204,113,0.08)' : 'none',
                    border: 'none',
                    padding: '10px 14px', borderRadius: 8,
                    color: isActive ? '#2ECC71' : (gold ? '#C9A84C' : (catOpen && dropdown ? '#2ECC71' : 'rgba(255,255,255,0.86)')),
                    fontFamily: '"Sora", system-ui, sans-serif',
                    fontSize: 14, letterSpacing: '0.01em', fontWeight: isActive ? 600 : 500,
                    cursor: 'pointer',
                    transition: 'color 200ms ease, background 200ms ease',
                    display: 'inline-flex', alignItems: 'center', gap: 5,
                  }}
                >
                  {label}
                  {dropdown && (
                    <svg width="10" height="6" viewBox="0 0 10 6" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
                      <path d="M1 1l4 4 4-4"/>
                    </svg>
                  )}
                </button>
              );
            })}
          </nav>
        )}

        {/* Derecha: buscador + iconos (desktop) | carrito + hamburger (mobile) */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          {!isMobile && (
            <form
              onSubmit={(e) => { e.preventDefault(); onSearch && onSearch(q); }}
              style={{
                display: 'flex', alignItems: 'center', gap: 8,
                background: 'rgba(255,255,255,0.04)',
                border: '1px solid rgba(255,255,255,0.08)',
                borderRadius: 10, padding: '8px 12px',
                color: 'rgba(255,255,255,0.6)',
                minWidth: 220,
              }}
            >
              {window.Icon.search(15)}
              <input
                value={q}
                onChange={(e) => setQ(e.target.value)}
                placeholder="Buscar 500+ productos…"
                style={{
                  background: 'transparent', border: 'none', outline: 'none',
                  color: '#fff', fontSize: 13, width: '100%',
                  fontFamily: 'Inter, system-ui, sans-serif',
                }}
              />
              <span style={{
                fontFamily: 'ui-monospace, monospace', fontSize: 10,
                color: 'rgba(255,255,255,0.4)',
                border: '1px solid rgba(255,255,255,0.12)',
                padding: '1px 5px', borderRadius: 4,
              }}>⌘K</span>
            </form>
          )}

          {!isMobile && <NavIcon>{window.Icon.user(18)}</NavIcon>}

          {/* Carrito siempre visible */}
          <button onClick={onOpenCart} style={{
            position: 'relative',
            background: 'rgba(46,204,113,0.10)',
            border: '1px solid rgba(46,204,113,0.35)',
            color: '#2ECC71', borderRadius: 10,
            padding: '8px 12px', cursor: 'pointer',
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            {window.Icon.cart(18)}
            {!isMobile && (
              <span style={{ fontSize: 13, fontFamily: '"Sora", sans-serif', fontWeight: 600, color: '#fff' }}>
                {window.fmtCLP(0)}
              </span>
            )}
            {cartCount > 0 && (
              <span style={{
                position: 'absolute', top: -6, right: -6,
                width: 18, height: 18, borderRadius: 999,
                background: '#2ECC71', color: '#0a0a0a',
                fontSize: 10, fontWeight: 700,
                display: 'grid', placeItems: 'center',
                border: '2px solid #111',
              }}>{cartCount}</span>
            )}
          </button>

          {/* Hamburger — solo mobile */}
          {isMobile && (
            <button
              onClick={() => setMobileOpen(!mobileOpen)}
              aria-label="Menú"
              style={{
                background: 'rgba(255,255,255,0.04)',
                border: '1px solid rgba(255,255,255,0.08)',
                color: '#fff', borderRadius: 10,
                width: 40, height: 40, cursor: 'pointer',
                display: 'flex', flexDirection: 'column',
                alignItems: 'center', justifyContent: 'center', gap: 5,
                padding: 0,
              }}
            >
              <span style={{
                width: 18, height: 1.5, background: mobileOpen ? '#2ECC71' : '#fff',
                borderRadius: 2,
                transform: mobileOpen ? 'rotate(45deg) translate(5px, 5px)' : 'none',
                transition: 'all 200ms',
              }}/>
              <span style={{
                width: 18, height: 1.5, background: mobileOpen ? '#2ECC71' : '#fff',
                borderRadius: 2,
                opacity: mobileOpen ? 0 : 1,
                transition: 'all 200ms',
              }}/>
              <span style={{
                width: 18, height: 1.5, background: mobileOpen ? '#2ECC71' : '#fff',
                borderRadius: 2,
                transform: mobileOpen ? 'rotate(-45deg) translate(5px, -5px)' : 'none',
                transition: 'all 200ms',
              }}/>
            </button>
          )}
        </div>
      </div>

      {/* ── Menú mobile desplegable ── */}
      {isMobile && mobileOpen && (
        <div style={{
          background: 'rgba(13,13,13,0.98)',
          borderTop: '1px solid rgba(255,255,255,0.06)',
          padding: '16px 20px 24px',
        }}>
          {/* Buscador mobile */}
          <form
            onSubmit={(e) => { e.preventDefault(); onSearch && onSearch(q); setMobileOpen(false); }}
            style={{
              display: 'flex', alignItems: 'center', gap: 8,
              background: 'rgba(255,255,255,0.04)',
              border: '1px solid rgba(255,255,255,0.08)',
              borderRadius: 10, padding: '10px 14px',
              marginBottom: 16,
            }}
          >
            {window.Icon.search(15)}
            <input
              value={q}
              onChange={(e) => setQ(e.target.value)}
              placeholder="Buscar productos…"
              style={{
                background: 'transparent', border: 'none', outline: 'none',
                color: '#fff', fontSize: 14, width: '100%',
                fontFamily: 'Inter, system-ui, sans-serif',
              }}
            />
          </form>

          {/* Links de nav */}
          <nav style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            {NAV_ITEMS.map(({ label, gold, page }) => {
              const isActive = currentPage === page;
              return (
                <button
                  key={label}
                  onClick={() => { setMobileOpen(false); onNavigate && onNavigate(page); }}
                  style={{
                    background: isActive ? 'rgba(46,204,113,0.07)' : 'none',
                    border: 'none',
                    padding: '13px 8px',
                    borderBottom: '1px solid rgba(255,255,255,0.05)',
                    color: isActive ? '#2ECC71' : (gold ? '#C9A84C' : 'rgba(255,255,255,0.86)'),
                    fontFamily: '"Sora", system-ui, sans-serif',
                    fontSize: 15, fontWeight: isActive ? 600 : 500, textAlign: 'left',
                    cursor: 'pointer',
                    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                  }}
                >
                  {label}
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
                    <path d="M9 6l6 6-6 6"/>
                  </svg>
                </button>
              );
            })}
          </nav>
        </div>
      )}

      {/* Mega-menú categorías — solo desktop */}
      {!isMobile && catOpen && <CategoriesDropdown onClose={() => setCatOpen(false)} />}
    </header>
  );
}

function NavIcon({ children }) {
  return (
    <button style={{
      background: 'rgba(255,255,255,0.04)',
      border: '1px solid rgba(255,255,255,0.08)',
      color: '#fff', borderRadius: 10,
      padding: 9, cursor: 'pointer',
      display: 'grid', placeItems: 'center',
      transition: 'all 200ms',
    }}>{children}</button>
  );
}

function CategoriesDropdown({ onClose }) {
  const cats = window.NAV_CATEGORIES;
  return (
    <div
      onMouseLeave={onClose}
      style={{
        position: 'absolute', left: 0, right: 0, top: '100%',
        background: 'rgba(17,17,17,0.96)',
        backdropFilter: 'blur(20px)',
        borderTop: '1px solid rgba(46,204,113,0.18)',
        borderBottom: '1px solid rgba(255,255,255,0.06)',
        animation: 'sat-fade 220ms ease',
        padding: '28px 32px',
      }}
    >
      <div style={{ maxWidth: 1320, margin: '0 auto' }}>
        <div style={{
          fontFamily: 'ui-monospace, monospace',
          fontSize: 11, color: '#2ECC71', letterSpacing: '0.18em',
          marginBottom: 18, textTransform: 'uppercase',
        }}>Categorías</div>
        <ul style={{
          listStyle: 'none', margin: 0, padding: 0,
          display: 'grid',
          gridTemplateColumns: 'repeat(3, minmax(0, 200px))',
          gap: '12px 48px',
        }}>
          {cats.map((cat) => (
            <li key={cat}>
              <a href="#" style={{
                color: cat === 'Todos' ? '#2ECC71' : '#fff',
                textDecoration: 'none', fontSize: 15,
                fontFamily: 'Inter, sans-serif',
                display: 'inline-flex', alignItems: 'center', gap: 10,
                fontWeight: cat === 'Todos' ? 600 : 400,
              }}>
                <span style={{ width: 14, height: 1, background: 'rgba(46,204,113,0.6)', flexShrink: 0 }}/>
                {cat}
              </a>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}

Object.assign(window, { Topbar, Navbar });
