// Avokado Bar — v3 Müşteri Menüsü (Menu.dc.html referansına piksel uyumlu)
// Erişim: /?v=3 — window.AvbMenuV3
(function(){
const { useState, useEffect, useRef, useMemo } = React;
const O = window.AvbOrd;
const U = window.AvbOrdUI;
const { INK, CREAM, GREEN, OLIVE, HAIR, HAIR2 } = U;
const EASE = 'cubic-bezier(0.2,0.8,0.2,1)';

const LAST_ORDER_KEY = 'avb3_last_order';
const ONBOARD_KEY = 'avb_onboard_v1';

function loadLastOrder(){
  try {
    const o = JSON.parse(localStorage.getItem(LAST_ORDER_KEY) || 'null');
    if (o && o.id && o.no && (Date.now() - (o.at || 0)) < 3 * 3600 * 1000) return o;
  } catch(_){}
  return null;
}
function saveLastOrder(o){
  try { localStorage.setItem(LAST_ORDER_KEY, JSON.stringify(o)); } catch(_){}
}

// Dil: önce kullanıcının önceki seçimi, yoksa tarayıcı dili, yoksa TR.
const LANG_KEY = 'avb3_lang';
function initialLang(){
  try {
    const saved = localStorage.getItem(LANG_KEY);
    if (saved === 'tr' || saved === 'en') return saved;
    const nav = (navigator.language || '').toLowerCase();
    if (nav && !nav.startsWith('tr')) return 'en';
  } catch(_){}
  return 'tr';
}

function TT(lang){
  const tr = lang === 'tr';
  return {
    searchPh: tr ? 'Menüde ara…' : 'Search the menu…',
    soldOut: tr ? 'Tükendi' : 'Sold out',
    viewCart: tr ? 'Sepeti gör' : 'View cart',
    addToCart: tr ? 'Siparişe ekle' : 'Add to order',
    cartTitle: tr ? 'Sepet' : 'Cart',
    total: tr ? 'Toplam' : 'Total',
    checkout: tr ? 'Siparişi tamamla' : 'Place order',
    remove: tr ? 'Kaldır' : 'Remove',
    added: tr ? 'Sepete eklendi' : 'Added to cart',
    orderFail: tr ? 'Sipariş gönderilemedi — tekrar deneyin' : 'Order failed — try again',
    emptyTitle: tr ? 'Sonuç bulunamadı' : 'No results',
    emptyDesc: tr ? 'Aramayı veya filtreleri değiştirmeyi deneyin.' : 'Try changing your search or filters.',
    footer: tr ? 'Fiyatlara KDV dahildir · the AVOKADO bar' : 'Prices include VAT · the AVOKADO bar',
    contains: tr ? 'İçerir: ' : 'Contains: ',
    optional: tr ? 'İsteğe bağlı' : 'Optional',
    pickOne: tr ? 'Birini seçin' : 'Pick one',
    noExtras: tr ? 'Ekstra istemiyorum · Siparişe ekle' : 'No extras · Add to order',
    withExtras: tr ? 'Ekstra eklemek istiyorum' : 'I want to add extras',
    obTitle: tr ? 'Siparişinizi kendiniz oluşturabilirsiniz' : 'You can build your own order',
    obDesc: tr ? 'Ürünleri seçin, siparişi tamamlayın — çıkan QR kodu garsonunuza gösterin, o onaylasın. İsterseniz her zamanki gibi garsona da sipariş verebilirsiniz.'
               : 'Pick your items and place the order — show the QR code to your waiter to confirm. Or simply order through your waiter as usual.',
    obSelf: tr ? 'Kendim sipariş oluşturacağım' : 'I will build my own order',
    obBrowse: tr ? 'Sadece menüye bakacağım' : 'Just browsing the menu',
    obLang: 'Dil · Language',
    obToast: tr ? 'Harika — ürünleri + ile ekleyin' : 'Great — add items with +',
    orderReady: tr ? 'Siparişiniz hazır' : 'Your order is ready',
    showWaiter: tr ? 'Bu kodu garsona gösterin — okutup siparişinizi onaylayacak.' : 'Show this code to your waiter to confirm the order.',
    itemsWord: tr ? 'ürün' : 'items',
    done: tr ? 'Tamam' : 'Done',
    sending: tr ? 'Gönderiliyor…' : 'Placing…',
    myOrder: tr ? 'Siparişim' : 'My order',
    stPending: tr ? 'Bekliyor — garsona QR kodu gösterin' : 'Waiting — show the QR to your waiter',
    stConfirmed: tr ? 'Onaylandı — hazırlanıyor' : 'Confirmed — being prepared',
    stPrinted: tr ? 'Hazırlanıyor' : 'Being prepared',
    stDelivered: tr ? 'Teslim edildi — afiyet olsun' : 'Delivered — enjoy',
    stCancelled: tr ? 'Sipariş iptal edildi' : 'Order cancelled',
  };
}

function MenuV3(){
  const { menu } = O.useMenuConfig();
  const [lang, setLangState] = useState(initialLang);
  const setLang = (v) => { setLangState(v); try { localStorage.setItem(LANG_KEY, v); } catch(_){} };
  const [searchOpen, setSearchOpen] = useState(false);
  const [search, setSearch] = useState('');
  const [dietFilters, setDietFilters] = useState({});
  const [activeCat, setActiveCat] = useState(null);
  const [detail, setDetail] = useState(null);        // { id, qty, sel }
  const [quickChoice, setQuickChoice] = useState(null); // item id
  const [cart, setCart] = useState([]);              // { key, id, qty, sel }
  const [cartOpen, setCartOpen] = useState(false);
  const [orderDone, setOrderDone] = useState(null);  // { no, id, qrUrl, totalFmt, count }
  const [placing, setPlacing] = useState(false);
  const [onboard, setOnboard] = useState(() => { try { return localStorage.getItem(ONBOARD_KEY) !== '1'; } catch(_){ return true; } });
  const [lastOrder, setLastOrder] = useState(loadLastOrder);
  const [trackOpen, setTrackOpen] = useState(false);
  const [toastEl, showToast] = U.useToast();
  const scrollerRef = useRef(null);
  const tabsRef = useRef(null);
  const spyLock = useRef(0);

  const T = TT(lang);
  const L = lang;
  const B = menu.badges || {};
  const ALG = menu.allergens || {};

  // Canlı aktif sipariş (pil + takip sheet'i)
  const liveOrder = O.useOrderDoc(lastOrder && lastOrder.id);
  const trackVisible = !!(lastOrder && liveOrder && liveOrder.status !== 'delivered' && liveOrder.status !== 'cancelled');
  useEffect(() => {
    // Teslim/iptalden 1 dk sonra pil kaybolur (localStorage temizle)
    if (lastOrder && liveOrder && (liveOrder.status === 'delivered' || liveOrder.status === 'cancelled')) {
      const t = setTimeout(() => { setLastOrder(null); try { localStorage.removeItem(LAST_ORDER_KEY); } catch(_){} }, 60000);
      return () => clearTimeout(t);
    }
  }, [lastOrder && lastOrder.id, liveOrder && liveOrder.status]);

  const dismissOnboard = (msg) => {
    try { localStorage.setItem(ONBOARD_KEY, '1'); } catch(_){}
    setOnboard(false);
    if (msg) showToast(msg);
  };

  /* ── Menü türetmeleri ── */
  const visibleItems = useMemo(() => {
    const q = search.trim().toLocaleLowerCase('tr');
    const active = Object.keys(dietFilters).filter(k => dietFilters[k]);
    return (menu.items || []).filter(it => {
      if (it.hidden) return false;
      if (active.length && !active.every(f => (it.badges || []).includes(f))) return false;
      if (q) {
        const loc = it[L] || it.tr || { n:'', d:'' };
        const hay = ((loc.n || '') + ' ' + (loc.d || '')).toLocaleLowerCase('tr');
        if (!hay.includes(q)) return false;
      }
      return true;
    });
  }, [menu, search, dietFilters, L]);

  const cats = useMemo(() => (menu.categories || []).filter(c => !c.hidden).slice().sort((a,b) => a.sort - b.sort), [menu]);
  const sections = useMemo(() => cats.map(c => {
    const items = visibleItems.filter(i => i.cat === c.id).sort((a,b) => a.sort - b.sort);
    if (!items.length) return null;
    return { id: c.id, label: c[L] || c.tr, count: items.length, items };
  }).filter(Boolean), [cats, visibleItems, L]);

  const currentCat = activeCat && sections.some(s => s.id === activeCat) ? activeCat : (sections[0] && sections[0].id);

  const centerTab = (id) => {
    const tabs = tabsRef.current;
    if (!tabs) return;
    const btn = tabs.querySelector('[data-tab-id="' + id + '"]');
    if (btn) tabs.scrollTo({ left: btn.offsetLeft - tabs.clientWidth / 2 + btn.clientWidth / 2, behavior:'smooth' });
  };
  const scrollToCat = (id) => {
    setActiveCat(id);
    spyLock.current = Date.now() + 600;
    const sc = scrollerRef.current;
    if (sc) {
      const el = sc.querySelector('[data-sec="' + id + '"]');
      if (el) sc.scrollTo({ top: el.offsetTop - sc.offsetTop - 4, behavior:'smooth' });
    }
    centerTab(id);
  };
  const onScroll = () => {
    if (spyLock.current && Date.now() < spyLock.current) return;
    const sc = scrollerRef.current;
    if (!sc) return;
    const secs = sc.querySelectorAll('[data-sec]');
    let cur = null;
    secs.forEach(el => { if (el.offsetTop - sc.offsetTop <= sc.scrollTop + 80) cur = el.getAttribute('data-sec'); });
    if (cur && cur !== currentCat) { setActiveCat(cur); centerTab(cur); }
  };

  /* ── Sepet hesapları ── */
  const lineCalc = (c) => {
    const it = (menu.items || []).find(i => i.id === c.id);
    if (!it) return null;
    let delta = 0; const names = [];
    Object.entries(c.sel || {}).forEach(([gid, v]) => {
      const g = (menu.extraGroups || {})[gid]; if (!g) return;
      const ids = g.type === 'single' ? (v ? [v] : []) : Object.keys(v || {}).filter(k => v[k]);
      ids.forEach(oid => {
        const o = (g.options || []).find(x => x.id === oid);
        if (o) { delta += Number(o.delta) || 0; names.push((o[L] || o.tr) + (o.delta ? ' +' + o.delta : '')); }
      });
    });
    return { it, unit: (Number(it.price) || 0) + delta, names };
  };
  const addToCart = (it, qty, sel) => {
    const key = it.id + '|' + JSON.stringify(sel || {});
    setCart(c => {
      const found = c.find(x => x.key === key);
      if (found) return c.map(x => x.key === key ? { ...x, qty: x.qty + qty } : x);
      return [...c, { key, id: it.id, qty, sel: sel || {} }];
    });
    setDetail(null);
    showToast(T.added);
  };
  const quickAdd = (it) => {
    if (it.extras && it.extras.length) setQuickChoice(it.id);
    else addToCart(it, 1, {});
  };
  let cartTotal = 0;
  const cartLines = cart.map(c => {
    const calc = lineCalc(c);
    if (!calc) return null;
    const total = calc.unit * c.qty;
    cartTotal += total;
    return { c, calc, total };
  }).filter(Boolean);
  const cartCount = cart.reduce((a, c) => a + c.qty, 0);

  const checkout = async () => {
    if (placing) return;
    setPlacing(true);
    const lines = cartLines.map(({ c, calc }) => ({
      itemId: calc.it.id,
      name: calc.it.tr.n, nameEn: (calc.it.en && calc.it.en.n) || calc.it.tr.n,
      qty: c.qty, extras: calc.names, sel: c.sel || {}, note: '',
      station: O.lineStation(menu, { itemId: calc.it.id }),
      unit: calc.unit, total: calc.unit * c.qty,
    }));
    try {
      const order = await O.createOrder(lines, cartTotal);
      const qrUrl = O.makeQrUrl(order.no, order.id);
      setCart([]); setCartOpen(false);
      setOrderDone({ no:'#' + order.no, id: order.id, qrUrl, totalFmt: O.fmt(order.total), count: lines.reduce((a,l) => a + l.qty, 0) });
      const last = { id: order.id, no: order.no, at: Date.now() };
      setLastOrder(last); saveLastOrder(last);
    } catch(e){
      console.warn('[MenuV3] checkout:', e && e.message);
      showToast(T.orderFail, true);
    }
    setPlacing(false);
  };

  /* ── Alt bileşen render'ları ── */
  const dietDefs = Object.keys(B).filter(k => k !== 'pop' && k !== 'new');

  const renderCard = (it) => {
    const tone = O.TONES[it.tone] || ['#EEE','#CCC'];
    const loc = it[L] || it.tr;
    const flags = (it.badges || []).filter(b => b === 'pop' || b === 'new');
    const diet = (it.badges || []).filter(b => b !== 'pop' && b !== 'new').slice(0,2);
    const flag = flags.length ? (B[flags[0]] || {})[L] : null;
    return (
      <div key={it.id} onClick={() => { if (!it.soldOut) setDetail({ id: it.id, qty:1, sel:{} }); }} className="avb3-press"
        style={{ background:'#FFFFFF', borderRadius:20, padding:12, display:'flex', gap:12, cursor: it.soldOut ? 'default' : 'pointer', boxShadow:'0 1px 0 rgba(0,0,0,0.04)', opacity: it.soldOut ? 0.62 : 1 }}>
        <div style={{ position:'relative', width:86, height:86, flexShrink:0 }}>
          {it.photo ? (
            <img src={it.photo} alt={loc.n} loading="lazy" style={{ width:86, height:86, objectFit:'cover', borderRadius:14, display:'block', filter: it.soldOut ? 'grayscale(1)' : 'none' }} />
          ) : (
            <div style={{ width:86, height:86, borderRadius:14, background:'linear-gradient(145deg, ' + tone[0] + ', ' + tone[1] + ')', display:'flex', alignItems:'center', justifyContent:'center', fontSize:26, fontWeight:900, color:'rgba(26,26,26,0.35)' }}>{(loc.n || '?').charAt(0)}</div>
          )}
          {flag && (
            <div style={{ position:'absolute', top:6, left:6, padding:'3px 8px', borderRadius:999, background: flags[0] === 'new' ? INK : GREEN, color: flags[0] === 'new' ? CREAM : INK, fontSize:10, fontWeight:700, letterSpacing:'0.04em' }}>{flag}</div>
          )}
        </div>
        <div style={{ flex:1, minWidth:0, display:'flex', flexDirection:'column', gap:4 }}>
          <div style={{ fontSize:16, fontWeight:600, color:INK, lineHeight:1.25 }}>{loc.n}</div>
          <div style={{ fontSize:13, color:'#808080', lineHeight:1.4, overflow:'hidden', display:'-webkit-box', WebkitLineClamp:2, WebkitBoxOrient:'vertical' }}>{loc.d}</div>
          <div style={{ display:'flex', alignItems:'center', gap:8, marginTop:'auto', paddingTop:4 }}>
            <div style={{ fontSize:16, fontWeight:700, color:INK, fontVariantNumeric:'tabular-nums' }}>{O.fmt(it.price)}</div>
            <div style={{ display:'flex', gap:4, flex:1, minWidth:0, overflow:'hidden' }}>
              {diet.map(b => (
                <span key={b} style={{ flexShrink:0, padding:'3px 8px', borderRadius:999, background:'rgba(208,228,18,0.22)', color:'#5C6410', fontSize:10.5, fontWeight:700 }}>{(B[b] || {})[L] || b}</span>
              ))}
            </div>
            {it.soldOut ? (
              <span style={{ padding:'5px 10px', borderRadius:999, background:'rgba(192,58,43,0.1)', color:'#C03A2B', fontSize:11, fontWeight:700, flexShrink:0 }}>{T.soldOut}</span>
            ) : (
              <button onClick={(e) => { e.stopPropagation(); quickAdd(it); }} aria-label="Ekle" className="avb3-press-hard avb3-hover-green"
                style={{ width:36, height:36, borderRadius:999, border:'none', background:GREEN, display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', flexShrink:0 }}>
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke={INK} strokeWidth="2.4" strokeLinecap="round"><path d="M12 5v14M5 12h14" /></svg>
              </button>
            )}
          </div>
        </div>
      </div>
    );
  };

  /* ── Detay sheet ── */
  let detailEl = null;
  if (detail) {
    const it = (menu.items || []).find(i => i.id === detail.id);
    if (it) {
      const tone = O.TONES[it.tone] || ['#EEE','#CCC'];
      const loc = it[L] || it.tr;
      const sel = detail.sel;
      let delta = 0;
      const groups = (it.extras || []).map(gid => (menu.extraGroups || {})[gid]).filter(Boolean);
      groups.forEach(g => {
        const v = sel[g.id];
        const ids = g.type === 'single' ? (v ? [v] : []) : Object.keys(v || {}).filter(k => v[k]);
        ids.forEach(oid => { const o = (g.options || []).find(x => x.id === oid); if (o) delta += Number(o.delta) || 0; });
      });
      const unit = (Number(it.price) || 0) + delta;
      const dietAll = (it.badges || []).filter(b => b !== 'pop' && b !== 'new');
      const allergenNames = (it.allergens || []).map(a => (ALG[a] || {})[L] || a);
      detailEl = (
        <U.Sheet onClose={() => setDetail(null)}>
          <div className="avb3-noscroll" style={{ overflowY:'auto', flex:1 }}>
            <div style={{ position:'relative' }}>
              {it.photo ? (
                <img src={it.photo} alt={loc.n} decoding="async" style={{ width:'100%', height:210, objectFit:'cover', display:'block' }} />
              ) : (
                <div style={{ width:'100%', height:130, background:'linear-gradient(145deg, ' + tone[0] + ', ' + tone[1] + ')', display:'flex', alignItems:'center', justifyContent:'center', fontSize:44, fontWeight:900, color:'rgba(26,26,26,0.3)' }}>{(loc.n || '?').charAt(0)}</div>
              )}
              <div style={{ position:'absolute', top:12, right:12 }}><U.CloseX light onClick={() => setDetail(null)} /></div>
            </div>
            <div style={{ padding:'18px 18px 8px' }}>
              <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:12 }}>
                <div style={{ fontSize:22, fontWeight:700, color:INK, letterSpacing:'-0.01em', lineHeight:1.2 }}>{loc.n}</div>
                <div style={{ fontSize:19, fontWeight:700, color:INK, fontVariantNumeric:'tabular-nums', flexShrink:0 }}>{O.fmt(it.price)}</div>
              </div>
              <div style={{ fontSize:14.5, color:'#3D3D3D', lineHeight:1.55, marginTop:6 }}>{loc.d}</div>
              {dietAll.length > 0 && (
                <div style={{ display:'flex', gap:5, flexWrap:'wrap', marginTop:10 }}>
                  {dietAll.map(b => (
                    <span key={b} style={{ padding:'4px 10px', borderRadius:999, background:'rgba(208,228,18,0.22)', color:'#5C6410', fontSize:11.5, fontWeight:700 }}>{(B[b] || {})[L] || b}</span>
                  ))}
                </div>
              )}
              {allergenNames.length > 0 && (
                <div style={{ marginTop:12, padding:'10px 12px', borderRadius:12, background:'rgba(26,26,26,0.04)', fontSize:12.5, color:'#808080', lineHeight:1.5 }}>{T.contains + allergenNames.join(' · ')}</div>
              )}
            </div>
            {groups.map(g => {
              const single = g.type === 'single';
              return (
                <div key={g.id} style={{ padding:'8px 18px 4px' }}>
                  <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom:8 }}>
                    <div style={{ fontSize:12, fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'#808080' }}>{g[L] || g.tr}</div>
                    <div style={{ fontSize:11.5, color:'#B3B3B3' }}>{single ? T.pickOne : T.optional}</div>
                  </div>
                  <div style={{ background:'#FFFFFF', borderRadius:14, overflow:'hidden' }}>
                    {(g.options || []).map((o, i) => {
                      const selected = single ? sel[g.id] === o.id : !!(sel[g.id] && sel[g.id][o.id]);
                      const toggle = () => {
                        const ns = { ...sel };
                        if (single) ns[g.id] = ns[g.id] === o.id ? null : o.id;
                        else ns[g.id] = { ...(ns[g.id] || {}), [o.id]: !selected };
                        setDetail({ ...detail, sel: ns });
                      };
                      return (
                        <div key={o.id} onClick={toggle} className="avb3-hover-faint"
                          style={{ display:'flex', alignItems:'center', gap:12, padding:'12px 14px', cursor:'pointer', borderTop: i === 0 ? 'none' : '1px solid rgba(26,26,26,0.06)' }}>
                          <span style={{ width:20, height:20, borderRadius: single ? 999 : 6, border:'2px solid ' + (selected ? '#A8B80F' : 'rgba(26,26,26,0.25)'), background: selected ? GREEN : 'transparent', display:'inline-flex', alignItems:'center', justifyContent:'center', flexShrink:0, transition:'background 180ms, border-color 180ms', boxSizing:'border-box' }}>
                            {selected && <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke={INK} strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12.5l5 5L20 6.5" /></svg>}
                          </span>
                          <span style={{ flex:1, fontSize:15, fontWeight:500, color:INK }}>{o[L] || o.tr}</span>
                          <span style={{ fontSize:13.5, fontWeight:600, color:'#808080', fontVariantNumeric:'tabular-nums' }}>{o.delta ? '+' + O.fmt(o.delta) : ''}</span>
                        </div>
                      );
                    })}
                  </div>
                </div>
              );
            })}
            <div style={{ height:16 }} />
          </div>
          <div style={{ display:'flex', gap:12, alignItems:'center', padding:'14px 18px 16px', borderTop:'1px solid ' + HAIR, background:CREAM }}>
            <div style={{ display:'flex', alignItems:'center', gap:2, background:'#FFFFFF', border:'1px solid ' + HAIR2, borderRadius:14, height:52, padding:'0 6px', flexShrink:0 }}>
              <button onClick={() => setDetail({ ...detail, qty: Math.max(1, detail.qty - 1) })} aria-label="Azalt" className="avb3-press-hard" style={{ width:38, height:44, border:'none', background:'none', fontSize:20, fontWeight:600, color:OLIVE, cursor:'pointer' }}>−</button>
              <span style={{ minWidth:24, textAlign:'center', fontSize:17, fontWeight:700, color:INK, fontVariantNumeric:'tabular-nums' }}>{detail.qty}</span>
              <button onClick={() => setDetail({ ...detail, qty: detail.qty + 1 })} aria-label="Artır" className="avb3-press-hard" style={{ width:38, height:44, border:'none', background:'none', fontSize:19, fontWeight:600, color:OLIVE, cursor:'pointer' }}>+</button>
            </div>
            <button onClick={() => addToCart(it, detail.qty, sel)} className="avb3-press avb3-hover-olive"
              style={{ flex:1, height:52, border:'none', borderRadius:14, background:OLIVE, color:GREEN, fontSize:15.5, fontWeight:600, display:'flex', alignItems:'center', justifyContent:'space-between', padding:'0 18px', cursor:'pointer' }}>
              <span>{T.addToCart}</span>
              <span style={{ fontWeight:700, fontVariantNumeric:'tabular-nums' }}>{O.fmt(unit * detail.qty)}</span>
            </button>
          </div>
        </U.Sheet>
      );
    }
  }

  /* ── Quick-choice ── */
  let quickEl = null;
  if (quickChoice) {
    const it = (menu.items || []).find(i => i.id === quickChoice);
    if (it) {
      const loc = it[L] || it.tr;
      quickEl = (
        <>
          <div onClick={() => setQuickChoice(null)} style={{ position:'absolute', inset:0, zIndex:12, background:'rgba(20,20,15,0.55)', animation:'avb3Fade 200ms' }} />
          <div style={{ position:'absolute', left:12, right:12, bottom:'12px', zIndex:13, background:CREAM, borderRadius:20, padding:'18px 16px 16px', animation:'avb3SheetUp 280ms ' + EASE }}>
            <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', gap:10, marginBottom:14, padding:'0 4px' }}>
              <div style={{ fontSize:16, fontWeight:700, color:INK }}>{loc.n}</div>
              <div style={{ fontSize:15, fontWeight:700, color:INK, fontVariantNumeric:'tabular-nums' }}>{O.fmt(it.price)}</div>
            </div>
            <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
              <button onClick={() => { setQuickChoice(null); addToCart(it, 1, {}); }} className="avb3-press avb3-hover-olive"
                style={{ height:50, border:'none', borderRadius:14, background:OLIVE, color:GREEN, fontSize:15, fontWeight:600, cursor:'pointer' }}>{T.noExtras}</button>
              <button onClick={() => { setQuickChoice(null); setDetail({ id: it.id, qty:1, sel:{} }); }} className="avb3-press avb3-hover-faint"
                style={{ height:50, border:'1px solid ' + HAIR2, borderRadius:14, background:'#FFFFFF', color:INK, fontSize:15, fontWeight:600, cursor:'pointer' }}>{T.withExtras}</button>
            </div>
          </div>
        </>
      );
    }
  }

  /* ── Sepet sheet ── */
  let cartEl = null;
  if (cartOpen && cartLines.length > 0) {
    cartEl = (
      <U.Sheet onClose={() => setCartOpen(false)} maxHeight="82%">
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'18px 18px 10px' }}>
          <div style={{ fontSize:20, fontWeight:700, color:INK }}>{T.cartTitle}</div>
          <U.CloseX onClick={() => setCartOpen(false)} />
        </div>
        <div className="avb3-noscroll" style={{ overflowY:'auto', flex:1, padding:'4px 18px' }}>
          <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
            {cartLines.map(({ c, calc, total }) => {
              const loc = calc.it[L] || calc.it.tr;
              const setQty = (q) => setCart(cur => q <= 0
                ? cur.filter(x => x.key !== c.key)
                : cur.map(x => x.key === c.key ? { ...x, qty: q } : x));
              return (
                <div key={c.key} style={{ background:'#FFFFFF', borderRadius:14, padding:'12px 14px', display:'flex', gap:10, alignItems:'flex-start' }}>
                  <div style={{ flex:1, minWidth:0 }}>
                    <div style={{ fontSize:15, fontWeight:600, color:INK }}>{loc.n}</div>
                    {calc.names.length > 0 && <div style={{ fontSize:12.5, color:'#808080', marginTop:3, lineHeight:1.4 }}>{calc.names.join(' · ')}</div>}
                    <div style={{ display:'flex', alignItems:'center', gap:10, marginTop:8 }}>
                      <div style={{ display:'flex', alignItems:'center', gap:2, background:'rgba(26,26,26,0.04)', borderRadius:10, padding:'0 4px' }}>
                        <button onClick={() => setQty(c.qty - 1)} style={{ width:28, height:30, border:'none', background:'none', fontSize:16, color:OLIVE, cursor:'pointer' }}>−</button>
                        <span style={{ minWidth:18, textAlign:'center', fontSize:14, fontWeight:700, color:INK, fontVariantNumeric:'tabular-nums' }}>{c.qty}</span>
                        <button onClick={() => setQty(c.qty + 1)} style={{ width:28, height:30, border:'none', background:'none', fontSize:15, color:OLIVE, cursor:'pointer' }}>+</button>
                      </div>
                      <button onClick={() => setQty(0)} style={{ border:'none', background:'none', fontSize:12.5, fontWeight:600, color:'#C03A2B', cursor:'pointer', padding:4 }}>{T.remove}</button>
                    </div>
                  </div>
                  <div style={{ fontSize:15, fontWeight:700, color:INK, fontVariantNumeric:'tabular-nums', flexShrink:0 }}>{O.fmt(total)}</div>
                </div>
              );
            })}
          </div>
          <div style={{ height:12 }} />
        </div>
        <div style={{ padding:'12px 18px 16px', borderTop:'1px solid ' + HAIR }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:12 }}>
            <span style={{ fontSize:14, color:'#808080', fontWeight:500 }}>{T.total}</span>
            <span style={{ fontSize:22, fontWeight:800, color:INK, fontVariantNumeric:'tabular-nums' }}>{O.fmt(cartTotal)}</span>
          </div>
          <button onClick={checkout} disabled={placing} className="avb3-press avb3-hover-olive"
            style={{ width:'100%', height:52, border:'none', borderRadius:14, background:OLIVE, color:GREEN, fontSize:16, fontWeight:600, cursor:'pointer', opacity: placing ? 0.7 : 1 }}>
            {placing ? T.sending : T.checkout}
          </button>
        </div>
      </U.Sheet>
    );
  }

  /* ── QR / sipariş tamam ekranı ── */
  const renderOrderPanel = (no, id, qrUrl, meta, statusLine, onClose) => (
    <>
      <div style={{ position:'absolute', inset:0, zIndex:14, background:'rgba(20,20,15,0.55)', animation:'avb3Fade 200ms' }} />
      <div style={{ position:'absolute', left:0, right:0, bottom:0, zIndex:15, background:CREAM, borderRadius:'24px 24px 0 0', display:'flex', flexDirection:'column', alignItems:'center', padding:'28px 24px 24px', animation:'avb3SheetUp 280ms ' + EASE, textAlign:'center' }}>
        <div style={{ width:52, height:52, borderRadius:999, background:GREEN, display:'flex', alignItems:'center', justifyContent:'center', marginBottom:12 }}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke={INK} strokeWidth="2.8" strokeLinecap="round" strokeLinejoin="round"><path d="M4 12.5l5 5L20 6.5" /></svg>
        </div>
        <div style={{ fontSize:20, fontWeight:700, color:INK }}>{T.orderReady}</div>
        <div style={{ fontSize:14, color:'#808080', marginTop:4, lineHeight:1.5 }}>{statusLine || T.showWaiter}</div>
        {qrUrl && (
          <div style={{ width:216, height:216, backgroundColor:'#FFFFFF', backgroundImage:'url("' + qrUrl + '")', backgroundSize:'contain', backgroundRepeat:'no-repeat', backgroundPosition:'center', borderRadius:16, margin:'16px 0 12px', boxShadow:'0 1px 0 rgba(0,0,0,0.04), 0 8px 24px rgba(40,40,30,0.06)' }} />
        )}
        <div style={{ fontSize:24, fontWeight:800, color:INK, fontVariantNumeric:'tabular-nums' }}>{no}</div>
        {meta && <div style={{ fontSize:13, color:'#808080', marginTop:2, fontVariantNumeric:'tabular-nums' }}>{meta}</div>}
        <button onClick={onClose} className="avb3-press avb3-hover-olive"
          style={{ marginTop:18, width:'100%', height:50, border:'none', borderRadius:14, background:OLIVE, color:GREEN, fontSize:15, fontWeight:600, cursor:'pointer' }}>{T.done}</button>
      </div>
    </>
  );

  let doneEl = null;
  if (orderDone) {
    doneEl = renderOrderPanel(orderDone.no, orderDone.id, orderDone.qrUrl, orderDone.count + ' ' + T.itemsWord + ' · ' + orderDone.totalFmt, null, () => setOrderDone(null));
  }

  /* ── Aktif sipariş takip sheet'i (✱ senaryo A10) ── */
  let trackEl = null;
  if (trackOpen && lastOrder && liveOrder) {
    const stLine = {
      pending: T.stPending, confirmed: T.stConfirmed, printed: T.stPrinted,
      delivered: T.stDelivered, cancelled: T.stCancelled,
    }[liveOrder.status] || T.stPending;
    const qrUrl = liveOrder.status === 'pending' ? O.makeQrUrl(lastOrder.no, lastOrder.id) : null;
    trackEl = renderOrderPanel('#' + lastOrder.no, lastOrder.id, qrUrl, O.fmt(liveOrder.total || 0), stLine, () => setTrackOpen(false));
  }

  /* ── Onboarding ── */
  let onboardEl = null;
  if (onboard) {
    onboardEl = (
      <>
        <div style={{ position:'absolute', inset:0, zIndex:16, background:'rgba(20,20,15,0.55)', animation:'avb3Fade 200ms' }} />
        <div style={{ position:'absolute', left:0, right:0, bottom:0, zIndex:17, background:CREAM, borderRadius:'24px 24px 0 0', padding:'28px 22px 24px', animation:'avb3SheetUp 280ms ' + EASE, textAlign:'center' }}>
          {(() => {
            const ob = O.onboardingOf(menu);
            const sq = ob.shape === 'square';
            const box = sq
              ? { width:200, height:200, borderRadius:20, margin:'0 auto 16px' }
              : { width:'100%', height:132, borderRadius:16, marginBottom:16 };
            if (ob.image) {
              return <img src={ob.image} alt="" style={{ ...box, objectFit:'cover', display:'block', background:'rgba(26,26,26,0.05)' }} />;
            }
            return <div style={{ ...box, backgroundColor:GREEN, backgroundImage:'url("/Brand/Logo/logo-yellow.png")', backgroundSize:'contain', backgroundRepeat:'no-repeat', backgroundPosition:'center' }} />;
          })()}
          <div style={{ fontSize:11, fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'#808080', marginBottom:8 }}>{T.obLang}</div>
          <div style={{ display:'flex', justifyContent:'center', gap:8, marginBottom:18 }}>
            {[['tr','Türkçe'], ['en','English']].map(([code, label]) => {
              const on = L === code;
              return (
                <button key={code} onClick={() => setLang(code)} className="avb3-press-mid"
                  style={{ height:40, padding:'0 20px', borderRadius:999, border:'1px solid ' + (on ? INK : HAIR2), background: on ? INK : '#FFFFFF', color: on ? GREEN : '#3D3D3D', fontSize:14.5, fontWeight:600, cursor:'pointer', transition:'background 180ms ' + EASE + ', color 180ms' }}>
                  {label}
                </button>
              );
            })}
          </div>
          <div style={{ fontSize:21, fontWeight:700, color:INK, letterSpacing:'-0.01em' }}>{T.obTitle}</div>
          <div style={{ fontSize:14.5, color:'#3D3D3D', lineHeight:1.55, marginTop:8, textWrap:'pretty' }}>{T.obDesc}</div>
          <div style={{ display:'flex', flexDirection:'column', gap:8, marginTop:20 }}>
            <button onClick={() => dismissOnboard(T.obToast)} className="avb3-press avb3-hover-olive"
              style={{ height:52, border:'none', borderRadius:14, background:OLIVE, color:GREEN, fontSize:15, fontWeight:700, cursor:'pointer' }}>{T.obSelf}</button>
            <button onClick={() => dismissOnboard(null)} className="avb3-press avb3-hover-faint"
              style={{ height:52, border:'1px solid ' + HAIR2, borderRadius:14, background:'#FFFFFF', color:INK, fontSize:15, fontWeight:600, cursor:'pointer' }}>{T.obBrowse}</button>
          </div>
        </div>
      </>
    );
  }

  const cartBarVisible = cartCount > 0 && !cartOpen && !detail && !orderDone && !trackOpen;
  const trackPillVisible = trackVisible && !cartBarVisible && !cartOpen && !detail && !orderDone && !trackOpen && !onboard;

  return (
    <div className="avb3-stage">
      <div className="avb3-column">

        {/* Üst bar */}
        <div style={{ position:'relative', zIndex:5, background:'rgba(245,240,232,0.88)', backdropFilter:'blur(12px)', WebkitBackdropFilter:'blur(12px)', borderBottom:'1px solid ' + HAIR }}>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:12, padding:'14px 16px 10px' }}>
            <U.Wordmark big />
            <div style={{ display:'flex', alignItems:'center', gap:8 }}>
              <button onClick={() => { setSearchOpen(o => !o); setSearch(''); }} aria-label="Ara" className="avb3-press-mid"
                style={{ width:36, height:36, borderRadius:12, border:'1px solid ' + HAIR2, background: searchOpen ? GREEN : '#FFFFFF', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer' }}>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={INK} strokeWidth="2" strokeLinecap="round"><circle cx="11" cy="11" r="7" /><path d="M20 20l-3.5-3.5" /></svg>
              </button>
              <button onClick={() => setLang(L === 'tr' ? 'en' : 'tr')} className="avb3-press-mid"
                style={{ height:36, padding:'0 12px', borderRadius:12, border:'1px solid ' + HAIR2, background:'#FFFFFF', fontSize:13, fontWeight:700, color:INK, cursor:'pointer' }}>{L === 'tr' ? 'EN' : 'TR'}</button>
            </div>
          </div>
          {searchOpen && (
            <>
              <div style={{ padding:'0 16px 8px' }}>
                <input value={search} onChange={e => setSearch(e.target.value)} placeholder={T.searchPh} autoFocus
                  style={{ width:'100%', boxSizing:'border-box', height:42, padding:'0 14px', borderRadius:12, border:'1px solid ' + HAIR2, background:'#FFFFFF', fontSize:15, color:INK, outline:'none' }} />
              </div>
              <div className="avb3-noscroll" style={{ display:'flex', gap:6, overflowX:'auto', padding:'0 16px 10px', alignItems:'center' }}>
                {dietDefs.map(f => {
                  const on = !!dietFilters[f];
                  return (
                    <button key={f} onClick={() => setDietFilters(d => ({ ...d, [f]: !on }))} className="avb3-press-mid"
                      style={{ flexShrink:0, display:'flex', alignItems:'center', gap:5, height:28, padding:'0 11px', borderRadius:999, border:'1px solid ' + (on ? 'rgba(168,184,15,0.6)' : HAIR2), background: on ? 'rgba(208,228,18,0.35)' : 'transparent', color: on ? '#3D4408' : '#808080', fontSize:12, fontWeight:600, cursor:'pointer' }}>
                      <span style={{ width:6, height:6, borderRadius:99, background: on ? '#A8B80F' : '#B3B3B3' }} />{(B[f] || {})[L] || f}
                    </button>
                  );
                })}
              </div>
            </>
          )}
          <div ref={tabsRef} className="avb3-noscroll" style={{ display:'flex', gap:8, overflowX:'auto', padding:'2px 16px 10px', scrollBehavior:'smooth' }}>
            {sections.map(s => {
              const on = s.id === currentCat;
              return (
                <button key={s.id} data-tab-id={s.id} onClick={() => scrollToCat(s.id)} className="avb3-press-mid"
                  style={{ flexShrink:0, height:36, padding:'0 16px', borderRadius:999, border:'1px solid ' + (on ? INK : HAIR2), background: on ? INK : '#FFFFFF', color: on ? GREEN : '#3D3D3D', fontSize:14, fontWeight:600, cursor:'pointer', transition:'background 180ms ' + EASE + ', color 180ms' }}>
                  {s.label}
                </button>
              );
            })}
          </div>
        </div>

        {/* Liste */}
        <div ref={scrollerRef} onScroll={onScroll} className="avb3-noscroll" style={{ flex:1, overflowY:'auto', padding:'16px 16px 120px', position:'relative' }}>
          {sections.length === 0 && (
            <div style={{ textAlign:'center', padding:'64px 24px', color:'#808080' }}>
              <div style={{ fontSize:17, fontWeight:600, color:'#3D3D3D', marginBottom:6 }}>{T.emptyTitle}</div>
              <div style={{ fontSize:14 }}>{T.emptyDesc}</div>
            </div>
          )}
          {sections.map(sec => (
            <div key={sec.id} data-sec={sec.id}>
              <div style={{ display:'flex', alignItems:'baseline', gap:8, margin:'12px 2px 12px' }}>
                <div style={{ fontSize:12, fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'#808080' }}>{sec.label}</div>
                <div style={{ flex:1, height:1, background:HAIR, alignSelf:'center' }} />
                <div style={{ fontSize:12, fontWeight:500, color:'#B3B3B3', fontVariantNumeric:'tabular-nums' }}>{sec.count}</div>
              </div>
              <div style={{ display:'flex', flexDirection:'column', gap:10, marginBottom:24 }}>
                {sec.items.map(renderCard)}
              </div>
            </div>
          ))}
          <div style={{ textAlign:'center', padding:'8px 0 24px', color:'#B3B3B3', fontSize:12 }}>{T.footer}</div>
        </div>

        {/* Aktif sipariş pili (✱) */}
        {trackPillVisible && (
          <div style={{ position:'absolute', left:16, right:16, bottom:'16px', zIndex:6, display:'flex', justifyContent:'center' }}>
            <button onClick={() => setTrackOpen(true)} className="avb3-press"
              style={{ height:44, padding:'0 18px', border:'none', borderRadius:999, background:INK, color:CREAM, display:'flex', alignItems:'center', gap:10, cursor:'pointer', boxShadow:'0 12px 36px rgba(40,40,30,0.18)', animation:'avb3SheetUp 280ms ' + EASE }}>
              <span style={{ width:8, height:8, borderRadius:99, background:GREEN }} />
              <span style={{ fontSize:14, fontWeight:600 }}>{T.myOrder} · <span style={{ fontVariantNumeric:'tabular-nums', fontWeight:800 }}>#{lastOrder.no}</span></span>
              <span style={{ fontSize:12, fontWeight:600, color:GREEN }}>{O.statusMeta(liveOrder.status).label}</span>
            </button>
          </div>
        )}

        {/* Sepet çubuğu */}
        {cartBarVisible && (
          <div style={{ position:'absolute', left:16, right:16, bottom:'16px', zIndex:6 }}>
            <button onClick={() => setCartOpen(true)} className="avb3-press avb3-hover-olive"
              style={{ width:'100%', height:56, border:'none', borderRadius:16, background:OLIVE, color:GREEN, display:'flex', alignItems:'center', justifyContent:'space-between', padding:'0 18px', cursor:'pointer', boxShadow:'0 12px 36px rgba(40,40,30,0.18)', animation:'avb3SheetUp 280ms ' + EASE }}>
              <span style={{ display:'flex', alignItems:'center', gap:10, fontSize:15, fontWeight:600 }}>
                <span style={{ minWidth:24, height:24, borderRadius:999, background:GREEN, color:INK, fontSize:13, fontWeight:800, display:'inline-flex', alignItems:'center', justifyContent:'center', padding:'0 4px', fontVariantNumeric:'tabular-nums' }}>{cartCount}</span>
                {T.viewCart}
              </span>
              <span style={{ fontSize:16, fontWeight:700, fontVariantNumeric:'tabular-nums' }}>{O.fmt(cartTotal)}</span>
            </button>
          </div>
        )}

        {detailEl}
        {cartEl}
        {quickEl}
        {doneEl}
        {trackEl}
        {onboardEl}
        {toastEl}
      </div>
    </div>
  );
}

window.AvbMenuV3 = MenuV3;
})();
