// Menu + Item detail sheet — namespaced under window.AvbX
(function(){
const { useState, useEffect, useRef, useMemo } = React;
const {
  INK, GREEN, OLIVE, CREAM,
  CATEGORIES, ITEMS, BADGES, ALLERGENS, getItemMods, findModOption,
  T, Icon, Tap, Badge, DishImage, IconButton, Stepper, Wordmark, useScrollY, fmt,
} = window.AvbX;

// ── Sticky category tab strip with underline ──
function CategoryTabs({ cats, active, onChange, lang }) {
  const ref = useRef(null);
  const items = useRef({});
  const [line, setLine] = useState({ x:0, w:0 });
  useEffect(() => {
    const el = items.current[active];
    const cont = ref.current;
    if (el && cont) {
      const pr = cont.getBoundingClientRect();
      const r = el.getBoundingClientRect();
      setLine({ x: r.left - pr.left + cont.scrollLeft, w: r.width });
      // center the active tab horizontally WITHOUT scrollIntoView (which scrolls ancestors)
      const target = el.offsetLeft - (cont.clientWidth / 2) + (el.offsetWidth / 2);
      cont.scrollTo({ left: Math.max(0, target), behavior: 'smooth' });
    }
  }, [active]);
  return (
    <div ref={ref} className="avb-noscroll" style={{ position:'relative', display:'flex', padding:'2px 14px 8px', overflowX:'auto', whiteSpace:'nowrap' }}>
      {cats.map(c => (
        <button key={c.id} ref={el=>items.current[c.id]=el} onClick={()=>onChange(c.id)} style={{
          border:'none', background:'transparent', padding:'10px 4px', margin:'0 9px',
          fontFamily:'var(--font-body)', fontWeight:active===c.id?700:500, fontSize:15,
          color:active===c.id?INK:'#999', cursor:'pointer', whiteSpace:'nowrap', letterSpacing:'-0.01em',
          transition:'color 180ms var(--ease)',
        }}>{c[lang]}</button>
      ))}
      <div style={{ position:'absolute', bottom:3, left:0, height:2.5, borderRadius:2, width:line.w, transform:`translateX(${line.x}px)`, background:INK, transition:'transform 320ms var(--ease), width 320ms var(--ease)' }} />
    </div>
  );
}

// ── Menu row (compact, photo right) ──
function MenuRow({ item, qty, lang, onAdd, onOpen }) {
  const L = item[lang];
  const addBtn = (
    <Tap onClick={(e)=>{ e.stopPropagation(); onAdd(item); }} style={{
      width:34, height:34, borderRadius:999, border:'none',
      background:qty>0?GREEN:INK, color:qty>0?INK:GREEN, display:'inline-flex', alignItems:'center', justifyContent:'center',
      cursor:'pointer', boxShadow:'0 4px 12px rgba(0,0,0,0.18)', fontWeight:800, fontSize:14, flex:'none',
    }}>{qty>0?<span style={{ fontVariantNumeric:'tabular-nums' }}>{qty}</span>:<Icon.plus size={16} color={GREEN} />}</Tap>
  );
  return (
    <div onClick={onOpen} style={{ display:'flex', gap:14, padding:'14px 0', borderBottom:'1px solid rgba(26,26,26,0.07)', cursor:'pointer', alignItems: item.photo?'stretch':'center' }}>
      <div style={{ flex:1, minWidth:0, display:'flex', flexDirection:'column', gap:6 }}>
        <div style={{ display:'flex', alignItems:'center', gap:6, flexWrap:'wrap' }}>
          {item.badges.filter(b=>b==='pop'||b==='new').slice(0,1).map(b=><Badge key={b} kind={b} lang={lang} size="sm" />)}
          <span style={{ fontWeight:700, fontSize:16, color:INK, letterSpacing:'-0.01em', lineHeight:1.25 }}>{L.n}</span>
        </div>
        <div style={{ fontSize:13, color:'#999', lineHeight:1.45, display:'-webkit-box', WebkitLineClamp:2, WebkitBoxOrient:'vertical', overflow:'hidden' }}>{L.d}</div>
        <div style={{ display:'flex', alignItems:'center', gap:10, marginTop:'auto' }}>
          <span style={{ fontWeight:800, fontSize:16, color:INK, fontVariantNumeric:'tabular-nums' }}>{fmt(item.price)}</span>
          {item.badges.filter(b=>['veg','gf','hp'].includes(b)).slice(0,1).map(b=><Badge key={b} kind={b} lang={lang} size="sm" />)}
        </div>
      </div>
      {item.photo ? (
        <div style={{ position:'relative', width:104, flex:'none' }}>
          <DishImage photo={item.photo} tone={item.tone} radius={16} style={{ width:104, height:104 }} />
          <div style={{ position:'absolute', bottom:6, right:6 }}>{addBtn}</div>
        </div>
      ) : addBtn}
    </div>
  );
}

function MenuScreen({ lang, cart, onAddQuick, onOpen, orderType, setOrderType, onGoCart, greeting, onOpenCombos }) {
  const scrollRef = useRef(null);
  const y = useScrollY(scrollRef);
  const [cat, setCat] = useState(CATEGORIES[0].id);
  const [q, setQ] = useState('');
  const sectionRefs = useRef({});
  const scrolled = y > 8;

  const grouped = useMemo(() => {
    const g = {}; CATEGORIES.forEach(c=>g[c.id]=[]);
    ITEMS.forEach(it=>{ if(g[it.cat]) g[it.cat].push(it); });
    return g;
  }, []);

  const filtered = useMemo(() => {
    if (!q.trim()) return null;
    const s = q.toLocaleLowerCase('tr');
    return ITEMS.filter(it => (it.tr.n+' '+it.en.n+' '+it.tr.d+' '+it.en.d).toLocaleLowerCase('tr').includes(s));
  }, [q]);

  const onCatChange = (id) => {
    setCat(id);
    const el = sectionRefs.current[id], scr = scrollRef.current;
    if (el && scr) scr.scrollTo({ top: el.offsetTop - 104, behavior:'smooth' });
  };
  useEffect(() => {
    const scr = scrollRef.current; if(!scr) return;
    const on = () => {
      const top = scr.scrollTop + 120; let a = CATEGORIES[0].id;
      CATEGORIES.forEach(c=>{ const el=sectionRefs.current[c.id]; if(el && el.offsetTop<=top) a=c.id; });
      if (a!==cat) setCat(a);
    };
    scr.addEventListener('scroll', on, { passive:true });
    return ()=>scr.removeEventListener('scroll', on);
  }, [cat]);

  const cartCount = cart.reduce((a,c)=>a+c.qty,0);
  const cartTotal = cart.reduce((a,c)=>a+c.unitPrice*c.qty,0);
  const qtyOf = (id) => cart.filter(c=>c.itemId===id).reduce((a,c)=>a+c.qty,0);

  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column', position:'relative' }}>
      {/* translucent top spacer over dynamic island */}
      <div style={{ position:'absolute', top:0, left:0, right:0, height:54, zIndex:18,
        background:scrolled?'rgba(245,240,232,0.85)':'transparent', backdropFilter:scrolled?'blur(14px) saturate(160%)':'none', WebkitBackdropFilter:scrolled?'blur(14px) saturate(160%)':'none',
        borderBottom:scrolled?'1px solid rgba(26,26,26,0.06)':'1px solid transparent', transition:'background 220ms', pointerEvents:'none' }} />

      <div ref={scrollRef} style={{ flex:1, overflowY:'auto', overflowX:'hidden' }}>
        <div style={{ padding:'60px 18px 12px' }}>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:14 }}>
            <Wordmark />
            <IconButton onClick={()=>onOpen('__profile')}><Icon.user size={18} /></IconButton>
          </div>
          <div style={{ fontWeight:800, fontSize:28, letterSpacing:'-0.025em', color:INK, lineHeight:1.05 }}>{T[lang].tagline}</div>
          <div style={{ color:'#999', fontSize:14, marginTop:5 }}>{T[lang].sub}</div>

          <div style={{ marginTop:14 }}>
            <OrderTypeSegment value={orderType} onChange={setOrderType} lang={lang} />
          </div>
          <div style={{ marginTop:12, display:'flex', alignItems:'center', gap:10, background:'#fff', borderRadius:12, padding:'12px 14px', boxShadow:'inset 0 0 0 1px rgba(26,26,26,0.06)' }}>
            <Icon.search size={18} color="#999" />
            <input value={q} onChange={e=>setQ(e.target.value)} placeholder={T[lang].search} style={{ flex:1, border:'none', outline:'none', background:'transparent', fontFamily:'var(--font-body)', fontSize:14, color:INK }} />
            {q && <Tap onClick={()=>setQ('')} style={{ border:'none', background:'transparent', cursor:'pointer', padding:0, lineHeight:0 }}><Icon.close size={16} color="#999" /></Tap>}
          </div>
          {onOpenCombos && !q && (
            <Tap onClick={onOpenCombos} style={{ width:'100%', marginTop:12, display:'flex', alignItems:'center', gap:12, background:INK, color:CREAM, borderRadius:14, padding:'13px 14px', border:'none', cursor:'pointer', textAlign:'left', position:'relative', overflow:'hidden' }}>
              <div style={{ position:'absolute', right:-20, top:-20, width:90, height:90, borderRadius:999, background:'radial-gradient(circle, rgba(207,216,41,0.22) 0%, rgba(207,216,41,0) 70%)' }} />
              <span style={{ width:38, height:38, borderRadius:11, background:GREEN, display:'inline-flex', alignItems:'center', justifyContent:'center', flex:'none' }}><Icon.sparkle size={19} color={INK} /></span>
              <span style={{ flex:1 }}>
                <span style={{ display:'block', fontWeight:800, fontSize:15, color:GREEN }}>{T[lang].buildMenu}</span>
                <span style={{ display:'block', fontSize:12, color:'rgba(245,240,232,0.72)', marginTop:1 }}>{T[lang].moodDesc}</span>
              </span>
              <Icon.chevron size={16} color={CREAM} />
            </Tap>
          )}
        </div>

        {!filtered && (
          <div style={{ position:'sticky', top:54, zIndex:19, background:scrolled?'rgba(245,240,232,0.92)':CREAM, backdropFilter:scrolled?'blur(14px) saturate(160%)':'none', WebkitBackdropFilter:scrolled?'blur(14px) saturate(160%)':'none', borderBottom:scrolled?'1px solid rgba(26,26,26,0.07)':'1px solid transparent', transition:'background 220ms', paddingTop:4 }}>
            <CategoryTabs cats={CATEGORIES} active={cat} onChange={onCatChange} lang={lang} />
          </div>
        )}

        {filtered ? (
          <div style={{ padding:'8px 18px 120px' }}>
            {filtered.length===0 && <div style={{ padding:'60px 0', textAlign:'center', color:'#999', fontSize:15 }}>{T[lang].noResults}</div>}
            {filtered.map(it=><MenuRow key={it.id} item={it} qty={qtyOf(it.id)} lang={lang} onAdd={onAddQuick} onOpen={()=>onOpen(it)} />)}
          </div>
        ) : (
          <div style={{ padding:'8px 18px 120px' }}>
            {CATEGORIES.map(c => {
              const list = grouped[c.id]||[]; if(!list.length) return null;
              return (
                <section key={c.id} ref={el=>sectionRefs.current[c.id]=el} style={{ paddingTop:14, scrollMarginTop:104 }}>
                  <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom:8 }}>
                    <div style={{ fontWeight:800, fontSize:20, color:INK, letterSpacing:'-0.015em' }}>{c[lang]}</div>
                    <div style={{ fontSize:12, color:'#999', fontVariantNumeric:'tabular-nums' }}>{list.length}</div>
                  </div>
                  <div style={{ display:'flex', flexDirection:'column' }}>
                    {list.map(it=><MenuRow key={it.id} item={it} qty={qtyOf(it.id)} lang={lang} onAdd={onAddQuick} onOpen={()=>onOpen(it)} />)}
                  </div>
                </section>
              );
            })}
          </div>
        )}
      </div>

      {cartCount>0 && (
        <div style={{ position:'absolute', left:16, right:16, bottom:16, zIndex:30 }}>
          <Tap haptic="medium" onClick={onGoCart} style={{ display:'flex', alignItems:'center', gap:12, background:INK, color:GREEN, padding:'12px 14px 12px 12px', borderRadius:999, border:'none', cursor:'pointer', boxShadow:'0 12px 30px rgba(0,0,0,0.28)', width:'100%' }}>
            <span style={{ width:34, height:34, borderRadius:999, background:GREEN, color:INK, fontWeight:800, fontSize:14, display:'inline-flex', alignItems:'center', justifyContent:'center', fontVariantNumeric:'tabular-nums' }}>{cartCount}</span>
            <span style={{ fontWeight:700, fontSize:15, color:CREAM }}>{T[lang].viewCart}</span>
            <div style={{ flex:1 }} />
            <span style={{ fontWeight:800, fontSize:16, color:GREEN, fontVariantNumeric:'tabular-nums' }}>{fmt(cartTotal)}</span>
          </Tap>
        </div>
      )}
    </div>
  );
}

// ── Order-type segment ──
function OrderTypeSegment({ value, onChange, lang, light }) {
  const opts = [
    { id:'dine_in', label:T[lang].orderTypeDinein, I:Icon.qr },
    { id:'takeaway', label:T[lang].orderTypeTakeaway, I:Icon.bag },
    { id:'delivery', label:T[lang].orderTypeDelivery, I:Icon.pin },
  ];
  return (
    <div style={{ display:'inline-flex', background:'#fff', borderRadius:12, padding:3, boxShadow:'inset 0 0 0 1px rgba(26,26,26,0.08)' }}>
      {opts.map(o=>{ const on=value===o.id; return (
        <Tap key={o.id} onClick={()=>onChange(o.id)} style={{ border:'none', padding:'8px 14px', borderRadius:9, background:on?INK:'transparent', color:on?CREAM:INK, fontWeight:600, fontSize:13, fontFamily:'var(--font-body)', cursor:'pointer', display:'inline-flex', alignItems:'center', gap:6 }}>
          <o.I size={14} color={on?CREAM:INK} />{o.label}
        </Tap>
      ); })}
    </div>
  );
}

// ── Item detail bottom sheet (note + milk modifiers) ──
function ItemSheet({ item, lang, onClose, onAdd, favOn, onFavToggle }) {
  const [mounted, setMounted] = useState(false);
  const [qty, setQty] = useState(1);
  const [note, setNote] = useState('');
  const mods = getItemMods(item);
  const [sel, setSel] = useState(() => {
    const s = {};
    mods.forEach(g => { s[g.id] = g.type==='single' ? (g.required ? g.options[0].id : (g.id==='mg_milk' ? g.options[0].id : null)) : []; });
    return s;
  });
  useEffect(()=>{ const r=requestAnimationFrame(()=>setMounted(true)); return ()=>cancelAnimationFrame(r); },[]);
  if (!item) return null;
  const L = item[lang];
  const close = () => { setMounted(false); setTimeout(onClose, 280); };
  // sum option deltas across all groups
  let modDelta = 0;
  mods.forEach(g => {
    if (g.type==='single') { const o=g.options.find(x=>x.id===sel[g.id]); if(o) modDelta+=o.delta; }
    else { (sel[g.id]||[]).forEach(id=>{ const o=g.options.find(x=>x.id===id); if(o) modDelta+=o.delta; }); }
  });
  const unit = item.price + modDelta;
  const toggleSingle = (gid, oid) => setSel(s=>({ ...s, [gid]: oid }));
  const toggleMulti = (gid, oid) => setSel(s=>{ const cur=s[gid]||[]; return { ...s, [gid]: cur.includes(oid)?cur.filter(x=>x!==oid):[...cur,oid] }; });

  return (
    <div style={{ position:'absolute', inset:0, zIndex:100, display:'flex', flexDirection:'column', justifyContent:'flex-end' }}>
      <div onClick={close} style={{ position:'absolute', inset:0, background:'rgba(20,20,15,0.55)', opacity:mounted?1:0, transition:'opacity 280ms var(--ease)' }} />
      <div style={{ position:'relative', zIndex:2, background:CREAM, borderRadius:'24px 24px 0 0', maxHeight:'90%', display:'flex', flexDirection:'column', transform:mounted?'translateY(0)':'translateY(100%)', transition:'transform 340ms var(--ease)', boxShadow:'0 -12px 40px rgba(0,0,0,0.22)' }}>
        <div style={{ overflowY:'auto', flex:1 }}>
          {item.photo ? (
            <div style={{ position:'relative' }}>
              <DishImage photo={item.photo} tone={item.tone} radius={0} style={{ width:'100%', aspectRatio:'1 / 1', borderRadius:'24px 24px 0 0' }} />
              <div style={{ position:'absolute', top:14, left:14, display:'flex', gap:5, flexWrap:'wrap' }}>{item.badges.map(b=><Badge key={b} kind={b} lang={lang} />)}</div>
              <IconButton onClick={close} size={38} style={{ position:'absolute', top:12, right:12, background:'rgba(255,255,255,0.92)' }}><Icon.close size={17} /></IconButton>
              <IconButton onClick={onFavToggle} size={38} style={{ position:'absolute', bottom:12, right:12, background:'rgba(255,255,255,0.92)' }}><Icon.heart size={17} filled={favOn} color={favOn?'#C03A2B':INK} /></IconButton>
            </div>
          ) : (
            <div style={{ position:'relative', padding:'12px 14px 0', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
              <div style={{ position:'absolute', top:8, left:'50%', transform:'translateX(-50%)', width:40, height:5, borderRadius:999, background:'rgba(26,26,26,0.15)' }} />
              <IconButton onClick={onFavToggle} size={38}><Icon.heart size={17} filled={favOn} color={favOn?'#C03A2B':INK} /></IconButton>
              <IconButton onClick={close} size={38}><Icon.close size={17} /></IconButton>
            </div>
          )}
          <div style={{ padding: item.photo?'18px 18px 6px':'10px 18px 6px' }}>
            {!item.photo && item.badges.length>0 && <div style={{ display:'flex', gap:5, flexWrap:'wrap', marginBottom:12 }}>{item.badges.map(b=><Badge key={b} kind={b} lang={lang} />)}</div>}
            <div style={{ fontWeight:800, fontSize:24, color:INK, letterSpacing:'-0.02em', lineHeight:1.15 }}>{L.n}</div>
            <div style={{ fontSize:15, color:'#555', lineHeight:1.55, marginTop:8 }}>{L.d}</div>
          </div>
          {/* allergens */}
          {item.allergens.length>0 && (
            <div style={{ padding:'14px 18px 4px' }}>
              <div style={{ fontSize:11, color:'#999', textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:700, marginBottom:8 }}>{T[lang].allergens}</div>
              <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
                {item.allergens.map(a=><span key={a} style={{ padding:'6px 11px', borderRadius:8, background:'#F9E1DC', color:'#8A3224', fontSize:12, fontWeight:600 }}>{ALLERGENS[a]?ALLERGENS[a][lang]:a}</span>)}
              </div>
            </div>
          )}
          {/* modifier / extra groups */}
          {mods.map(g => (
            <div key={g.id} style={{ padding:'16px 18px 4px' }}>
              <div style={{ display:'flex', alignItems:'baseline', gap:8, marginBottom:10 }}>
                <span style={{ fontSize:11, color:'#999', textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:700 }}>{g[lang]}</span>
                <span style={{ fontSize:11, color:'#B3B3B3', fontWeight:600 }}>{g.type==='multiple'?(lang==='tr'?'İstediğin kadar':'Add any'):(lang==='tr'?'Bir seçim':'Pick one')}</span>
              </div>
              <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                {g.options.map(o=>{
                  const on = g.type==='single' ? sel[g.id]===o.id : (sel[g.id]||[]).includes(o.id);
                  const onClick = () => g.type==='single' ? toggleSingle(g.id,o.id) : toggleMulti(g.id,o.id);
                  return (
                    <Tap key={o.id} onClick={onClick} style={{ display:'flex', alignItems:'center', gap:12, padding:'12px 14px', borderRadius:12, background:'#fff', border:'none', boxShadow:on?`inset 0 0 0 2px ${OLIVE}`:'inset 0 0 0 1px rgba(26,26,26,0.08)', cursor:'pointer' }}>
                      {g.type==='single'
                        ? <span style={{ width:20, height:20, borderRadius:999, border:on?`6px solid ${OLIVE}`:'2px solid rgba(26,26,26,0.25)', flex:'none', transition:'border 160ms' }} />
                        : <span style={{ width:20, height:20, borderRadius:6, background:on?OLIVE:'#fff', boxShadow:on?'none':'inset 0 0 0 2px rgba(26,26,26,0.25)', flex:'none', display:'inline-flex', alignItems:'center', justifyContent:'center', transition:'background 160ms' }}>{on&&<Icon.check size={13} color={GREEN} />}</span>}
                      <span style={{ flex:1, textAlign:'left', fontWeight:600, fontSize:15, color:INK }}>{o[lang]}</span>
                      {o.delta>0 && <span style={{ fontSize:13, color:'#999', fontWeight:700, fontVariantNumeric:'tabular-nums' }}>+{fmt(o.delta)}</span>}
                    </Tap>
                  );
                })}
              </div>
            </div>
          ))}
          {/* note */}
          <div style={{ padding:'16px 18px 8px' }}>
            <div style={{ fontSize:11, color:'#999', textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:700, marginBottom:8, display:'flex', alignItems:'center', gap:6 }}><Icon.note size={13} color="#999" />{T[lang].addNote}</div>
            <input value={note} onChange={e=>setNote(e.target.value)} placeholder={T[lang].notePh} style={{ width:'100%', border:'none', outline:'none', background:'#fff', boxShadow:'inset 0 0 0 1px rgba(26,26,26,0.08)', borderRadius:12, padding:'12px 14px', fontFamily:'var(--font-body)', fontSize:14, color:INK }} />
          </div>
        </div>
        <div style={{ padding:'14px 18px calc(18px + env(safe-area-inset-bottom,0px))', borderTop:'1px solid rgba(26,26,26,0.06)', background:CREAM, display:'flex', alignItems:'center', gap:12 }}>
          <Stepper value={qty} onInc={()=>setQty(q=>q+1)} onDec={()=>setQty(q=>Math.max(1,q-1))} />
          <Tap haptic="medium" onClick={()=>{ onAdd(item, qty, sel, note); close(); }} style={{ flex:1, height:52, borderRadius:14, border:'none', background:OLIVE, color:GREEN, cursor:'pointer', display:'inline-flex', alignItems:'center', justifyContent:'space-between', padding:'0 20px', fontWeight:700, fontSize:15 }}>
            <span>{T[lang].addCart}</span>
            <span style={{ fontWeight:800, fontSize:16, fontVariantNumeric:'tabular-nums' }}>{fmt(unit*qty)}</span>
          </Tap>
        </div>
      </div>
    </div>
  );
}

Object.assign(window.AvbX = window.AvbX || {}, { CategoryTabs, MenuRow, MenuScreen, OrderTypeSegment, ItemSheet });
})();
