// Avokado Bar — v3 Yazdırma İstasyonu (Yazdirma Istasyonu.dc.html referansına piksel uyumlu)
// Erişim: /yazdirma — window.AvbPrintV3
// Fiş, ürünün hazırlandığı istasyona göre ayrılır: MUTFAK ve SERVİS ayrı fiş basar.
// Not: Gerçek termal basım için print-station-electron menu_orders 'confirmed'
// siparişlerini aynı fiş düzeniyle besleyebilir; burada window.print kullanılır.
(function(){
const { useState, useEffect } = React;
const O = window.AvbOrd;
const U = window.AvbOrdUI;
const { INK, CREAM, GREEN, OLIVE, HAIR, HAIR2 } = U;

function PrintInner(){
  const { menu } = O.useMenuConfig();
  const orders = O.useOrders({ limit: 200 });
  const [selId, setSelId] = useState(null);
  const [stFilter, setStFilter] = useState('all');
  const [toastEl, showToast] = U.useToast();

  // Print CSS kapsamı: yalnız bu yüzeyde body class'ı
  useEffect(() => {
    document.body.classList.add('avb3-print-station');
    return () => document.body.classList.remove('avb3-print-station');
  }, []);

  const sorted = orders.slice().sort((a,b) => (b.confirmedAt || b.createdAt) - (a.confirmedAt || a.createdAt));
  const queue = sorted.filter(o => o.status === 'confirmed');
  const printed = sorted.filter(o => o.status === 'printed').slice(0, 15);
  const effSelId = (selId && sorted.some(o => o.id === selId)) ? selId : (queue[0] && queue[0].id);
  const sel = sorted.find(o => o.id === effSelId) || null;

  const tLabel = (id) => O.tableLabel(menu, id) || 'Gel-al / Masasız';
  const parts = sel ? O.splitByStation(menu, sel) : [];
  const shown = parts.filter(p => stFilter === 'all' || p.id === stFilter);
  const split = parts.length > 1;

  const doPrint = async () => {
    window.print();
    if (sel && sel.status === 'confirmed' && stFilter === 'all') {
      try { await O.patchOrder(sel.id, { status:'printed', printedAt: Date.now() }); }
      catch(e){ showToast('Durum güncellenemedi — bağlantıyı kontrol edin', true); }
    }
  };

  // Kuyruk kartında hangi istasyona kaç ürün gittiği
  const stationSummary = (o) => O.splitByStation(menu, o)
    .map(p => p.meta.label + ' ' + p.lines.reduce((a,l) => a + (Number(l.qty) || 0), 0))
    .join(' · ');

  const receipt = (part) => (
    <div key={part.id} className="avb-receipt"
      style={{ background:'#FFFFFF', borderRadius:16, padding:'0 0 22px', overflow:'hidden', boxShadow:'0 1px 0 rgba(0,0,0,0.04), 0 8px 24px rgba(40,40,30,0.08)', fontVariantNumeric:'tabular-nums', marginBottom:14 }}>
      {split && (
        <div style={{ background:INK, color:CREAM, padding:'9px 22px', fontSize:14, fontWeight:800, letterSpacing:'0.14em', textAlign:'center' }}>
          {part.meta.caps}
        </div>
      )}
      <div style={{ padding:'20px 22px 0' }}>
        {sel.revision > 0 && (
          <div style={{ border:'2px solid ' + INK, padding:'6px 8px', textAlign:'center', fontSize:12, fontWeight:800, color:INK, marginBottom:12, letterSpacing:'0.06em' }}>
            DÜZELTİLDİ · {sel.revision}. SÜRÜM — ÖNCEKİ FİŞİ İPTAL EDİN
          </div>
        )}
        <div style={{ textAlign:'center', borderBottom:'2px solid ' + INK, paddingBottom:12 }}>
          <div style={{ display:'flex', alignItems:'baseline', gap:4, justifyContent:'center' }}>
            <span style={{ fontWeight:300, fontSize:13, color:INK }}>the</span>
            <span style={{ fontWeight:900, fontSize:18, letterSpacing:'0.02em', color:INK }}>AVOKADO</span>
            <span style={{ fontWeight:300, fontSize:13, color:INK }}>bar</span>
          </div>
          <div style={{ fontSize:11, color:'#808080', marginTop:3 }}>Nişantaşı, İstanbul</div>
        </div>
        <div style={{ display:'flex', justifyContent:'space-between', padding:'12px 0 4px', fontSize:13, color:'#3D3D3D' }}>
          <span style={{ fontWeight:800, fontSize:16, color:INK }}>#{sel.no}</span>
          <span>{O.fmtWhen(sel.createdAt)}</span>
        </div>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', paddingBottom:10, borderBottom:'1px dashed rgba(26,26,26,0.25)' }}>
          <span style={{ fontSize:13.5, fontWeight:700, color:INK }}>{tLabel(sel.tableId)}</span>
          <span style={{ fontSize:12, fontWeight:800, color:INK, letterSpacing:'0.08em' }}>{part.meta.caps}</span>
        </div>
        <div style={{ padding:'8px 0', borderBottom:'1px dashed rgba(26,26,26,0.25)' }}>
          {part.lines.map((l, i) => (
            <div key={i} style={{ padding:'5px 0' }}>
              <div style={{ display:'flex', justifyContent:'space-between', gap:10, fontSize:13.5, fontWeight:600, color:INK }}>
                <span>{l.qty}× {l.name}</span>
                <span style={{ flexShrink:0 }}>{O.fmt(l.total)}</span>
              </div>
              {l.extras && l.extras.length > 0 && (
                <div style={{ fontSize:12, color:'#808080', paddingLeft:14, lineHeight:1.45 }}>+ {l.extras.join(' · + ')}</div>
              )}
              {l.note && (
                <div style={{ fontSize:12.5, fontWeight:700, color:INK, paddingLeft:14, lineHeight:1.45 }}>» NOT: {l.note}</div>
              )}
            </div>
          ))}
        </div>
        {sel.note && (
          <div style={{ padding:'8px 0', borderBottom:'1px dashed rgba(26,26,26,0.25)', fontSize:12.5, fontWeight:700, color:INK, lineHeight:1.45 }}>
            » SİPARİŞ NOTU: {sel.note}
          </div>
        )}
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', paddingTop:10 }}>
          <span style={{ fontSize:13, fontWeight:700, color:INK }}>{split ? part.meta.caps + ' TOPLAM' : 'TOPLAM'}</span>
          <span style={{ fontSize:19, fontWeight:800, color:INK }}>{O.fmt(part.total)}</span>
        </div>
        {split && (
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', paddingTop:4, fontSize:12, color:'#808080' }}>
            <span>Sipariş toplamı</span>
            <span>{O.fmt(sel.total)}</span>
          </div>
        )}
        <div style={{ textAlign:'center', fontSize:11, color:'#B3B3B3', marginTop:14 }}>Afiyet olsun · avokadobar.com</div>
      </div>
    </div>
  );

  const filters = [{ id:'all', label:'Tüm fişler' }].concat(parts.map(p => ({ id:p.id, label:p.meta.label })));

  return (
    <div style={{ minHeight:'100dvh', background:CREAM, display:'flex', flexDirection:'column', position:'relative' }}>
      <div style={{ background:'rgba(245,240,232,0.9)', backdropFilter:'blur(12px)', borderBottom:'1px solid ' + HAIR, padding:'14px 24px', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
        <div style={{ display:'flex', alignItems:'center', gap:12 }}>
          <U.Wordmark />
          <U.RoleBadge label="YAZDIRMA İSTASYONU" />
        </div>
        <span style={{ fontSize:13, fontWeight:600, color:'#808080', fontVariantNumeric:'tabular-nums' }}>{queue.length} sipariş kuyrukta</span>
      </div>

      <div style={{ flex:1, maxWidth:1100, width:'100%', margin:'0 auto', padding:24, boxSizing:'border-box', display:'grid', gridTemplateColumns:'minmax(300px, 1fr) minmax(320px, 420px)', gap:24, alignItems:'start' }}>
        <div>
          <div style={{ fontSize:12, fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'#808080', margin:'0 2px 10px' }}>Yazdırma kuyruğu</div>
          {queue.length === 0 && (
            <div style={{ background:'#FFFFFF', borderRadius:16, padding:'32px 24px', textAlign:'center', color:'#808080', fontSize:14, lineHeight:1.6 }}>
              Kuyrukta sipariş yok.<br />Garson onayladığı siparişler burada belirir.
            </div>
          )}
          <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
            {queue.map(o => {
              const on = o.id === effSelId;
              return (
                <div key={o.id} onClick={() => { setSelId(o.id); setStFilter('all'); }} className="avb3-hover-card"
                  style={{ background:'#FFFFFF', borderRadius:16, padding:'14px 16px', cursor:'pointer', boxShadow: on ? '0 8px 24px rgba(40,40,30,0.08)' : '0 1px 0 rgba(0,0,0,0.04)', border:'2px solid ' + (on ? GREEN : 'transparent') }}>
                  <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', gap:10 }}>
                    <div style={{ display:'flex', alignItems:'baseline', gap:10, flexWrap:'wrap' }}>
                      <span style={{ fontSize:16, fontWeight:800, color:INK, fontVariantNumeric:'tabular-nums' }}>#{o.no}</span>
                      <span style={{ fontSize:13, fontWeight:600, color:OLIVE }}>{tLabel(o.tableId)}</span>
                      {o.revision > 0 && (
                        <span style={{ padding:'2px 8px', borderRadius:999, background:'rgba(46,90,138,0.12)', color:'#2E5A8A', fontSize:10.5, fontWeight:700 }}>DÜZELTİLDİ</span>
                      )}
                    </div>
                    <span style={{ fontSize:12, color:'#B3B3B3' }}>{O.fmtClock(o.confirmedAt || o.createdAt)}</span>
                  </div>
                  <div style={{ fontSize:13, color:'#808080', marginTop:5, lineHeight:1.5 }}>{O.orderSummary(o)}</div>
                  <div style={{ fontSize:11.5, color:'#B3B3B3', marginTop:4, fontWeight:600 }}>{stationSummary(o)}</div>
                </div>
              );
            })}
          </div>
          {printed.length > 0 && (
            <>
              <div style={{ fontSize:12, fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'#808080', margin:'20px 2px 10px' }}>Yazdırılanlar</div>
              <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
                {printed.map(p => (
                  <div key={p.id} onClick={() => { setSelId(p.id); setStFilter('all'); }}
                    style={{ background:'rgba(255,255,255,0.6)', borderRadius:12, padding:'10px 14px', cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'space-between', opacity:0.75, border:'2px solid ' + (p.id === effSelId ? GREEN : 'transparent') }}>
                    <span style={{ fontSize:14, fontWeight:700, color:'#3D3D3D', fontVariantNumeric:'tabular-nums' }}>
                      #{p.no} <span style={{ fontWeight:500, color:'#808080' }}>{tLabel(p.tableId)}</span>
                    </span>
                    <span style={{ fontSize:12, color:'#B3B3B3' }}>{O.fmtClock(p.printedAt || p.createdAt)}</span>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>

        <div>
          {sel ? (
            <>
              {parts.length > 1 && (
                <div className="avb-noprint" style={{ display:'flex', gap:6, marginBottom:12, flexWrap:'wrap' }}>
                  {filters.map(f => {
                    const on = f.id === stFilter;
                    return (
                      <button key={f.id} onClick={() => setStFilter(f.id)}
                        style={{ height:34, padding:'0 14px', borderRadius:999, border:'1px solid ' + (on ? INK : HAIR2), background: on ? INK : '#FFFFFF', color: on ? GREEN : '#3D3D3D', fontSize:13, fontWeight:600, cursor:'pointer' }}>
                        {f.label}
                      </button>
                    );
                  })}
                </div>
              )}
              <div className="avb-print-area">
                {shown.map(receipt)}
              </div>
              <button onClick={doPrint} className="avb3-press avb3-hover-olive avb-noprint"
                style={{ width:'100%', height:50, border:'none', borderRadius:14, background:OLIVE, color:GREEN, fontSize:15, fontWeight:700, cursor:'pointer' }}>
                {sel.status === 'printed' ? 'Tekrar yazdır' : 'Yazdır'}
                {shown.length > 1 ? ' · ' + shown.length + ' fiş' : ''}
              </button>
              {stFilter !== 'all' && (
                <div className="avb-noprint" style={{ fontSize:12, color:'#B3B3B3', textAlign:'center', marginTop:8, lineHeight:1.5 }}>
                  Tek istasyon yazdırılıyor — sipariş “yazdırıldı” olarak işaretlenmez.
                </div>
              )}
            </>
          ) : (
            <div style={{ background:'rgba(255,255,255,0.6)', borderRadius:16, padding:'48px 24px', textAlign:'center', color:'#808080', fontSize:14 }}>
              Önizleme için kuyruktan sipariş seçin
            </div>
          )}
        </div>
      </div>
      {toastEl}
    </div>
  );
}

function PrintV3(){
  const authState = O.useStaffAuth(['printer', 'admin', 'garson', 'kasiyer']);
  return (
    <U.StaffGate authState={authState} badge="YAZDIRMA İSTASYONU" title="Yazdırma istasyonuna giriş">
      <PrintInner />
    </U.StaffGate>
  );
}

window.AvbPrintV3 = PrintV3;
})();
