// Avokado Bar — v3 Garson Paneli (Garson Paneli.dc.html referansına piksel uyumlu)
// Erişim: /garson — window.AvbWaiterV3
// Auth: WhatsApp OTP (telefon) + users/{uid}.role (garson/admin/kasiyer)
(function(){
const { useState, useEffect, useRef } = 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)';

/* ── Garson: sipariş oluşturma ve var olan siparişi düzenleme ──
   order verilmezse yeni sipariş: doğrudan "confirmed" açılır (garson zaten
   onaylamış sayılır, anında yazdırma kuyruğuna düşer).
   order verilirse düzenleme: içerik/masa/not değiştirilir, yazdırılmış sipariş
   yeniden kuyruğa girer. */
function cartKey(id, sel, note){ return id + '|' + JSON.stringify(sel || {}) + '|' + (note || ''); }

// Var olan siparişin satırlarını sepete çevirir. Ürün menüde bulunamazsa
// (silinmiş/eski sipariş) satır "dondurulmuş" olarak korunur — adı ve fiyatı
// siparişte yazdığı gibi kalır, adet ve not yine değiştirilebilir.
function seedCart(menu, order){
  return ((order && order.lines) || []).map((l, i) => {
    const it = l.itemId ? (menu.items || []).find(x => x.id === l.itemId) : null;
    const qty = Number(l.qty) || 1;
    if (it) return { key: cartKey(it.id, l.sel || {}, l.note || ''), id: it.id, qty, sel: l.sel || {}, note: l.note || '', frozen: null };
    return {
      key: 'frozen' + i, id: l.itemId || null, qty, sel: l.sel || {}, note: l.note || '',
      frozen: {
        name: l.name || 'Ürün', nameEn: l.nameEn || l.name || 'Ürün',
        unit: Number(l.unit) || (qty ? Math.round((Number(l.total) || 0) / qty) : 0),
        extras: l.extras || [], station: O.lineStation(menu, l),
      },
    };
  });
}

function OrderComposer({ menu, staffName, order, onClose, onDone }){
  const editing = !!order;
  const [search, setSearch] = useState('');
  const [detail, setDetail] = useState(null);   // { id, qty, sel, note, replaceKey }
  const [cart, setCart] = useState(() => seedCart(menu, order)); // { key, id, qty, sel, note, frozen }
  const [review, setReview] = useState(editing);
  const [tableId, setTableId] = useState((order && order.tableId) || null);
  const [orderNote, setOrderNote] = useState((order && order.note) || '');
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState(null);

  // Garson, müşteriye kapalı ürünleri de görür — yalnız "Kapalı" olanlar düşer.
  const cats = (menu.categories || []).filter(c => !c.staffHidden).slice().sort((a,b) => a.sort - b.sort);
  const q = search.trim().toLocaleLowerCase('tr');
  const sections = cats.map(c => {
    const items = (menu.items || [])
      .filter(it => !it.staffHidden && it.cat === c.id)
      .filter(it => !q || (it.tr.n + ' ' + (it.tr.d || '')).toLocaleLowerCase('tr').includes(q))
      .sort((a,b) => a.sort - b.sort);
    return items.length ? { id:c.id, label:c.tr, items, custHidden: !!c.hidden } : null;
  }).filter(Boolean);

  const lineCalc = (c) => {
    if (c.frozen) return {
      itemId: c.id || null, name: c.frozen.name, nameEn: c.frozen.nameEn,
      unit: c.frozen.unit, names: c.frozen.extras || [], station: c.frozen.station, frozen: true,
    };
    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.tr + (o.delta ? ' +' + o.delta : '')); }
      });
    });
    return {
      itemId: it.id, name: it.tr.n, nameEn: (it.en && it.en.n) || it.tr.n,
      unit: (Number(it.price) || 0) + delta, names, station: O.lineStation(menu, { itemId: it.id }), frozen: false,
    };
  };
  let total = 0;
  const lines = cart.map(c => {
    const calc = lineCalc(c);
    if (!calc) return null;
    const t = calc.unit * c.qty;
    total += t;
    return { c, calc, total: t };
  }).filter(Boolean);
  const count = cart.reduce((a,c) => a + c.qty, 0);

  // Ürün sepete girer; replaceKey verilirse var olan satırın yerini alır.
  const commitDetail = (it, qty, sel, note, replaceKey) => {
    const k = cartKey(it.id, sel || {}, note || '');
    setCart(cur => {
      const idx = replaceKey ? cur.findIndex(x => x.key === replaceKey) : -1;
      const base = replaceKey ? cur.filter(x => x.key !== replaceKey) : cur;
      const f = base.find(x => x.key === k);
      if (f) return base.map(x => x.key === k ? { ...x, qty: x.qty + qty } : x);
      const entry = { key: k, id: it.id, qty, sel: sel || {}, note: note || '', frozen: null };
      if (idx >= 0) { const next = base.slice(); next.splice(Math.min(idx, next.length), 0, entry); return next; }
      return [...base, entry];
    });
    setDetail(null);
  };

  const submit = async () => {
    if (busy || !lines.length) return;
    setBusy(true); setErr(null);
    try {
      const payload = lines.map(({ c, calc, total: t }) => ({
        itemId: calc.itemId || null,
        name: calc.name, nameEn: calc.nameEn,
        qty: c.qty, extras: calc.names, sel: c.sel || {}, note: c.note || '',
        station: calc.station, unit: calc.unit, total: t,
      }));
      if (editing) {
        const upd = await O.reviseOrder(order, payload, total, {
          tableId, note: orderNote.trim(), staffName: staffName || null,
        });
        onDone(upd, true);
      } else {
        const created = await O.createOrder(payload, total, {
          status: 'confirmed', tableId, note: orderNote.trim(),
          createdBy: 'waiter', staffName: staffName || null,
        });
        onDone(created, false);
      }
    } catch(e){
      setErr((editing ? 'Değişiklik kaydedilemedi: ' : 'Sipariş oluşturulamadı: ') + (e && e.message || 'bağlantı hatası'));
      setBusy(false);
    }
  };

  const tableLabel = O.tableLabel(menu, tableId) || 'Masa seçilmedi';
  const wasPrinted = editing && (order.status === 'printed' || order.status === 'confirmed');

  /* Ürün detay sheet'i — ekstra + adet + not */
  let detailEl = null;
  if (detail) {
    const it = (menu.items || []).find(i => i.id === detail.id);
    if (it) {
      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;
      detailEl = (
        <U.Sheet onClose={() => setDetail(null)} z={22}>
          <div style={{ display:'flex', alignItems:'flex-start', justifyContent:'space-between', gap:12, padding:'18px 18px 4px' }}>
            <div>
              <div style={{ fontSize:19, fontWeight:700, color:INK, lineHeight:1.25 }}>{it.tr.n}</div>
              <div style={{ fontSize:13, color:'#808080', marginTop:3 }}>{it.tr.d}</div>
            </div>
            <U.CloseX onClick={() => setDetail(null)} />
          </div>
          <div className="avb3-noscroll" style={{ overflowY:'auto', flex:1, padding:'8px 18px 0' }}>
            {groups.map(g => {
              const single = g.type === 'single';
              return (
                <div key={g.id} style={{ marginBottom:12 }}>
                  <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.tr}</div>
                    <div style={{ fontSize:11.5, color:'#B3B3B3' }}>{single ? 'Birini seçin' : 'İsteğe bağlı'}</div>
                  </div>
                  <div style={{ background:'#FFFFFF', borderRadius:14, overflow:'hidden' }}>
                    {(g.options || []).map((o, i) => {
                      const on = 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]: !on };
                        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 ' + (on ? '#A8B80F' : 'rgba(26,26,26,0.25)'), background: on ? GREEN : 'transparent', display:'inline-flex', alignItems:'center', justifyContent:'center', flexShrink:0, boxSizing:'border-box' }}>
                            {on && <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.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={{ fontSize:12, fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'#808080', marginBottom:6 }}>Mutfağa not</div>
            <textarea value={detail.note} onChange={e => setDetail({ ...detail, note: e.target.value })} rows={2}
              placeholder="Örn. soğansız, az pişmiş, ayrı serviste"
              style={{ width:'100%', padding:'10px 12px', borderRadius:12, border:'1px solid ' + HAIR2, fontSize:14, color:INK, outline:'none', boxSizing:'border-box', resize:'vertical', lineHeight:1.5, background:'#FFFFFF' }} />
            <div style={{ height:14 }} />
          </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) })} 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 })} 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={() => commitDetail(it, detail.qty, sel, detail.note, detail.replaceKey)} 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>{detail.replaceKey ? 'Satırı güncelle' : 'Siparişe ekle'}</span>
              <span style={{ fontWeight:700, fontVariantNumeric:'tabular-nums' }}>{O.fmt(unit * detail.qty)}</span>
            </button>
          </div>
        </U.Sheet>
      );
    }
  }

  /* Özet + masa + sipariş notu */
  let reviewEl = null;
  if (review) {
    reviewEl = (
      <U.Sheet onClose={() => setReview(false)} z={22} maxHeight="92%">
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'18px 18px 10px' }}>
          <div style={{ fontSize:20, fontWeight:700, color:INK }}>
            {editing ? 'Siparişi düzenle' : 'Siparişi tamamla'}
            {editing && <span style={{ color:'#B3B3B3', fontWeight:600, fontVariantNumeric:'tabular-nums' }}> · #{order.no}</span>}
          </div>
          <U.CloseX onClick={() => setReview(false)} />
        </div>
        <div className="avb3-noscroll" style={{ overflowY:'auto', flex:1, padding:'0 18px' }}>
          <div style={{ fontSize:12, fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'#808080', margin:'4px 2px 8px' }}>Masa</div>
          {(menu.areas || []).map(a => {
            const areaTables = (menu.tables || []).filter(t => t.area === a.id);
            if (!areaTables.length) return null;
            return (
              <div key={a.id} style={{ marginBottom:10 }}>
                <div style={{ fontSize:12, fontWeight:600, color:'#B3B3B3', margin:'0 2px 6px' }}>{a.tr}</div>
                <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
                  {areaTables.map(t => {
                    const on = tableId === t.id;
                    return (
                      <button key={t.id} onClick={() => setTableId(on ? null : t.id)} className="avb3-press-mid"
                        style={{ height:34, padding:'0 13px', borderRadius:999, border:'1px solid ' + (on ? INK : HAIR2), background: on ? INK : '#FFFFFF', color: on ? GREEN : '#3D3D3D', fontSize:13, fontWeight:600, cursor:'pointer' }}>
                        Masa {t.label}
                      </button>
                    );
                  })}
                </div>
              </div>
            );
          })}

          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', margin:'14px 2px 8px' }}>
            <div style={{ fontSize:12, fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'#808080' }}>Ürünler</div>
            <button onClick={() => setReview(false)} className="avb3-press-mid"
              style={{ height:30, padding:'0 12px', borderRadius:999, border:'1px dashed rgba(26,26,26,0.22)', background:'none', color:OLIVE, fontSize:12.5, fontWeight:700, cursor:'pointer' }}>
              + Ürün ekle
            </button>
          </div>
          {lines.length === 0 && (
            <div style={{ background:'#FFFFFF', borderRadius:14, padding:'20px 16px', textAlign:'center', color:'#808080', fontSize:13.5, lineHeight:1.5 }}>
              Sipariş boş. {editing ? 'Siparişi tamamen kaldırmak için detaydan “Siparişi iptal et” kullanın.' : 'Ürün ekleyerek başlayın.'}
            </div>
          )}
          <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
            {lines.map(({ c, calc, total: t }) => {
              const setQty = (nq) => setCart(cur => nq <= 0 ? cur.filter(x => x.key !== c.key) : cur.map(x => x.key === c.key ? { ...x, qty: nq } : x));
              const setNote = (v) => setCart(cur => cur.map(x => x.key === c.key ? { ...x, note: v } : x));
              const sMeta = O.stationMeta(calc.station);
              return (
                <div key={c.key} style={{ background:'#FFFFFF', borderRadius:14, padding:'12px 14px' }}>
                  <div style={{ display:'flex', gap:10, alignItems:'flex-start' }}>
                    <div style={{ flex:1, minWidth:0 }}>
                      <div style={{ display:'flex', alignItems:'center', gap:7, flexWrap:'wrap' }}>
                        <span style={{ fontSize:15, fontWeight:600, color:INK }}>{calc.name}</span>
                        <span style={{ padding:'2px 8px', borderRadius:999, background:sMeta.bg, color:sMeta.fg, fontSize:10.5, fontWeight:700, letterSpacing:'0.04em' }}>{sMeta.caps}</span>
                      </div>
                      {calc.names.length > 0 && <div style={{ fontSize:12.5, color:'#808080', marginTop:3, lineHeight:1.4 }}>{calc.names.join(' · ')}</div>}
                    </div>
                    <div style={{ fontSize:15, fontWeight:700, color:INK, fontVariantNumeric:'tabular-nums', flexShrink:0 }}>{O.fmt(t)}</div>
                  </div>
                  <input value={c.note} onChange={e => setNote(e.target.value)} placeholder="Bu ürüne not (örn. soğansız)"
                    style={{ width:'100%', height:36, marginTop:8, padding:'0 11px', borderRadius:10, border:'1px solid ' + HAIR2, background:CREAM, fontSize:13, color: c.note ? '#B36F14' : INK, fontWeight: c.note ? 600 : 400, outline:'none', boxSizing:'border-box' }} />
                  <div style={{ display:'flex', alignItems:'center', gap:8, marginTop:8, flexWrap:'wrap' }}>
                    <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>
                    {!calc.frozen && (menu.items || []).some(i => i.id === c.id && (i.extras || []).length > 0) && (
                      <button onClick={() => { setDetail({ id: c.id, qty: c.qty, sel: O.deepClone(c.sel || {}), note: c.note || '', replaceKey: c.key }); setReview(false); }}
                        style={{ border:'none', background:'none', fontSize:12.5, fontWeight:600, color:OLIVE, cursor:'pointer', padding:4 }}>Ekstraları değiştir</button>
                    )}
                    <button onClick={() => setQty(0)} style={{ border:'none', background:'none', fontSize:12.5, fontWeight:600, color:'#C03A2B', cursor:'pointer', padding:4, marginLeft:'auto' }}>Kaldır</button>
                  </div>
                </div>
              );
            })}
          </div>

          <div style={{ fontSize:12, fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'#808080', margin:'16px 2px 6px' }}>Sipariş notu</div>
          <textarea value={orderNote} onChange={e => setOrderNote(e.target.value)} rows={2}
            placeholder="Tüm siparişi ilgilendiren not (örn. hepsi aynı anda çıksın)"
            style={{ width:'100%', padding:'10px 12px', borderRadius:12, border:'1px solid ' + HAIR2, fontSize:14, color:INK, outline:'none', boxSizing:'border-box', resize:'vertical', lineHeight:1.5, background:'#FFFFFF' }} />
          {editing && wasPrinted && (
            <div style={{ marginTop:12, padding:'10px 12px', borderRadius:12, background:'rgba(46,90,138,0.1)', color:'#2E5A8A', fontSize:12.5, fontWeight:600, lineHeight:1.5 }}>
              Bu sipariş mutfağa/bara gitmişti. Kaydedince güncel fiş yazdırma kuyruğuna yeniden düşer — eski fişi iptal ettirin.
            </div>
          )}
          {err && <div style={{ marginTop:10, padding:'10px 12px', borderRadius:10, background:'rgba(192,58,43,0.1)', color:'#C03A2B', fontSize:13, fontWeight:600 }}>{err}</div>}
          <div style={{ height:14 }} />
        </div>
        <div style={{ padding:'12px 18px 16px', borderTop:'1px solid ' + HAIR }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:10 }}>
            <span style={{ fontSize:13.5, color: tableId ? OLIVE : '#B3B3B3', fontWeight:600 }}>{tableLabel}</span>
            <span style={{ fontSize:22, fontWeight:800, color:INK, fontVariantNumeric:'tabular-nums' }}>{O.fmt(total)}</span>
          </div>
          <button onClick={submit} disabled={busy || !lines.length} className="avb3-press avb3-hover-olive"
            style={{ width:'100%', height:52, border:'none', borderRadius:14, background:OLIVE, color:GREEN, fontSize:16, fontWeight:700, cursor:'pointer', opacity: (busy || !lines.length) ? 0.7 : 1 }}>
            {busy
              ? (editing ? 'Kaydediliyor…' : 'Oluşturuluyor…')
              : (editing ? 'Değişiklikleri kaydet' : 'Siparişi oluştur · Yazdırmaya gönder')}
          </button>
        </div>
      </U.Sheet>
    );
  }

  return (
    <div style={{ position:'absolute', inset:0, zIndex:18, background:CREAM, display:'flex', flexDirection:'column', animation:'avb3Fade 200ms' }}>
      <div style={{ background:'rgba(245,240,232,0.95)', backdropFilter:'blur(12px)', borderBottom:'1px solid ' + HAIR }}>
        <div style={{ display:'flex', alignItems:'center', gap:10, padding:'14px 16px 10px' }}>
          <U.CloseX onClick={onClose} />
          <div style={{ flex:1 }}>
            <div style={{ fontSize:17, fontWeight:700, color:INK }}>
              {editing ? 'Ürün ekle' : 'Sipariş oluştur'}
              {editing && <span style={{ color:'#B3B3B3', fontWeight:600, fontVariantNumeric:'tabular-nums' }}> · #{order.no}</span>}
            </div>
            <div style={{ fontSize:12.5, color: tableId ? OLIVE : '#B3B3B3', fontWeight:600, marginTop:1 }}>{tableLabel}</div>
          </div>
        </div>
        <div style={{ padding:'0 16px 12px' }}>
          <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Ürün ara…"
            style={{ width:'100%', height:42, padding:'0 14px', borderRadius:12, border:'1px solid ' + HAIR2, background:'#FFFFFF', fontSize:15, color:INK, outline:'none', boxSizing:'border-box' }} />
        </div>
      </div>

      <div className="avb3-noscroll" style={{ flex:1, overflowY:'auto', padding:'12px 16px 110px' }}>
        {sections.length === 0 && (
          <div style={{ textAlign:'center', padding:'48px 24px', color:'#808080', fontSize:14 }}>Ürün bulunamadı.</div>
        )}
        {sections.map(sec => (
          <div key={sec.id}>
            <div style={{ display:'flex', alignItems:'baseline', gap:8, margin:'10px 2px 8px' }}>
              <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>
            <div style={{ display:'flex', flexDirection:'column', gap:6, marginBottom:16 }}>
              {sec.items.map(it => {
                const inCart = cart.filter(c => c.id === it.id).reduce((a,c) => a + c.qty, 0);
                return (
                  <div key={it.id} onClick={() => setDetail({ id: it.id, qty:1, sel:{}, note:'' })} className="avb3-hover-card"
                    style={{ background:'#FFFFFF', borderRadius:14, padding:'11px 14px', display:'flex', alignItems:'center', gap:10, cursor:'pointer', boxShadow:'0 1px 0 rgba(0,0,0,0.04)', opacity: it.soldOut ? 0.5 : 1 }}>
                    <div style={{ flex:1, minWidth:0 }}>
                      <div style={{ fontSize:15, fontWeight:600, color:INK, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
                        {inCart > 0 && <span style={{ color:'#5C6410', fontWeight:800 }}>{inCart}× </span>}
                        {it.tr.n}
                      </div>
                      <div style={{ display:'flex', gap:8, marginTop:2 }}>
                        {(it.extras || []).length > 0 && <span style={{ fontSize:12, color:'#B3B3B3' }}>ekstra seçilebilir</span>}
                        {(it.hidden || sec.custHidden) && <span style={{ fontSize:11.5, color:'#2E5A8A', fontWeight:600 }}>menüde yok</span>}
                      </div>
                    </div>
                    {it.soldOut ? (
                      <span style={{ padding:'4px 10px', borderRadius:999, background:'rgba(192,58,43,0.1)', color:'#C03A2B', fontSize:11, fontWeight:700 }}>Tükendi</span>
                    ) : (
                      <>
                        <span style={{ fontSize:15, fontWeight:700, color:INK, fontVariantNumeric:'tabular-nums' }}>{O.fmt(it.price)}</span>
                        <button onClick={(e) => { e.stopPropagation(); if ((it.extras || []).length) setDetail({ id: it.id, qty:1, sel:{}, note:'' }); else addToCart(it, 1, {}, ''); }}
                          aria-label="Ekle" className="avb3-press-hard avb3-hover-green"
                          style={{ width:34, height:34, borderRadius:999, border:'none', background:GREEN, display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', flexShrink:0 }}>
                          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={INK} strokeWidth="2.4" strokeLinecap="round"><path d="M12 5v14M5 12h14" /></svg>
                        </button>
                      </>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>

      {(count > 0 || editing) && !review && !detail && (
        <div style={{ position:'absolute', left:16, right:16, bottom:16, zIndex:6 }}>
          <button onClick={() => setReview(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' }}>{count}</span>
              {editing ? 'Özete dön' : 'Devam'}
            </span>
            <span style={{ fontSize:16, fontWeight:700, fontVariantNumeric:'tabular-nums' }}>{O.fmt(total)}</span>
          </button>
        </div>
      )}

      {detailEl}
      {reviewEl}
    </div>
  );
}

function WaiterInner({ staffName }){
  const { menu } = O.useMenuConfig();
  const orders = O.useOrders({ limit: 200 });
  const [tab, setTab] = useState('orders');
  const [detailId, setDetailId] = useState(null);
  const [manualMode, setManualMode] = useState(false);
  const [manualNo, setManualNo] = useState('');
  const [scanning, setScanning] = useState(false);
  const [scanNote, setScanNote] = useState(null);
  const [composer, setComposer] = useState(null);  // { order } → düzenleme, { order:null } → yeni
  const [busy, setBusy] = useState(false);
  const [toastEl, showToast] = U.useToast();
  const videoRef = useRef(null);
  const streamRef = useRef(null);
  const loopRef = useRef(null);
  const canvasRef = useRef(null);

  const sorted = orders.slice().sort((a,b) => b.createdAt - a.createdAt);
  const pending = sorted.filter(o => o.status === 'pending');
  const done = sorted.filter(o => o.status !== 'pending').slice(0, 12);

  const patch = async (id, p, okMsg) => {
    if (busy) return;
    setBusy(true);
    try { await O.patchOrder(id, p); if (okMsg) showToast(okMsg); }
    catch(e){ showToast('İşlem başarısız — bağlantıyı kontrol edin', true); }
    setBusy(false);
  };

  /* ── QR tarama ── */
  const stopStream = () => {
    if (streamRef.current) { streamRef.current.getTracks().forEach(t => t.stop()); streamRef.current = null; }
    if (loopRef.current) { clearInterval(loopRef.current); loopRef.current = null; }
  };
  useEffect(() => () => stopStream(), []);

  const openByCode = (code) => {
    const s = String(code || '').trim();
    if (!s) return;
    let ord = null;
    const m = s.match(/^AVB:(\d+):(\S+)$/);
    if (m) ord = sorted.find(o => o.id === m[2]) || sorted.find(o => String(o.no) === m[1]);
    else ord = sorted.find(o => String(o.no) === s.replace('#',''));
    stopStream();
    if (ord) { setDetailId(ord.id); setScanning(false); setManualMode(false); setManualNo(''); setScanNote(null); setTab('orders'); }
    else { setScanNote('Sipariş bulunamadı: ' + s); setScanning(false); }
  };

  const startScan = async () => {
    const hasCamera = !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
    const hasDetector = 'BarcodeDetector' in window;
    const hasJsQR = typeof window.jsQR === 'function';
    if (!hasCamera || (!hasDetector && !hasJsQR)) {
      setManualMode(true);
      setScanNote('Bu cihazda kamerayla okuma yok — sipariş numarasını girin.');
      return;
    }
    setScanning(true); setScanNote(null);
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } });
      streamRef.current = stream;
      if (videoRef.current) videoRef.current.srcObject = stream;
      if (hasDetector) {
        const det = new window.BarcodeDetector({ formats: ['qr_code'] });
        loopRef.current = setInterval(async () => {
          try {
            const v = videoRef.current;
            if (!v || v.readyState < 2) return;
            const codes = await det.detect(v);
            if (codes && codes.length) openByCode(codes[0].rawValue);
          } catch(_){}
        }, 400);
      } else {
        // jsQR fallback: kareyi canvas'a çizip çöz
        if (!canvasRef.current) canvasRef.current = document.createElement('canvas');
        loopRef.current = setInterval(() => {
          try {
            const v = videoRef.current;
            if (!v || v.readyState < 2) return;
            const cv = canvasRef.current;
            cv.width = v.videoWidth; cv.height = v.videoHeight;
            const ctx = cv.getContext('2d');
            ctx.drawImage(v, 0, 0, cv.width, cv.height);
            const img = ctx.getImageData(0, 0, cv.width, cv.height);
            const code = window.jsQR(img.data, img.width, img.height);
            if (code && code.data) openByCode(code.data);
          } catch(_){}
        }, 400);
      }
    } catch(e){
      stopStream();
      setScanning(false); setManualMode(true);
      setScanNote('Kameraya erişilemedi — sipariş numarasını girin.');
    }
  };

  /* ── Kart ── */
  const orderCard = (o) => {
    const st = O.statusMeta(o.status);
    return (
      <div key={o.id} onClick={() => setDetailId(o.id)} className="avb3-hover-card"
        style={{ background:'#FFFFFF', borderRadius:16, padding:14, cursor:'pointer', boxShadow:'0 1px 0 rgba(0,0,0,0.04)' }}>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:10 }}>
          <div style={{ display:'flex', alignItems:'baseline', gap:8 }}>
            <span style={{ fontSize:16, fontWeight:800, color:INK, fontVariantNumeric:'tabular-nums' }}>#{o.no}</span>
            <span style={{ fontSize:12.5, fontWeight:600, color: o.tableId ? OLIVE : '#B3B3B3' }}>{O.tableLabel(menu, o.tableId) || 'Masa atanmadı'}</span>
          </div>
          <span style={{ padding:'4px 10px', borderRadius:999, background:st.bg, color:st.fg, fontSize:11, fontWeight:700 }}>{st.label}</span>
        </div>
        <div style={{ fontSize:13, color:'#808080', marginTop:6, lineHeight:1.5 }}>{O.orderSummary(o)}</div>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginTop:8 }}>
          <span style={{ fontSize:12, color:'#B3B3B3' }}>{O.timeAgo(o.createdAt)}</span>
          <span style={{ fontSize:15, fontWeight:700, color:INK, fontVariantNumeric:'tabular-nums' }}>{O.fmt(o.total)}</span>
        </div>
      </div>
    );
  };

  const groups = [];
  if (pending.length) groups.push({ label:'Bekleyen siparişler', orders: pending });
  if (done.length) groups.push({ label:'Tamamlananlar', orders: done });

  /* ── Masalar ── */
  const activeOrders = sorted.filter(o => o.status !== 'delivered' && o.status !== 'cancelled');
  const tableAreas = (menu.areas || []).map(a => ({
    id: a.id, label: a.tr,
    tables: (menu.tables || []).filter(t => t.area === a.id).map(t => {
      const tOrders = activeOrders.filter(o => o.tableId === t.id);
      const occupied = tOrders.length > 0;
      return { t, occupied, count: tOrders.length, total: tOrders.reduce((s,o) => s + o.total, 0), first: tOrders[0] };
    }),
  })).filter(a => a.tables.length);

  /* ── Detay sheet ── */
  let detailEl = null;
  const dOrder = detailId && sorted.find(x => x.id === detailId);
  if (dOrder) {
    const o = dOrder;
    const closed = o.status === 'delivered' || o.status === 'cancelled';
    detailEl = (
      <U.Sheet onClose={() => setDetailId(null)}>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'18px 18px 4px' }}>
          <div style={{ fontSize:20, fontWeight:800, color:INK, fontVariantNumeric:'tabular-nums' }}>#{o.no}</div>
          <U.CloseX onClick={() => setDetailId(null)} />
        </div>
        <div style={{ padding:'0 18px 6px', fontSize:12.5, color:'#808080' }}>
          {O.timeAgo(o.createdAt)} · {(o.lines || []).reduce((a,l) => a + l.qty, 0)} ürün
          {o.revision > 0 && <span style={{ color:'#2E5A8A', fontWeight:600 }}> · {o.revision}. düzeltme{o.revisedBy ? ' · ' + o.revisedBy : ''}</span>}
        </div>
        <div className="avb3-noscroll" style={{ overflowY:'auto', flex:1, padding:'6px 18px' }}>
          {!closed && (
            <>
              <div style={{ fontSize:12, fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'#808080', margin:'4px 2px 8px' }}>Masa ata</div>
              {(menu.areas || []).map(a => {
                const areaTables = (menu.tables || []).filter(t => t.area === a.id);
                if (!areaTables.length) return null;
                return (
                  <div key={a.id} style={{ marginBottom:10 }}>
                    <div style={{ fontSize:12, fontWeight:600, color:'#B3B3B3', margin:'0 2px 6px' }}>{a.tr}</div>
                    <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
                      {areaTables.map(t => {
                        const on = o.tableId === t.id;
                        return (
                          <button key={t.id} onClick={() => patch(o.id, { tableId: on ? null : t.id })} className="avb3-press-mid"
                            style={{ height:34, padding:'0 13px', borderRadius:999, border:'1px solid ' + (on ? INK : HAIR2), background: on ? INK : '#FFFFFF', color: on ? GREEN : '#3D3D3D', fontSize:13, fontWeight:600, cursor:'pointer' }}>
                            Masa {t.label}
                          </button>
                        );
                      })}
                    </div>
                  </div>
                );
              })}
            </>
          )}
          <div style={{ fontSize:12, fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'#808080', margin:'14px 2px 8px' }}>Sipariş içeriği</div>
          <div style={{ background:'#FFFFFF', borderRadius:14, overflow:'hidden' }}>
            {(o.lines || []).map((l, i) => {
              const sm = O.stationMeta(O.lineStation(menu, l));
              return (
              <div key={i} style={{ display:'flex', gap:10, padding:'12px 14px', borderTop: i === 0 ? 'none' : '1px solid rgba(26,26,26,0.06)', alignItems:'flex-start' }}>
                <span style={{ minWidth:28, height:24, borderRadius:8, background:'rgba(208,228,18,0.3)', color:'#3D4408', fontSize:13, fontWeight:800, display:'inline-flex', alignItems:'center', justifyContent:'center', fontVariantNumeric:'tabular-nums' }}>{l.qty}×</span>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ display:'flex', alignItems:'center', gap:7, flexWrap:'wrap' }}>
                    <span style={{ fontSize:15, fontWeight:600, color:INK }}>{l.name}</span>
                    <span style={{ padding:'2px 8px', borderRadius:999, background:sm.bg, color:sm.fg, fontSize:10.5, fontWeight:700, letterSpacing:'0.04em' }}>{sm.caps}</span>
                  </div>
                  {l.extras && l.extras.length > 0 && <div style={{ fontSize:12.5, color:'#808080', marginTop:3, lineHeight:1.4 }}>{l.extras.join(' · ')}</div>}
                  {l.note && <div style={{ fontSize:12.5, color:'#D4851C', fontWeight:600, marginTop:3, lineHeight:1.4 }}>Not: {l.note}</div>}
                </div>
                <div style={{ fontSize:14, fontWeight:700, color:INK, fontVariantNumeric:'tabular-nums' }}>{O.fmt(l.total)}</div>
              </div>
              );
            })}
          </div>
          {o.note && (
            <div style={{ marginTop:10, padding:'10px 12px', borderRadius:12, background:'rgba(212,133,28,0.1)', color:'#D4851C', fontSize:13, fontWeight:600, lineHeight:1.5 }}>
              Sipariş notu: {o.note}
            </div>
          )}
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', padding:'14px 4px' }}>
            <span style={{ fontSize:14, color:'#808080', fontWeight:500 }}>Toplam</span>
            <span style={{ fontSize:21, fontWeight:800, color:INK, fontVariantNumeric:'tabular-nums' }}>{O.fmt(o.total)}</span>
          </div>
        </div>
        <div style={{ padding:'10px 18px 16px', borderTop:'1px solid ' + HAIR }}>
          {!closed && (
            <button onClick={() => { setDetailId(null); setComposer({ order: o }); }} className="avb3-press avb3-hover-faint"
              style={{ width:'100%', height:46, borderRadius:14, border:'1px solid ' + HAIR2, background:'#FFFFFF', color:INK, fontSize:14, fontWeight:700, cursor:'pointer', marginBottom:8, display:'flex', alignItems:'center', justifyContent:'center', gap:8 }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={INK} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 20h9" /><path d="M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z" /></svg>
              Siparişi düzenle
            </button>
          )}
          {o.status === 'pending' && (
            <>
              <button onClick={() => patch(o.id, { status:'confirmed', confirmedAt: Date.now() }, 'Onaylandı — yazdırmaya gönderildi')} disabled={busy} className="avb3-press avb3-hover-olive"
                style={{ width:'100%', height:52, border:'none', borderRadius:14, background:OLIVE, color:GREEN, fontSize:15.5, fontWeight:700, cursor:'pointer', opacity: busy ? 0.7 : 1 }}>
                {o.tableId ? 'Siparişi onayla · Yazdırmaya gönder' : 'Masa seçmeden onayla'}
              </button>
              <button onClick={() => patch(o.id, { status:'cancelled', cancelledAt: Date.now() })} disabled={busy}
                style={{ width:'100%', height:40, border:'none', borderRadius:12, background:'transparent', color:'#C03A2B', fontSize:13, fontWeight:700, cursor:'pointer', marginTop:6 }}>
                Siparişi iptal et
              </button>
            </>
          )}
          {(o.status === 'confirmed' || o.status === 'printed') && (
            <>
              <div style={{ textAlign:'center', padding:10, borderRadius:12, background:'rgba(46,138,74,0.1)', color:'#2E8A4A', fontSize:13.5, fontWeight:700, marginBottom:8 }}>
                Onaylandı — yazdırma istasyonuna gönderildi ✓
              </div>
              <button onClick={() => patch(o.id, { status:'delivered', deliveredAt: Date.now() })} disabled={busy} className="avb3-press avb3-hover-olive"
                style={{ width:'100%', height:48, border:'none', borderRadius:14, background:OLIVE, color:GREEN, fontSize:14.5, fontWeight:700, cursor:'pointer', opacity: busy ? 0.7 : 1 }}>
                Teslim edildi olarak işaretle
              </button>
            </>
          )}
          {closed && (
            <div style={{ textAlign:'center', padding:12, borderRadius:12, background:'rgba(26,26,26,0.05)', color:'#3D3D3D', fontSize:14, fontWeight:700 }}>
              {o.status === 'delivered' ? 'Teslim edildi ✓' : 'İptal edildi'}
            </div>
          )}
        </div>
      </U.Sheet>
    );
  }

  /* ── Tarama ekranı ── */
  let scanEl = null;
  if (scanning) {
    scanEl = (
      <div style={{ position:'absolute', inset:0, zIndex:20, background:INK, display:'flex', flexDirection:'column', animation:'avb3Fade 200ms' }}>
        <video ref={el => { videoRef.current = el; if (el && streamRef.current) el.srcObject = streamRef.current; }} autoPlay playsInline muted
          style={{ position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'cover' }} />
        <div style={{ position:'relative', zIndex:2, display:'flex', alignItems:'center', justifyContent:'space-between', padding:16 }}>
          <span style={{ color:CREAM, fontSize:15, fontWeight:700 }}>QR kodu çerçeveye hizalayın</span>
          <button onClick={() => { stopStream(); setScanning(false); }}
            style={{ width:36, height:36, borderRadius:999, border:'none', background:'rgba(245,240,232,0.2)', color:CREAM, fontSize:16, cursor:'pointer' }}>×</button>
        </div>
        <div style={{ position:'relative', zIndex:2, flex:1, display:'flex', alignItems:'center', justifyContent:'center' }}>
          <div style={{ width:230, height:230, borderRadius:20, boxShadow:'0 0 0 3px ' + GREEN + ', 0 0 0 9999px rgba(20,20,15,0.45)' }} />
        </div>
        <div style={{ position:'relative', zIndex:2, padding:'0 24px 28px', textAlign:'center' }}>
          <button onClick={() => { stopStream(); setScanning(false); setManualMode(true); }}
            style={{ height:44, padding:'0 20px', borderRadius:12, border:'1px solid rgba(245,240,232,0.35)', background:'transparent', color:CREAM, fontSize:13.5, fontWeight:600, cursor:'pointer' }}>
            Kod okunmuyor mu? No ile bul
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="avb3-stage">
      <div className="avb3-column">
        {/* Üst bar */}
        <div style={{ background:'rgba(245,240,232,0.9)', backdropFilter:'blur(12px)', WebkitBackdropFilter:'blur(12px)', borderBottom:'1px solid ' + HAIR, zIndex:5 }}>
          <div style={{ padding:'14px 16px 10px', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
            <div style={{ display:'flex', alignItems:'center', gap:10 }}>
              <U.Wordmark />
              <U.RoleBadge label="GARSON" />
            </div>
            <span style={{ fontSize:12, fontWeight:600, color:'#808080', fontVariantNumeric:'tabular-nums' }}>{pending.length} bekleyen</span>
          </div>
          <div style={{ padding:'0 16px 12px' }}>
            <U.PillTabs tabs={[{ id:'orders', label:'Siparişler' }, { id:'tables', label:'Masalar' }]} active={tab} onChange={setTab} />
          </div>
        </div>

        {tab === 'orders' && (
          <>
            <div style={{ padding:'14px 16px 10px' }}>
              <div style={{ display:'flex', gap:8 }}>
                <button onClick={startScan} className="avb3-press avb3-hover-faint"
                  style={{ flex:1, height:54, borderRadius:16, border:'1px solid ' + HAIR2, background:'#FFFFFF', color:INK, fontSize:14.5, fontWeight:700, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', gap:8 }}>
                  <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke={INK} strokeWidth="2" strokeLinecap="round"><path d="M3 7V5a2 2 0 0 1 2-2h2M17 3h2a2 2 0 0 1 2 2v2M21 17v2a2 2 0 0 1-2 2h-2M7 21H5a2 2 0 0 1-2-2v-2" /><rect x="8" y="8" width="8" height="8" rx="1" /></svg>
                  QR Okut
                </button>
                <button onClick={() => setComposer({ order: null })} className="avb3-press avb3-hover-olive"
                  style={{ flex:1, height:54, border:'none', borderRadius:16, background:OLIVE, color:GREEN, fontSize:14.5, fontWeight:700, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', gap:8 }}>
                  <svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke={GREEN} strokeWidth="2.4" strokeLinecap="round"><path d="M12 5v14M5 12h14" /></svg>
                  Sipariş oluştur
                </button>
              </div>
              {scanNote && <div style={{ marginTop:8, fontSize:12.5, color:'#808080', textAlign:'center' }}>{scanNote}</div>}
              {manualMode && (
                <div style={{ display:'flex', gap:8, marginTop:10 }}>
                  <input value={manualNo} onChange={e => setManualNo(e.target.value)} onKeyDown={e => { if (e.key === 'Enter') openByCode(manualNo); }}
                    placeholder="Sipariş no girin (örn. 1042)" inputMode="numeric"
                    style={{ flex:1, height:44, padding:'0 14px', borderRadius:12, border:'1px solid ' + HAIR2, background:'#FFFFFF', fontSize:15, color:INK, outline:'none', boxSizing:'border-box' }} />
                  <button onClick={() => openByCode(manualNo)} className="avb3-press"
                    style={{ height:44, padding:'0 16px', borderRadius:12, border:'none', background:GREEN, color:INK, fontSize:14, fontWeight:700, cursor:'pointer' }}>Bul</button>
                </div>
              )}
            </div>
            <div className="avb3-noscroll" style={{ flex:1, overflowY:'auto', padding:'4px 16px 24px' }}>
              {groups.length === 0 && (
                <div style={{ textAlign:'center', padding:'56px 24px', color:'#808080' }}>
                  <div style={{ fontSize:16, fontWeight:600, color:'#3D3D3D', marginBottom:6 }}>Bekleyen sipariş yok</div>
                  <div style={{ fontSize:13.5, lineHeight:1.5 }}>Müşteri menüden sipariş oluşturduğunda burada görünür.</div>
                </div>
              )}
              {groups.map(grp => (
                <div key={grp.label}>
                  <div style={{ fontSize:12, fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'#808080', margin:'12px 2px 10px' }}>{grp.label}</div>
                  <div style={{ display:'flex', flexDirection:'column', gap:8, marginBottom:12 }}>
                    {grp.orders.map(orderCard)}
                  </div>
                </div>
              ))}
            </div>
          </>
        )}

        {tab === 'tables' && (
          <div className="avb3-noscroll" style={{ flex:1, overflowY:'auto', padding:'14px 16px 24px' }}>
            {tableAreas.map(ar => (
              <div key={ar.id}>
                <div style={{ fontSize:12, fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'#808080', margin:'8px 2px 10px' }}>{ar.label}</div>
                <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginBottom:18 }}>
                  {ar.tables.map(({ t, occupied, count, total, first }) => (
                    <div key={t.id} onClick={() => { if (occupied && first) { setDetailId(first.id); setTab('orders'); } }}
                      style={{ background: occupied ? 'rgba(208,228,18,0.18)' : '#FFFFFF', border:'2px solid ' + (occupied ? 'rgba(168,184,15,0.6)' : 'transparent'), borderRadius:16, padding:14, cursor: occupied ? 'pointer' : 'default', minHeight:84, display:'flex', flexDirection:'column', boxSizing:'border-box' }}>
                      <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
                        <span style={{ fontSize:16, fontWeight:800, color:INK }}>Masa {t.label}</span>
                        <span style={{ fontSize:11, fontWeight:600, color:'#808080' }}>{t.cap} kişilik</span>
                      </div>
                      <div style={{ marginTop:'auto', fontSize:12.5, fontWeight:600, color: occupied ? '#5C6410' : '#B3B3B3' }}>
                        {occupied ? count + ' sipariş · ' + O.fmt(total) : 'Boş'}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
            <div style={{ fontSize:12, color:'#B3B3B3', textAlign:'center' }}>Mekan ve masa tanımları admin panelinden yönetilir.</div>
          </div>
        )}

        {composer && (
          <OrderComposer
            menu={menu}
            staffName={staffName}
            order={composer.order}
            onClose={() => setComposer(null)}
            onDone={(o, edited) => {
              setComposer(null);
              showToast(edited
                ? ('#' + o.no + ' güncellendi' + (o.status === 'confirmed' ? ' · yazdırmaya yeniden gönderildi' : ''))
                : ('#' + o.no + ' oluşturuldu · yazdırmaya gönderildi'));
            }}
          />
        )}
        {detailEl}
        {scanEl}
        {toastEl}
      </div>
    </div>
  );
}

function WaiterV3(){
  const authState = O.useStaffAuth(['garson', 'admin', 'kasiyer']);
  return (
    <U.StaffGate authState={authState} badge="GARSON" title="Garson paneline giriş">
      <WaiterInner staffName={authState.user && authState.user.name} />
    </U.StaffGate>
  );
}

window.AvbWaiterV3 = WaiterV3;
})();
