// nav.jsx — header with mobile hamburger, search overlay, language toggle

function Nav({ route, setRoute, cartCount, lang, setLang, cartBadgeRef, onSearchOpen }) {
  const [mobileOpen, setMobileOpen] = React.useState(false);
  const t = (ar, en) => lang === 'ar' ? ar : en;
  const links = [
    { id: 'home',   label: t('الرئيسية',  'Home') },
    { id: 'shop',   label: t('العطور',    'Boutique') },
    { id: 'attars', label: t('العطّارون', 'Attars') },
    { id: 'story',  label: t('قصتنا',     'Story') },
  ];

  React.useEffect(() => {
    document.body.style.overflow = mobileOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [mobileOpen]);

  const go = (l) => { setMobileOpen(false); setRoute(l.route || l.id); };

  return (
    <>
      <nav className="nav">
        <div className="nav-row">
          {/* mobile: hamburger */}
          <button className="nav-burger" onClick={() => setMobileOpen(true)} aria-label="menu"><I.menu /></button>

          {/* desktop: left links */}
          <div className="nav-left">
            {links.map(l => (
              <a key={l.id} className={'nav-link' + (route === (l.route || l.id) || ((l.route || l.id) === 'shop' && route === 'pdp') ? ' active' : '')}
                 onClick={(e) => { e.preventDefault(); go(l); }}>
                {l.label}
              </a>
            ))}
          </div>

          <div className="brand" onClick={() => setRoute('home')}>
            <div className="brand-mark">{lang === 'ar' ? 'استبرق' : 'ISTABRAQ'}</div>
            <div className="brand-mark-en">{t('Indian Perfumery · since 2018', 'Indian Perfumery · since 2018')}</div>
          </div>

          <div className="nav-right">
            <div className="lang-toggle nav-lang-desktop">
              <button className={lang === 'ar' ? 'active' : ''} onClick={() => setLang('ar')}>ع</button>
              <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>EN</button>
            </div>
            <button className="icon-btn nav-search" onClick={onSearchOpen} aria-label="search"><I.search /></button>
            <button className="icon-btn nav-account" aria-label="account"><I.user /></button>
            <button className="icon-btn" onClick={() => setRoute('cart')} aria-label="cart" ref={cartBadgeRef} data-cart-icon>
              <I.bag />
              {cartCount > 0 && <span className="badge tabular" data-cart-badge>{cartCount}</span>}
            </button>
          </div>
        </div>
      </nav>

      {/* Mobile drawer */}
      {mobileOpen && (
        <div className="mobile-menu" onClick={() => setMobileOpen(false)}>
          <div className="mobile-menu-panel" onClick={e => e.stopPropagation()}>
            <div className="mobile-menu-head">
              <div>
                <div className="brand-mark" style={{ fontSize: 28 }}>{lang === 'ar' ? 'استبرق' : 'ISTABRAQ'}</div>
                <div className="brand-mark-en">{t('Indian Perfumery', 'Indian Perfumery')}</div>
              </div>
              <button className="icon-btn" onClick={() => setMobileOpen(false)}><I.close /></button>
            </div>
            <div className="mobile-menu-links">
              {links.map(l => (
                <a key={l.id} className={'mobile-menu-link' + (route === (l.route || l.id) ? ' on' : '')} onClick={() => go(l)}>
                  {l.label}
                  <I.arrow />
                </a>
              ))}
            </div>
            <div className="mobile-menu-foot">
              <div className="lang-toggle" style={{ alignSelf: 'flex-start' }}>
                <button className={lang === 'ar' ? 'active' : ''} onClick={() => setLang('ar')}>عربي</button>
                <button className={lang === 'en' ? 'active' : ''} onClick={() => setLang('en')}>English</button>
              </div>
              <button className="btn ghost full" onClick={() => { setMobileOpen(false); onSearchOpen(); }}>
                <I.search /> {t('بحث', 'Search')}
              </button>
              <div style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 16, lineHeight: 1.6 }}>
                {t('شارع جميرا، دبي · 04-555-7788', 'Jumeirah St, Dubai · 04-555-7788')}<br />
                hello@istabraq.store
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

function SearchOverlay({ open, onClose, onPick, lang }) {
  const [q, setQ] = React.useState('');
  const inputRef = React.useRef();
  React.useEffect(() => {
    if (open) setTimeout(() => inputRef.current?.focus(), 50);
    else setQ('');
  }, [open]);

  if (!open) return null;

  const results = q
    ? PRODUCTS.filter(p =>
        p.name_ar.includes(q) ||
        p.name_en.toLowerCase().includes(q.toLowerCase()) ||
        SCENT_FAMILIES.find(f => f.id === p.family)?.ar.includes(q) ||
        SCENT_FAMILIES.find(f => f.id === p.family)?.en.toLowerCase().includes(q.toLowerCase())
      ).slice(0, 8)
    : PRODUCTS.slice(0, 8);

  return (
    <>
      <div className="modal-back" onClick={onClose} style={{ background: 'rgba(0,0,0,0.4)' }} />
      <div className="search-overlay">
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <input ref={inputRef}
                 placeholder={lang === 'ar' ? 'ابحث عن عطر، عائلة عطرية…' : 'Search for a fragrance, family…'}
                 value={q} onChange={(e) => setQ(e.target.value)}
                 onKeyDown={(e) => e.key === 'Escape' && onClose()} />
          <button className="icon-btn" onClick={onClose} aria-label="close"><I.close /></button>
        </div>
        <div className="search-results">
          {results.map(p => {
            const fam = SCENT_FAMILIES.find(f => f.id === p.family);
            return (
              <div key={p.id} className="search-result" onClick={() => { onPick(p); onClose(); }}>
                <div className="mini">
                  <div className="mini-bottle" style={{ background: p.tone, color: p.tone }} />
                </div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontFamily: 'var(--f-ar-head)', fontSize: 14, whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }}>{lang === 'ar' ? p.name_ar : p.name_en}</div>
                  <div className="eyebrow" style={{ fontSize: 9, marginTop: 2 }}>{lang === 'ar' ? fam.ar : fam.en} · {p.price} AED</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
}

window.Nav = Nav;
window.SearchOverlay = SearchOverlay;
