/* global React, SFIcons */
const { Search, Cart, User, Truck, Phone, MapPin, Menu, ChevronDown, Grid, Package, CreditCard, LogOut } = SFIcons;
const { IconButton } = window.MADECIDesignSystem_419fb1;

function TopBar() {
  return (
    <div style={{ background: 'var(--madeci-ink)', color: 'rgba(255,255,255,.82)' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 24px', height: 38, display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontFamily: 'var(--font-body)', fontSize: 13 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <Truck size={15} stroke="var(--madeci-red)" />
          <span>Reparto en <strong style={{ color: '#fff' }}>San Antonio</strong> y alrededores · Despacho express</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 22 }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 7 }}><Phone size={14} /> WhatsApp +56 9 9443 7835</span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 7 }}><Phone size={14} /> Call center 600 612 9877</span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 7 }}><MapPin size={14} /> Sucursal Cartagena</span>
        </div>
      </div>
    </div>
  );
}

function AccountMenu({ account, onAccount, onLogout }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  React.useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, []);
  const item = (Icon, label, onClick, danger) => (
    <button onClick={() => { setOpen(false); onClick(); }} style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', textAlign: 'left', padding: '10px 14px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14, color: danger ? 'var(--madeci-red)' : 'var(--text-body)' }}
      onMouseEnter={(e) => e.currentTarget.style.background = 'var(--neutral-50)'} onMouseLeave={(e) => e.currentTarget.style.background = 'none'}>
      <Icon size={17} stroke={danger ? 'var(--madeci-red)' : 'var(--text-muted)'} /> {label}
    </button>
  );
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button onClick={() => setOpen((o) => !o)} style={accBtn}>
        <User size={20} />
        <span style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', lineHeight: 1.1 }}>
          <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>Mi cuenta</span>
          <strong style={{ fontSize: 13.5, color: 'var(--text-strong)' }}>{account ? account.name.replace(' SpA', '') : 'Minimarket El Sol'}</strong>
        </span>
        <ChevronDown size={15} stroke="var(--text-muted)" style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .15s' }} />
      </button>
      {open && (
        <div style={{ position: 'absolute', right: 0, top: 'calc(100% + 8px)', width: 220, background: 'var(--surface-card)', border: '1px solid var(--border-subtle)', borderRadius: 'var(--radius-md)', boxShadow: 'var(--shadow-lg)', padding: '6px 0', zIndex: 60 }}>
          <div style={{ padding: '8px 14px 10px', borderBottom: '1px solid var(--border-subtle)', marginBottom: 4 }}>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 14, color: 'var(--text-strong)' }}>{account ? account.name : 'Minimarket El Sol SpA'}</div>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--text-muted)' }}>{account ? account.code : 'C-04821'}</div>
          </div>
          {item(Grid, 'Mi cuenta', onAccount)}
          {item(Package, 'Mis pedidos', onAccount)}
          <div style={{ borderTop: '1px solid var(--border-subtle)', margin: '4px 0' }} />
          {item(LogOut, 'Cerrar sesión', onLogout, true)}
        </div>
      )}
    </div>
  );
}

function Header({ cartCount, categories, onCart, onLogo, onAccount, onLogout, onEnter, onShop, onCategory, loggedIn, account, query, setQuery }) {
  return (
    <header style={{ position: 'sticky', top: 0, zIndex: 40, background: 'var(--surface-card)', boxShadow: 'var(--shadow-sm)' }}>
      <TopBar />
      <div style={{ borderBottom: '1px solid var(--border-subtle)' }}>
        <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 24px', height: 78, display: 'flex', alignItems: 'center', gap: 28 }}>
          <img src="assets/logo-horizontal.png" alt="MADECI" onClick={onLogo}
            style={{ height: 46, cursor: 'pointer' }} />
          <div style={{ flex: 1, maxWidth: 560, display: 'flex', alignItems: 'center', gap: 10, height: 46, padding: '0 16px', background: 'var(--neutral-50)', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-sm)' }}>
            <Search size={18} stroke="var(--text-muted)" />
            <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Buscar por producto, marca o SKU…"
              style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', fontFamily: 'var(--font-body)', fontSize: 15, color: 'var(--text-strong)' }} />
          </div>
          <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 12 }}>
            {loggedIn
              ? <AccountMenu account={account} onAccount={onAccount} onLogout={onLogout} />
              : <button onClick={onEnter} style={accBtn}><User size={20} /><span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15.5, color: 'var(--text-strong)' }}>Entrar</span></button>}
            <button onClick={onCart} style={{ ...accBtn, position: 'relative' }}>
              <span style={{ position: 'relative', display: 'flex' }}>
                <Cart size={22} stroke="var(--text-strong)" />
                {cartCount > 0 && <span style={cartBadge}>{cartCount}</span>}
              </span>
              <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14, color: 'var(--text-strong)' }}>Carrito</span>
            </button>
          </div>
        </div>
      </div>
      <CategoryNav categories={categories} onShop={onShop} onCategory={onCategory} />
    </header>
  );
}

function CategoryNav({ categories, onShop, onCategory }) {
  // Se arma con las categorías REALES que llegan de Random (no una lista fija).
  const cats = Array.isArray(categories) ? categories : [];
  return (
    <nav style={{ background: 'var(--surface-card)', borderBottom: '1px solid var(--border-subtle)' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 24px', height: 48, display: 'flex', alignItems: 'center', gap: 8 }}>
        <button onClick={onShop} style={{ ...navItem, flex: 'none', color: '#fff', background: 'var(--madeci-red)', borderRadius: 'var(--radius-sm)', cursor: 'pointer' }}>
          <Menu size={16} /> Todas las categorías
        </button>
        <div style={{ flex: 1, minWidth: 0, display: 'flex', alignItems: 'center', gap: 4, overflowX: 'auto' }}>
          {cats.map((c) => <button key={c.id || c.name} onClick={() => onCategory(c.name)} style={{ ...navItem, flex: 'none', whiteSpace: 'nowrap' }} onMouseEnter={(e) => e.currentTarget.style.color = 'var(--madeci-red)'} onMouseLeave={(e) => e.currentTarget.style.color = 'var(--text-body)'}>{c.name}</button>)}
        </div>
        <span style={{ flex: 'none', display: 'flex', alignItems: 'center', gap: 7, fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 13, color: 'var(--status-success)' }}>
          <Truck size={16} /> Pedido mínimo $30.000
        </span>
      </div>
    </nav>
  );
}

const accBtn = { display: 'flex', alignItems: 'center', gap: 9, background: 'none', border: 'none', cursor: 'pointer', padding: '6px 4px' };
const cartBadge = { position: 'absolute', top: -7, right: -9, minWidth: 18, height: 18, padding: '0 4px', background: 'var(--madeci-red)', color: '#fff', borderRadius: 999, fontSize: 11, fontWeight: 700, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-data)' };
const navItem = { display: 'flex', alignItems: 'center', gap: 7, height: 34, padding: '0 14px', background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 14, color: 'var(--text-body)', letterSpacing: '.01em', transition: 'color .15s' };

Object.assign(window, { Header });
