// aerOS Guest v2 — Menu screen: hero + featured + sticky scroll-spy nav + live search + filters + sections.
const { useState: _mn2S, useRef: _mn2R, useMemo: _mn2M, useEffect: _mn2E } = React;

function G2Menu({ C, t, lang, tw, onSelect, onQuickAdd, onCart, onWaiter, cartCount, cartTotal, onLang, onCurrency, brand, brandSub, onBack, onSettings }) {
  const D = window.G2DATA;
  const animate = tw.animate;
  const [activeCat, setActiveCat] = _mn2S(D.CATS[0].id);
  const [q, setQ] = _mn2S('');
  const [showSearch, setShowSearch] = _mn2S(false);
  const [diet, setDiet] = _mn2S([]);
  const MAXP = 750, MAXC = 900;
  const [priceMax, setPriceMax] = _mn2S(MAXP);
  const [calMax, setCalMax] = _mn2S(MAXC);
  const scroller = _mn2R(null), navRef = _mn2R(null), pillBar = _mn2R(null);
  const secRefs = _mn2R({}), pillRefs = _mn2R({});
  const clickScroll = _mn2R(false);
  const staggerCls = animate ? 'g2-stagger' : '';

  const name = p => lang === 'en' ? p.en : p.name;
  const filterCount = diet.length + (priceMax < MAXP ? 1 : 0) + (calMax < MAXC ? 1 : 0);
  const searching = q.trim() || filterCount > 0;

  const matches = p => {
    if (diet.length && !diet.every(d => p.diet.includes(d))) return false;
    if (p.price > priceMax) return false;
    if (p.cal > calMax) return false;
    if (q.trim()) { const ql = q.toLowerCase(); return (p.name + ' ' + p.en + ' ' + p.desc + ' ' + p.en_desc).toLowerCase().includes(ql); }
    return true;
  };
  const flat = _mn2M(() => D.PRODUCTS.filter(matches), [q, diet, priceMax, calMax]);
  const featured = _mn2M(() => D.PRODUCTS.filter(p => p.badge === 'chef' || p.badge === 'signature' || p.badge === 'popular').slice(0, 6), []);
  const dietCounts = _mn2M(() => { const c = {}; ['veg', 'vegan', 'gf', 'spicy'].forEach(d => c[d] = D.PRODUCTS.filter(p => p.diet.includes(d)).length); return c; }, []);

  // scroll spy
  const onScroll = () => {
    if (clickScroll.current || searching || !scroller.current || !navRef.current) return;
    const navBottom = navRef.current.getBoundingClientRect().bottom;
    let cur = D.CATS[0].id;
    for (const c of D.CATS) { const el = secRefs.current[c.id]; if (el && el.getBoundingClientRect().top - navBottom < 16) cur = c.id; }
    setActiveCat(cur);
  };
  _mn2E(() => { // keep active pill visible
    const pill = pillRefs.current[activeCat], bar = pillBar.current;
    if (pill && bar) { const want = pill.offsetLeft - bar.offsetWidth / 2 + pill.offsetWidth / 2; bar.scrollTo({ left: Math.max(0, want), behavior: 'smooth' }); }
  }, [activeCat]);

  const goCat = (id) => {
    setActiveCat(id);
    const el = secRefs.current[id]; if (!el || !scroller.current || !navRef.current) return;
    const navH = navRef.current.offsetHeight;
    const delta = el.getBoundingClientRect().top - scroller.current.getBoundingClientRect().top - navH - 6;
    clickScroll.current = true;
    scroller.current.scrollTo({ top: scroller.current.scrollTop + delta, behavior: 'smooth' });
    setTimeout(() => { clickScroll.current = false; }, 520);
  };

  const layout = tw.layout;
  const gridStyle = layout === 'gallery' ? { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 } : layout === 'text' ? { display: 'block' } : { display: 'flex', flexDirection: 'column', gap: layout === 'magazine' ? 16 : 11 };

  const toggleDiet = d => setDiet(s => s.includes(d) ? s.filter(x => x !== d) : [...s, d]);

  const _ctx = window.G2CTX || {};
  const modeLabel = tw.mode === 'room' ? (t.roomLabel + (_ctx.room ? ' ' + _ctx.room : '')) : tw.mode === 'view' ? t.viewOnly : (t.tableLabel + (_ctx.table ? ' ' + _ctx.table : ''));

  // ── HERO ──
  const langSwitch = (onDark) => (
    <G2Seg value={lang} onChange={onLang} options={[['tr', 'TR'], ['en', 'EN']]} C={onDark ? { ...C, ink2: 'rgba(255,255,255,0.85)', accent: 'rgba(255,255,255,0.92)', accentInk: C.accentDark, dark: false } : C} />
  );
  const iconBtn = (icon, onClick, onDark, label) => (
    <button onClick={onClick} aria-label={label} style={{ width: 40, height: 40, borderRadius: 12, border: onDark ? 'none' : `1px solid ${C.line2}`, background: onDark ? 'rgba(0,0,0,0.3)' : (C.dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.03)'), color: onDark ? '#fff' : C.ink, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexShrink: 0, backdropFilter: onDark ? 'blur(8px)' : 'none' }}>{icon({ size: 20 })}</button>
  );
  const rightCluster = (onDark) => (
    <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
      {langSwitch(onDark)}
      {onSettings && iconBtn(Icon.settings, onSettings, onDark, t.settings)}
    </div>
  );

  let hero;
  if (tw.heroStyle === 'minimal') {
    hero = (
      <div style={{ padding: '50px 16px 14px', background: C.bg }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          {onBack ? iconBtn(Icon.chevLeft, onBack, false, t.back) : <span />}
          {rightCluster(false)}
        </div>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12 }}>
          <div>
            <div style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: C.accent }}>{modeLabel}</div>
            <h1 style={{ fontFamily: G2THEME.headFont(tw), fontWeight: 600, fontSize: 33, color: C.ink, lineHeight: 1.05, marginTop: 6 }}>{brand}</h1>
            <div style={{ fontSize: 12.5, color: C.muted, marginTop: 4 }}>{brandSub}</div>
          </div>
        </div>
      </div>
    );
  } else if (tw.heroStyle === 'gradient') {
    hero = (
      <div style={{ position: 'relative', overflow: 'hidden', background: `linear-gradient(155deg, ${C.accent}, ${C.accentDark} 125%)`, padding: '52px 20px 26px', color: '#fff' }}>
        <div style={{ position: 'absolute', inset: 0, opacity: 0.2, backgroundImage: 'radial-gradient(circle at 82% 12%, #fff 0, transparent 42%), radial-gradient(circle at 8% 92%, #fff 0, transparent 38%)' }} />
        <div style={{ position: 'relative', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
            {onBack && iconBtn(Icon.chevLeft, onBack, true, t.back)}
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, fontWeight: 700, letterSpacing: '0.08em', background: 'rgba(255,255,255,0.18)', padding: '6px 12px', borderRadius: 999, backdropFilter: 'blur(6px)' }}>{Icon.utensils({ size: 13 })}{modeLabel}</span>
          </div>
          {rightCluster(true)}
        </div>
        <h1 style={{ position: 'relative', fontFamily: G2THEME.headFont(tw), fontWeight: 600, fontSize: 38, lineHeight: 1.04, marginTop: 30 }}>{brand}</h1>
        <div style={{ position: 'relative', fontSize: 13.5, opacity: 0.9, marginTop: 5 }}>{brandSub}</div>
      </div>
    );
  } else { // photo
    hero = (
      <div style={{ position: 'relative', height: 300 }}>
        <G2Photo id="hero" color={C.accent} ratio={392 / 300} radius={0} C={C} t={t} photoMode={tw.photoMode === 'upload' ? 'upload' : 'placeholder'} icon={Icon.utensils} style={{ position: 'absolute', inset: 0, paddingTop: 0, height: '100%' }} />
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(8,6,4,0.45) 0%, rgba(8,6,4,0.05) 38%, rgba(8,6,4,0.82) 100%)' }} />
        <div style={{ position: 'absolute', top: 0, left: 0, right: 0, padding: '52px 18px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
            {onBack && iconBtn(Icon.chevLeft, onBack, true, t.back)}
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, fontWeight: 700, color: '#fff', background: 'rgba(0,0,0,0.32)', padding: '6px 12px', borderRadius: 999, backdropFilter: 'blur(8px)' }}>{Icon.utensils({ size: 13 })}{modeLabel}</span>
          </div>
          {rightCluster(true)}
        </div>
        <div style={{ position: 'absolute', bottom: 18, left: 18, right: 18, color: '#fff' }}>
          <div style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', opacity: 0.85 }}>{t.welcome}</div>
          <h1 style={{ fontFamily: G2THEME.headFont(tw), fontWeight: 600, fontSize: 38, lineHeight: 1.02, marginTop: 4, textShadow: '0 2px 20px rgba(0,0,0,0.4)' }}>{brand}</h1>
          <div style={{ fontSize: 13, opacity: 0.92, marginTop: 3 }}>{brandSub}</div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: C.bg, fontFamily: G2THEME.BODY_FONT }}>
      <div ref={scroller} onScroll={onScroll} className="g2-noscroll" style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden' }}>
        {hero}

        {/* featured carousel */}
        {tw.featured && !searching && (
          <div style={{ padding: '18px 0 4px' }}>
            <div style={{ padding: '0 18px', display: 'flex', alignItems: 'center', gap: 7, marginBottom: 11 }}>
              <span style={{ color: C.accent, display: 'flex' }}>{Icon.sparkles({ size: 17 })}</span>
              <span style={{ fontFamily: G2THEME.headFont(tw), fontWeight: 600, fontSize: 19, color: C.ink }}>{t.featured}</span>
            </div>
            <div className="g2-noscroll" style={{ display: 'flex', gap: 13, overflowX: 'auto', padding: '0 18px 8px' }}>
              {featured.map(p => (
                <button key={p.id} onClick={() => onSelect(p)} style={{ flexShrink: 0, width: 210, border: 'none', borderRadius: tw.corners === 'sharp' ? 4 : 18, overflow: 'hidden', cursor: 'pointer', textAlign: 'left', fontFamily: G2THEME.BODY_FONT, background: C.bg2, boxShadow: C.cardShadow, position: 'relative' }}>
                  <div style={{ position: 'relative' }}>
                    <G2Photo id={'f-' + p.id} color={p.color} ratio={1.7} radius={0} C={C} t={t} photoMode={tw.photoMode} />
                    <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, transparent 40%, rgba(8,6,4,0.78))' }} />
                    {tw.showBadge && p.badge && <div style={{ position: 'absolute', top: 10, left: 10 }}><G2Badge kind={p.badge} t={t} small /></div>}
                    <div style={{ position: 'absolute', bottom: 10, left: 12, right: 12, color: '#fff' }}>
                      <div style={{ fontFamily: G2THEME.headFont(tw), fontWeight: 600, fontSize: 17, lineHeight: 1.1 }}>{name(p)}</div>
                      {tw.showPrice && <div className="tnum" style={{ fontSize: 13.5, fontWeight: 700, marginTop: 2, opacity: 0.95 }}>{G2THEME.money(p.price, tw.currency)}</div>}
                    </div>
                  </div>
                </button>
              ))}
            </div>
          </div>
        )}

        {/* sticky bar: search + filters + category nav */}
        <div ref={navRef} style={{ position: 'sticky', top: 0, zIndex: 30, background: C.bgGlass, backdropFilter: 'blur(16px) saturate(160%)', borderBottom: `1px solid ${C.line}` }}>
          <div style={{ display: 'flex', gap: 9, padding: '12px 16px 10px', alignItems: 'center' }}>
            <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 9, background: C.dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.04)', border: `1px solid ${C.line}`, borderRadius: 13, padding: '0 13px', height: 44 }}>
              <span style={{ color: C.muted, display: 'flex' }}>{Icon.search({ size: 18 })}</span>
              <input value={q} onChange={e => setQ(e.target.value)} placeholder={t.search} style={{ flex: 1, border: 'none', background: 'transparent', outline: 'none', fontSize: 14.5, fontFamily: G2THEME.BODY_FONT, color: C.ink }} />
              {q && <button onClick={() => setQ('')} style={{ border: 'none', background: 'none', cursor: 'pointer', color: C.muted, display: 'flex' }}>{Icon.x({ size: 16 })}</button>}
            </div>
            <button onClick={() => setShowSearch(true)} style={{ position: 'relative', width: 44, height: 44, borderRadius: 13, border: `1px solid ${filterCount ? C.accent : C.line}`, background: filterCount ? C.accent : (C.dark ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.04)'), color: filterCount ? C.accentInk : C.ink, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexShrink: 0 }}>
              {Icon.filter({ size: 19 })}
              {filterCount > 0 && <span className="tnum" style={{ position: 'absolute', top: -5, right: -5, minWidth: 17, height: 17, borderRadius: 9, background: C.ink, color: C.bg, fontSize: 10, fontWeight: 800, display: 'flex', alignItems: 'center', justifyContent: 'center', border: `2px solid ${C.bg}` }}>{filterCount}</span>}
            </button>
          </div>
          {!searching && (
            tw.catNav === 'tabs' ? (
              <div ref={pillBar} className="g2-noscroll" style={{ display: 'flex', gap: 4, overflowX: 'auto', padding: '0 14px' }}>
                {D.CATS.map(c => { const on = activeCat === c.id; return (
                  <button key={c.id} ref={el => pillRefs.current[c.id] = el} onClick={() => goCat(c.id)} style={{ position: 'relative', flexShrink: 0, padding: '11px 12px 13px', border: 'none', background: 'none', cursor: 'pointer', fontFamily: G2THEME.BODY_FONT, fontSize: 14, fontWeight: on ? 700 : 600, color: on ? C.ink : C.muted, transition: 'color 160ms' }}>
                    {lang === 'en' ? c.en : c.name}
                    <span style={{ position: 'absolute', bottom: 0, left: 12, right: 12, height: 3, borderRadius: 3, background: on ? C.accent : 'transparent', transition: 'background 160ms' }} />
                  </button>
                ); })}
              </div>
            ) : (
              <div ref={pillBar} className="g2-noscroll" style={{ display: 'flex', gap: 8, overflowX: 'auto', padding: '2px 14px 12px' }}>
                {D.CATS.map(c => <span key={c.id} ref={el => pillRefs.current[c.id] = el}><G2Chip active={activeCat === c.id} onClick={() => goCat(c.id)} C={C}>{lang === 'en' ? c.en : c.name}</G2Chip></span>)}
              </div>
            )
          )}
        </div>

        {/* body */}
        <div style={{ padding: '16px 16px', paddingBottom: cartCount > 0 ? 150 : 96 }}>
          {searching ? (
            flat.length === 0 ? (
              <div style={{ textAlign: 'center', padding: '56px 20px', color: C.muted }}>
                <div style={{ display: 'inline-flex', width: 62, height: 62, borderRadius: 20, background: C.bg2, alignItems: 'center', justifyContent: 'center', marginBottom: 13, color: C.line2 }}>{Icon.search({ size: 28 })}</div>
                <div style={{ fontWeight: 700, color: C.ink, fontSize: 16 }}>{t.noResults}</div>
              </div>
            ) : (
              <>
                <div style={{ fontSize: 12.5, fontWeight: 700, color: C.muted, marginBottom: 12 }}>{flat.length} {t.items}</div>
                <div className={staggerCls} style={gridStyle}>
                  {flat.map((p, i) => <G2Card key={p.id} p={p} layout={layout} C={C} t={t} lang={lang} tw={tw} onSelect={onSelect} onQuickAdd={onQuickAdd} animate={animate} idx={i} />)}
                </div>
              </>
            )
          ) : (
            D.CATS.map(c => {
              const items = D.PRODUCTS.filter(p => p.cat === c.id);
              if (!items.length) return null;
              return (
                <section key={c.id} ref={el => secRefs.current[c.id] = el} style={{ marginBottom: 26, scrollMarginTop: 120 }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 13 }}>
                    <h2 style={{ fontFamily: G2THEME.headFont(tw), fontWeight: 600, fontSize: 22, color: C.ink }}>{lang === 'en' ? c.en : c.name}</h2>
                    <span className="tnum" style={{ fontSize: 12, fontWeight: 600, color: C.muted }}>{items.length} {t.items}</span>
                  </div>
                  <div className={staggerCls} style={gridStyle}>
                    {items.map((p, i) => <G2Card key={p.id} p={p} layout={layout} C={C} t={t} lang={lang} tw={tw} onSelect={onSelect} onQuickAdd={onQuickAdd} animate={animate} idx={i} />)}
                  </div>
                </section>
              );
            })
          )}
        </div>
      </div>

      {/* filter sheet */}
      <G2FilterSheet open={showSearch} onClose={() => setShowSearch(false)} C={C} t={t} tw={tw} diet={diet} toggleDiet={toggleDiet} counts={dietCounts} priceMax={priceMax} setPriceMax={setPriceMax} calMax={calMax} setCalMax={setCalMax} maxP={MAXP} maxC={MAXC} resultCount={flat.length} onClear={() => { setDiet([]); setPriceMax(MAXP); setCalMax(MAXC); }} animate={animate} />

      {/* floating actions */}
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '0 16px 18px', display: 'flex', flexDirection: 'column', gap: 10, pointerEvents: 'none' }}>
        {cartCount > 0 && (
          <button onClick={onCart} style={{ pointerEvents: 'auto', width: '100%', height: 56, borderRadius: 16, border: 'none', background: `linear-gradient(180deg, ${C.accent}, ${C.accentDark})`, color: C.accentInk, display: 'flex', alignItems: 'center', gap: 12, padding: '0 18px', cursor: 'pointer', fontFamily: G2THEME.BODY_FONT, boxShadow: `0 14px 34px -10px ${C.accent}`, animation: animate ? 'g2up .35s cubic-bezier(.22,1,.36,1)' : 'none' }}>
            <span className="tnum" style={{ minWidth: 28, height: 28, borderRadius: 9, background: 'rgba(255,255,255,0.25)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13.5, fontWeight: 800 }}>{cartCount}</span>
            <span style={{ flex: 1, textAlign: 'left', fontSize: 15.5, fontWeight: 700 }}>{t.cart}</span>
            <span className="tnum" style={{ fontSize: 16.5, fontWeight: 800 }}>{G2THEME.money(cartTotal, tw.currency)}</span>
            <span style={{ display: 'flex' }}>{Icon.chevRight({ size: 20 })}</span>
          </button>
        )}
      </div>
      {tw.mode !== 'view' && (
        <button onClick={onWaiter} title={t.callWaiter} style={{ position: 'absolute', right: 16, bottom: cartCount > 0 ? 86 : 90, width: 54, height: 54, borderRadius: '50%', border: 'none', background: C.bg2, color: C.accent, boxShadow: C.shadow, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', zIndex: 5, border: `1px solid ${C.line}` }}>{Icon.headset({ size: 23 })}</button>
      )}
    </div>
  );
}

window.G2Menu = G2Menu;
