// Avokado Bar — Sipariş Sistemi v3 ortak UI parçaları (window.AvbOrdUI)
(function(){
const { useState, useEffect, useRef } = React;

const INK = '#1A1A1A', CREAM = '#F5F0E8', GREEN = '#D0E412', OLIVE = '#6B6B59';
const HAIR = 'rgba(26,26,26,0.08)', HAIR2 = 'rgba(26,26,26,0.12)';

// "the AVOKADO bar" yazı lockup'ı
function Wordmark({ big }){
  const s = big ? [15,19] : [13,17];
  return (
    <div style={{ display:'flex', alignItems:'baseline', gap: big ? 5 : 4, userSelect:'none' }}>
      <span style={{ fontWeight:300, fontSize:s[0], color:INK }}>the</span>
      <span style={{ fontWeight:900, fontSize:s[1], letterSpacing:'0.02em', color:INK }}>AVOKADO</span>
      <span style={{ fontWeight:300, fontSize:s[0], color:INK }}>bar</span>
    </div>
  );
}

function RoleBadge({ label, olive }){
  return (
    <span style={{ padding:'4px 10px', borderRadius:999, background: olive ? OLIVE : INK, color:GREEN, fontSize:11, fontWeight:700, letterSpacing:'0.06em', whiteSpace:'nowrap' }}>
      {label}
    </span>
  );
}

function CloseX({ onClick, light }){
  return (
    <button onClick={onClick} aria-label="Kapat" className="avb3-press-hard"
      style={{ width:34, height:34, borderRadius:999, border:'none', background: light ? 'rgba(245,240,232,0.92)' : 'rgba(26,26,26,0.06)', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', flexShrink:0 }}>
      <svg width="13" height="13" viewBox="0 0 14 14" fill="none" stroke={INK} strokeWidth="2.2" strokeLinecap="round"><path d="M1 1l12 12M13 1L1 13" /></svg>
    </button>
  );
}

function Toast({ text, danger, bottom }){
  if (!text) return null;
  return (
    <div style={{ position:'absolute', bottom: bottom || 96, left:'50%', zIndex:40, transform:'translateX(-50%)', background: danger ? '#C03A2B' : INK, color:CREAM, fontSize:13.5, fontWeight:600, padding:'10px 18px', borderRadius:999, whiteSpace:'nowrap', animation:'avb3Toast 1800ms cubic-bezier(0.2,0.8,0.2,1) forwards', pointerEvents:'none' }}>
      {text}
    </div>
  );
}
// Toast state yönetimi: [toast, showToast]
function useToast(){
  const [toast, setToast] = useState(null);
  const [tKey, setTKey] = useState(0);
  const show = (text, danger) => { setToast(text ? { text, danger: !!danger } : null); setTKey(k => k+1); };
  const el = toast ? <Toast key={tKey} text={toast.text} danger={toast.danger} /> : null;
  return [el, show];
}

// Alt sheet + scrim sarmalayıcı (position:absolute — kolon içinde)
function Sheet({ onClose, children, maxHeight, z, radius }){
  const zi = z || 10;
  return (
    <>
      <div onClick={onClose} style={{ position:'absolute', inset:0, zIndex:zi, background:'rgba(20,20,15,0.55)', animation:'avb3Fade 200ms' }} />
      <div style={{ position:'absolute', left:0, right:0, bottom:0, zIndex:zi+1, background:CREAM, borderRadius: radius || '24px 24px 0 0', maxHeight: maxHeight || '88%', display:'flex', flexDirection:'column', animation:'avb3SheetUp 280ms cubic-bezier(0.2,0.8,0.2,1)', overflow:'hidden' }}>
        {children}
      </div>
    </>
  );
}

// Sağdan açılan çekmece (admin) — position:fixed
function Drawer({ onClose, children, width }){
  return (
    <>
      <div onClick={onClose} style={{ position:'fixed', inset:0, zIndex:20, background:'rgba(20,20,15,0.55)', animation:'avb3Fade 200ms' }} />
      <div className="avb3-noscroll" style={{ position:'fixed', top:0, right:0, bottom:0, zIndex:21, width: width || 'min(460px, 100%)', background:CREAM, boxShadow:'-12px 0 36px rgba(40,40,30,0.14)', overflowY:'auto', animation:'avb3SlideIn 280ms cubic-bezier(0.2,0.8,0.2,1)', boxSizing:'border-box' }}>
        {children}
      </div>
    </>
  );
}

// Sekme pilleri (aktif: siyah bg + yeşil metin)
function PillTabs({ tabs, active, onChange, height }){
  const h = height || 34;
  return (
    <div style={{ display:'flex', gap:8 }}>
      {tabs.map(t => {
        const on = t.id === active;
        return (
          <button key={t.id} onClick={() => onChange(t.id)} className="avb3-press-mid"
            style={{ height:h, padding:'0 16px', borderRadius:999, border:'1px solid ' + (on ? INK : HAIR2), background: on ? INK : '#FFFFFF', color: on ? GREEN : '#3D3D3D', fontSize:13.5, fontWeight:600, cursor:'pointer', whiteSpace:'nowrap', transition:'background 180ms cubic-bezier(0.2,0.8,0.2,1), color 180ms' }}>
            {t.label}
          </button>
        );
      })}
    </div>
  );
}

// Personel giriş / yetki kapısı — WhatsApp OTP (personel hesapları telefonla giriş yapar)
// Akış: otp_requests {action:"send"} → kod WhatsApp'tan gelir → {action:"verify"} → custom token
function StaffGate({ authState, badge, title, children }){
  const { status, role, logout, user } = authState;
  const [step, setStep] = useState('phone');   // 'phone' | 'code'
  const [phone, setPhone] = useState('');
  const [code, setCode] = useState('');
  const [err, setErr] = useState(null);
  const [info, setInfo] = useState(null);
  const [busy, setBusy] = useState(false);
  const sendIdRef = useRef(null);
  const unsubRef = useRef([]);

  useEffect(() => () => { unsubRef.current.forEach(u => { try { u(); } catch(_){} }); }, []);
  const track = (u) => { unsubRef.current.push(u); return u; };

  if (status === 'ok') return children;

  const digits = phone.replace(/\D/g, '');

  const sendCode = async () => {
    if (busy) return;
    if (digits.length < 10) { setErr('Telefon numarasını başında 0 olmadan girin (5XX XXX XX XX).'); return; }
    setBusy(true); setErr(null); setInfo(null);
    try {
      const d = window.AvbOrd.fsdb();
      if (!d) throw new Error('Bağlantı yok');
      const ref = d.collection('otp_requests').doc();
      await ref.set({ action:'send', phone: digits, dial:'+90', createdAt: Date.now() });
      sendIdRef.current = ref.id;
      setStep('code'); setCode('');
      setInfo('Kod WhatsApp ile gönderildi.');
      track(ref.onSnapshot(snap => {
        const x = snap.data(); if (!x) return;
        if (x.status === 'rate_limited' || x.status === 'error') {
          setErr(x.error || 'Kod gönderilemedi.'); setInfo(null); setStep('phone');
        }
      }));
    } catch(e){ setErr('Kod gönderilemedi: ' + (e && e.message || 'bilinmeyen hata')); }
    setBusy(false);
  };

  const verifyCode = async () => {
    if (busy) return;
    if (code.length !== 6) { setErr('6 haneli kodu girin.'); return; }
    setBusy(true); setErr(null); setInfo(null);
    try {
      const d = window.AvbOrd.fsdb();
      const orig = await d.collection('otp_requests').doc(sendIdRef.current).get();
      const od = orig.data() || {};
      const vRef = d.collection('otp_requests').doc();
      await vRef.set({
        action:'verify', code,
        phone: od.phone || digits,
        phoneFormatted: od.phoneFormatted || '',
        dial: od.dial || '+90',
        status:'waiting', createdAt: Date.now(),
      });
      track(vRef.onSnapshot(async snap => {
        const x = snap.data();
        if (!x || x.status === 'waiting') return;
        if (x.status === 'verified') {
          try { await window.auth.signInWithCustomToken(x.token); }
          catch(e){ setErr('Oturum açılamadı: ' + (e && e.message)); setBusy(false); }
        } else if (x.status === 'wrong_code') {
          setErr(x.error || 'Kod hatalı.'); setBusy(false);
        } else {
          setErr(x.error || 'Kodun süresi doldu, tekrar gönderin.'); setStep('phone'); setBusy(false);
        }
      }));
    } catch(e){ setErr('Doğrulanamadı: ' + (e && e.message || 'bilinmeyen hata')); setBusy(false); }
  };

  const fieldStyle = { width:'100%', height:46, padding:'0 14px', borderRadius:12, border:'1px solid ' + HAIR2, fontSize:16, color:INK, outline:'none', boxSizing:'border-box', background:CREAM };

  let body = null;
  if (status === 'loading') {
    body = <div style={{ textAlign:'center', color:'#808080', fontSize:14, padding:'24px 0' }}>Yükleniyor…</div>;
  } else if (status === 'nofirebase') {
    body = <div style={{ textAlign:'center', color:'#C03A2B', fontSize:14, padding:'24px 0' }}>Bağlantı kurulamadı — sayfayı yenileyin.</div>;
  } else if (status === 'denied') {
    body = (
      <div style={{ textAlign:'center', padding:'8px 0' }}>
        <div style={{ padding:'10px 12px', borderRadius:10, background:'rgba(192,58,43,0.1)', color:'#C03A2B', fontSize:13, fontWeight:600, marginBottom:12 }}>
          Bu panel için yetkiniz yok{role ? ' (rol: ' + role + ')' : ''}.
        </div>
        <button onClick={logout} className="avb3-press" style={{ height:44, padding:'0 20px', borderRadius:12, border:'1px solid ' + HAIR2, background:'#FFFFFF', fontSize:14, fontWeight:600, color:INK, cursor:'pointer' }}>
          Farklı numarayla giriş yap
        </button>
      </div>
    );
  } else if (step === 'phone') {
    body = (
      <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
        <div>
          <div style={{ fontSize:11, fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'#808080', marginBottom:5 }}>Telefon numarası</div>
          <div style={{ display:'flex', gap:8, alignItems:'center' }}>
            <span style={{ height:46, display:'inline-flex', alignItems:'center', padding:'0 12px', borderRadius:12, background:'rgba(26,26,26,0.05)', fontSize:15, fontWeight:700, color:'#3D3D3D', flexShrink:0 }}>+90</span>
            <input value={phone} onChange={e => { setPhone(e.target.value); setErr(null); }}
              onKeyDown={e => { if (e.key === 'Enter') sendCode(); }}
              type="tel" inputMode="numeric" autoComplete="tel" placeholder="5XX XXX XX XX" maxLength={14}
              style={{ ...fieldStyle, fontVariantNumeric:'tabular-nums' }} />
          </div>
        </div>
        {err && <div style={{ padding:'10px 12px', borderRadius:10, background:'rgba(192,58,43,0.1)', color:'#C03A2B', fontSize:13, fontWeight:600 }}>{err}</div>}
        <button onClick={sendCode} disabled={busy} className="avb3-press avb3-hover-olive"
          style={{ height:48, border:'none', borderRadius:14, background:OLIVE, color:GREEN, fontSize:15, fontWeight:700, cursor:'pointer', marginTop:4, opacity: busy ? 0.7 : 1 }}>
          {busy ? 'Gönderiliyor…' : 'WhatsApp ile kod gönder'}
        </button>
        <div style={{ textAlign:'center', fontSize:12, color:'#B3B3B3', lineHeight:1.5 }}>
          Personel numaranıza WhatsApp'tan 6 haneli kod gelir.
        </div>
      </div>
    );
  } else {
    body = (
      <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
        <div>
          <div style={{ fontSize:11, fontWeight:600, letterSpacing:'0.08em', textTransform:'uppercase', color:'#808080', marginBottom:5 }}>WhatsApp'tan gelen kod</div>
          <input value={code} onChange={e => { setCode(e.target.value.replace(/\D/g,'').slice(0,6)); setErr(null); }}
            onKeyDown={e => { if (e.key === 'Enter') verifyCode(); }}
            type="text" inputMode="numeric" autoComplete="one-time-code" placeholder="––––––" autoFocus
            style={{ ...fieldStyle, textAlign:'center', letterSpacing:'0.4em', fontSize:22, fontWeight:700, fontVariantNumeric:'tabular-nums' }} />
        </div>
        {info && !err && <div style={{ padding:'10px 12px', borderRadius:10, background:'rgba(46,138,74,0.1)', color:'#2E8A4A', fontSize:13, fontWeight:600 }}>{info}</div>}
        {err && <div style={{ padding:'10px 12px', borderRadius:10, background:'rgba(192,58,43,0.1)', color:'#C03A2B', fontSize:13, fontWeight:600 }}>{err}</div>}
        <button onClick={verifyCode} disabled={busy || code.length !== 6} className="avb3-press avb3-hover-olive"
          style={{ height:48, border:'none', borderRadius:14, background:OLIVE, color:GREEN, fontSize:15, fontWeight:700, cursor:'pointer', marginTop:4, opacity: (busy || code.length !== 6) ? 0.7 : 1 }}>
          {busy ? 'Doğrulanıyor…' : 'Giriş yap'}
        </button>
        <button onClick={() => { setStep('phone'); setCode(''); setErr(null); setInfo(null); setBusy(false); }}
          style={{ height:38, border:'none', background:'none', color:'#808080', fontSize:13, fontWeight:600, cursor:'pointer' }}>
          Numarayı değiştir · Kodu tekrar gönder
        </button>
      </div>
    );
  }

  return (
    <div className="avb3-screen" style={{ flex:1, minHeight:'100dvh', boxSizing:'border-box', display:'flex', alignItems:'center', justifyContent:'center', padding:24, background:CREAM }}>
      <div style={{ width:'100%', maxWidth:380, background:'#FFFFFF', borderRadius:20, padding:'32px 28px', boxShadow:'0 1px 0 rgba(0,0,0,0.04), 0 8px 24px rgba(40,40,30,0.06)' }}>
        <div style={{ display:'flex', justifyContent:'center', marginBottom:6 }}><Wordmark /></div>
        <div style={{ textAlign:'center', fontSize:13, fontWeight:600, color:'#808080', marginBottom:8 }}>{title}</div>
        <div style={{ display:'flex', justifyContent:'center', marginBottom:20 }}><RoleBadge label={badge} /></div>
        {body}
      </div>
    </div>
  );
}

window.AvbOrdUI = { INK, CREAM, GREEN, OLIVE, HAIR, HAIR2, Wordmark, RoleBadge, CloseX, Toast, useToast, Sheet, Drawer, PillTabs, StaffGate };
})();
