// Cart + Checkout flow — namespaced under window.AvbX
(function(){
const { useState, useEffect, useRef } = React;
const {
  INK, GREEN, OLIVE, CREAM,
  ITEMS, TABLES, POINTS_RATES, findModOption,
  T, Icon, Tap, DishImage, IconButton, PrimaryButton, SecondaryButton, GhostButton, Stepper, useScrollY, fmt,
} = window.AvbX;

// ── reusable screen header ──
function ScreenHeader({ title, onBack, right, scrolled }) {
  return (
    <div style={{ position:'sticky', top:0, zIndex:20, paddingTop:46, background:scrolled?'rgba(245,240,232,0.9)':CREAM, backdropFilter:scrolled?'blur(14px) saturate(160%)':'none', WebkitBackdropFilter:scrolled?'blur(14px) saturate(160%)':'none', borderBottom:scrolled?'1px solid rgba(26,26,26,0.07)':'1px solid transparent', transition:'background 200ms' }}>
      <div style={{ padding:'8px 16px 12px', minHeight:48, display:'flex', alignItems:'center', gap:10 }}>
        {onBack && <IconButton onClick={onBack} size={38}><Icon.back size={18} /></IconButton>}
        <div style={{ fontWeight:800, fontSize:19, color:INK, letterSpacing:'-0.015em', flex:1 }}>{title}</div>
        {right}
      </div>
    </div>
  );
}

function CartLine({ line, lang, onInc, onDec }) {
  const item = ITEMS.find(i=>i.id===line.itemId);
  if (!item) return null;
  const L = item[lang];
  const labels = [];
  Object.values(line.sel||{}).forEach(v=>{ (Array.isArray(v)?v:(v?[v]:[])).forEach(id=>{ const o=findModOption(id); if(o && o.delta>0) labels.push(o[lang]); }); });
  return (
    <div style={{ display:'flex', gap:12, padding:'14px 0', borderBottom:'1px solid rgba(26,26,26,0.07)' }}>
      <DishImage photo={item.photo} tone={item.tone} radius={12} style={{ width:58, height:58 }} />
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontWeight:700, fontSize:15, color:INK, lineHeight:1.25 }}>{L.n}</div>
        <div style={{ fontSize:12.5, color:'#999', marginTop:3, fontVariantNumeric:'tabular-nums' }}>{fmt(line.unitPrice)}</div>
        {labels.length>0 && <div style={{ fontSize:12, color:OLIVE, marginTop:3, fontWeight:600 }}>+ {labels.join(', ')}</div>}
        {line.note && <div style={{ fontSize:12, color:'#B07A2A', marginTop:3, fontStyle:'italic' }}>“{line.note}”</div>}
      </div>
      <Stepper value={line.qty} onInc={onInc} onDec={onDec} size="sm" />
    </div>
  );
}

function CartScreen({ cart, lang, orderType, onInc, onDec, onCheckout, onBrowse, onChangeType, points }) {
  const ref = useRef(null); const y = useScrollY(ref); const scrolled = y>6;
  const subtotal = cart.reduce((s,c)=>s+c.unitPrice*c.qty,0);
  const earn = Math.floor(subtotal * (POINTS_RATES[orderType]||0.01));
  const typeLabel = { dine_in:T[lang].orderTypeDinein, takeaway:T[lang].orderTypeTakeaway, delivery:T[lang].orderTypeDelivery }[orderType];
  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column' }}>
      <div ref={ref} style={{ flex:1, overflowY:'auto' }}>
        <ScreenHeader title={T[lang].cart} scrolled={scrolled} />
        <div style={{ padding:'4px 18px 150px' }}>
          {cart.length===0 ? (
            <div style={{ padding:'80px 20px', textAlign:'center' }}>
              <div style={{ display:'inline-flex', width:64, height:64, borderRadius:999, background:'#fff', alignItems:'center', justifyContent:'center', boxShadow:'inset 0 0 0 1px rgba(26,26,26,0.08)' }}><Icon.bag size={26} color="#999" /></div>
              <div style={{ marginTop:14, fontWeight:800, fontSize:19, color:INK }}>{T[lang].empty}</div>
              <div style={{ marginTop:4, fontSize:14, color:'#999' }}>{T[lang].emptyDesc}</div>
              <div style={{ marginTop:18 }}><SecondaryButton onClick={onBrowse}>{T[lang].browseMenu}</SecondaryButton></div>
            </div>
          ) : (<>
            <Tap onClick={onChangeType} style={{ width:'100%', background:'#fff', borderRadius:16, padding:'12px 14px', display:'flex', alignItems:'center', gap:12, boxShadow:'inset 0 0 0 1px rgba(26,26,26,0.06)', border:'none', cursor:'pointer', marginTop:8 }}>
              <span style={{ width:38, height:38, borderRadius:10, background:GREEN, color:INK, display:'inline-flex', alignItems:'center', justifyContent:'center' }}>{orderType==='dine_in'?<Icon.qr size={18} />:orderType==='takeaway'?<Icon.bag size={18} />:<Icon.pin size={18} />}</span>
              <span style={{ flex:1, textAlign:'left' }}>
                <span style={{ display:'block', fontSize:11, color:'#999', textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:700 }}>{T[lang].orderTypeLabel}</span>
                <span style={{ display:'block', fontWeight:700, fontSize:15, color:INK }}>{typeLabel}</span>
              </span>
              <span style={{ fontSize:13, color:OLIVE, fontWeight:700, display:'inline-flex', alignItems:'center', gap:3 }}>{T[lang].change}<Icon.chevron size={13} color={OLIVE} /></span>
            </Tap>

            <div style={{ marginTop:4 }}>
              {cart.map(line=><CartLine key={line.key} line={line} lang={lang} onInc={()=>onInc(line.key)} onDec={()=>onDec(line.key)} />)}
            </div>

            <Tap onClick={onBrowse} style={{ marginTop:14, width:'100%', background:'transparent', border:'1px dashed rgba(26,26,26,0.25)', borderRadius:12, padding:'12px', color:OLIVE, fontWeight:700, fontSize:14, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', gap:6, fontFamily:'var(--font-body)' }}><Icon.plus size={15} color={OLIVE} />{T[lang].addMore}</Tap>

            <div style={{ marginTop:16, padding:16, borderRadius:16, background:'#fff', boxShadow:'inset 0 0 0 1px rgba(26,26,26,0.06)', display:'flex', flexDirection:'column', gap:8 }}>
              <div style={{ display:'flex', justifyContent:'space-between', color:'#555', fontSize:14 }}><span>{T[lang].subtotal}</span><span style={{ fontVariantNumeric:'tabular-nums' }}>{fmt(subtotal)}</span></div>
              <div style={{ display:'flex', justifyContent:'space-between', fontSize:14 }}><span style={{ color:'#555' }}>{T[lang].earn}</span><span style={{ color:OLIVE, fontWeight:700, fontVariantNumeric:'tabular-nums' }}>+{earn} P</span></div>
              <div style={{ height:1, background:'rgba(26,26,26,0.08)', margin:'6px 0' }} />
              <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline' }}><span style={{ fontWeight:700, fontSize:16, color:INK }}>{T[lang].total}</span><span style={{ fontWeight:900, fontSize:22, color:INK, fontVariantNumeric:'tabular-nums', letterSpacing:'-0.015em' }}>{fmt(subtotal)}</span></div>
            </div>
          </>)}
        </div>
      </div>
      {cart.length>0 && (
        <div style={{ position:'absolute', bottom:0, left:0, right:0, padding:'14px 16px calc(20px + env(safe-area-inset-bottom,0px))', background:'linear-gradient(to top, var(--avb-cream) 62%, rgba(245,240,232,0))' }}>
          <PrimaryButton full onClick={onCheckout}><span>{T[lang].checkout}</span><span style={{ fontWeight:800, fontVariantNumeric:'tabular-nums', marginLeft:'auto' }}>{fmt(subtotal)}</span></PrimaryButton>
        </div>
      )}
    </div>
  );
}

// ── Table select (dine-in) ──
function TableSelectScreen({ lang, onBack, selected, onSelect, onNext }) {
  const [area, setArea] = useState('ic');
  const tables = TABLES.filter(t=>t.area===area);
  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column' }}>
      <ScreenHeader title={T[lang].selectTable} onBack={onBack} scrolled />
      <div style={{ flex:1, overflowY:'auto', padding:'8px 18px 120px' }}>
        <div style={{ display:'flex', gap:8, marginBottom:18 }}>
          {[['ic',T[lang].indoor],['dis',T[lang].outdoor]].map(([k,lbl])=>{ const on=area===k; return (
            <Tap key={k} onClick={()=>setArea(k)} style={{ flex:1, padding:'12px', borderRadius:12, border:'none', background:on?INK:'#fff', color:on?CREAM:INK, fontWeight:700, fontSize:14, cursor:'pointer', boxShadow:on?'none':'inset 0 0 0 1px rgba(26,26,26,0.08)' }}>{lbl}</Tap>
          ); })}
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
          {tables.map(t=>{ const on=selected===t.id; const num=t.id.replace(/[a-z]/g,''); return (
            <Tap key={t.id} onClick={()=>onSelect(t.id)} style={{ aspectRatio:'1.4', borderRadius:16, border:'none', cursor:'pointer', background:on?GREEN:'#fff', boxShadow:on?'none':'inset 0 0 0 1px rgba(26,26,26,0.08)', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:4, position:'relative' }}>
              <Icon.qr size={20} color={on?INK:'#999'} />
              <span style={{ fontWeight:800, fontSize:22, color:INK, letterSpacing:'-0.02em' }}>{T[lang].table} {num}</span>
              <span style={{ fontSize:11, color:on?'rgba(26,26,26,0.6)':'#999', fontWeight:600 }}>{t.cap} {T[lang].person}</span>
              {on && <span style={{ position:'absolute', top:8, right:8, width:22, height:22, borderRadius:999, background:INK, display:'inline-flex', alignItems:'center', justifyContent:'center' }}><Icon.check size={13} color={GREEN} /></span>}
            </Tap>
          ); })}
        </div>
      </div>
      <div style={{ position:'absolute', bottom:0, left:0, right:0, padding:'14px 16px calc(20px + env(safe-area-inset-bottom,0px))', background:'linear-gradient(to top, var(--avb-cream) 62%, rgba(245,240,232,0))' }}>
        <PrimaryButton full disabled={!selected} onClick={onNext}>{T[lang].next}</PrimaryButton>
      </div>
    </div>
  );
}

// ── Pickup time (takeaway) ──
function PickupTimeScreen({ lang, onBack, selected, onSelect, onNext }) {
  const slots = ['asap','15','30','45','60'];
  const label = (s) => s==='asap'? T[lang].asap : (lang==='tr'?`+${s} dk`:`+${s} min`);
  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column' }}>
      <ScreenHeader title={T[lang].pickupTime} onBack={onBack} scrolled />
      <div style={{ flex:1, overflowY:'auto', padding:'8px 18px 120px' }}>
        <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
          {slots.map(s=>{ const on=selected===s; return (
            <Tap key={s} onClick={()=>onSelect(s)} style={{ display:'flex', alignItems:'center', gap:12, padding:'16px', borderRadius:14, background:'#fff', border:'none', boxShadow:on?`inset 0 0 0 2px ${OLIVE}`:'inset 0 0 0 1px rgba(26,26,26,0.08)', cursor:'pointer' }}>
              <Icon.clock size={20} color={on?OLIVE:'#999'} />
              <span style={{ flex:1, textAlign:'left', fontWeight:700, fontSize:16, color:INK }}>{s==='asap'?T[lang].asap:(lang==='tr'?'Belirli saat':'Specific time')}</span>
              <span style={{ fontSize:14, color:on?OLIVE:'#999', fontWeight:700, fontVariantNumeric:'tabular-nums' }}>{s==='asap'?(lang==='tr'?'~15 dk':'~15 min'):label(s)}</span>
            </Tap>
          ); })}
        </div>
      </div>
      <div style={{ position:'absolute', bottom:0, left:0, right:0, padding:'14px 16px calc(20px + env(safe-area-inset-bottom,0px))', background:'linear-gradient(to top, var(--avb-cream) 62%, rgba(245,240,232,0))' }}>
        <PrimaryButton full disabled={!selected} onClick={onNext}>{T[lang].next}</PrimaryButton>
      </div>
    </div>
  );
}

// ── Address form (delivery) ──
function AddressScreen({ lang, onBack, onNext }) {
  const [f, setF] = useState({ name:'', phone:'', neighborhood:'', district:'', full:'' });
  const set = (k)=>(e)=>setF(p=>({ ...p, [k]:e.target.value }));
  const inZone = f.neighborhood.trim().length>2;
  const valid = f.name && f.phone && f.neighborhood && f.full;
  const field = (k, label, ph) => (
    <div style={{ marginBottom:12 }}>
      <div style={{ fontSize:11, fontWeight:700, color:'#999', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:6 }}>{label}</div>
      <input value={f[k]} onChange={set(k)} placeholder={ph} style={{ width:'100%', border:'none', outline:'none', background:'#fff', boxShadow:'inset 0 0 0 1px rgba(26,26,26,0.08)', borderRadius:12, padding:'13px 14px', fontFamily:'var(--font-body)', fontSize:15, color:INK }} />
      {k==='neighborhood' && inZone && <div style={{ fontSize:12, color:'#3F6B2E', marginTop:5, fontWeight:600, display:'flex', alignItems:'center', gap:4 }}><Icon.check size={13} color="#3F6B2E" />{T[lang].inZone}</div>}
    </div>
  );
  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column' }}>
      <ScreenHeader title={T[lang].deliveryAddr} onBack={onBack} scrolled />
      <div style={{ flex:1, overflowY:'auto', padding:'10px 18px 120px' }}>
        {field('name', T[lang].addrName, lang==='tr'?'Ad Soyad':'Full name')}
        {field('phone', T[lang].addrPhone, '+90 5__ ___ __ __')}
        {field('neighborhood', T[lang].addrNeighborhood, lang==='tr'?'Mahalle adı':'Neighbourhood')}
        {field('district', T[lang].addrDistrict, lang==='tr'?'İlçe':'District')}
        {field('full', T[lang].addrFull, lang==='tr'?'Cadde, sokak, bina no, daire':'Street, building, apt')}
      </div>
      <div style={{ position:'absolute', bottom:0, left:0, right:0, padding:'14px 16px calc(20px + env(safe-area-inset-bottom,0px))', background:'linear-gradient(to top, var(--avb-cream) 62%, rgba(245,240,232,0))' }}>
        <PrimaryButton full disabled={!valid} onClick={onNext}>{T[lang].next}</PrimaryButton>
      </div>
    </div>
  );
}

// ── Confirm + payment selection ──
function ConfirmScreen({ cart, lang, orderType, meta, balance, onBack, onPlace }) {
  const ref=useRef(null); const y=useScrollY(ref); const scrolled=y>6;
  const [pay, setPay] = useState('balance');
  const subtotal = cart.reduce((s,c)=>s+c.unitPrice*c.qty,0);
  const delivery = orderType==='delivery' ? 0 : 0; // free
  const total = subtotal + delivery;
  const earn = Math.floor(total * (POINTS_RATES[orderType]||0.01));
  const typeLabel = { dine_in:`${T[lang].orderTypeDinein} · ${T[lang].table} ${(meta.table||'').replace(/[a-z]/g,'')}`, takeaway:T[lang].orderTypeTakeaway, delivery:T[lang].orderTypeDelivery }[orderType];
  const pays = [
    { id:'balance', label:T[lang].avkWallet, sub:fmt(balance||0), I:Icon.walletPts },
    { id:'card', label:T[lang].savedCard, sub:'•••• 4921', I:Icon.card },
    { id:'apple', label:T[lang].applePay, sub:'', I:Icon.apple },
    { id:'venue', label:T[lang].payAtVenue, sub:'', I:Icon.qr },
  ];
  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column' }}>
      <div ref={ref} style={{ flex:1, overflowY:'auto' }}>
        <ScreenHeader title={T[lang].confirmOrder} onBack={onBack} scrolled={scrolled} />
        <div style={{ padding:'4px 18px 150px' }}>
          {/* summary */}
          <div style={{ fontSize:11, color:'#999', textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:700, margin:'8px 0 10px' }}>{T[lang].orderSummary}</div>
          <div style={{ background:'#fff', borderRadius:16, padding:'4px 14px', boxShadow:'inset 0 0 0 1px rgba(26,26,26,0.06)' }}>
            {cart.map(line=>{ const item=ITEMS.find(i=>i.id===line.itemId); if(!item) return null; return (
              <div key={line.key} style={{ display:'flex', alignItems:'center', gap:10, padding:'12px 0', borderBottom:'1px solid rgba(26,26,26,0.06)' }}>
                <span style={{ minWidth:24, fontWeight:800, fontSize:14, color:OLIVE, fontVariantNumeric:'tabular-nums' }}>{line.qty}×</span>
                <span style={{ flex:1, fontSize:14, color:INK, fontWeight:600 }}>{item[lang].n}</span>
                <span style={{ fontSize:14, color:INK, fontVariantNumeric:'tabular-nums', fontWeight:700 }}>{fmt(line.unitPrice*line.qty)}</span>
              </div>
            ); })}
            <div style={{ display:'flex', justifyContent:'space-between', padding:'12px 0' }}>
              <span style={{ fontWeight:700, fontSize:15, color:INK }}>{typeLabel}</span>
            </div>
          </div>

          {/* payment */}
          <div style={{ fontSize:11, color:'#999', textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:700, margin:'18px 0 10px' }}>{T[lang].payment}</div>
          <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
            {pays.map(p=>{ const on=pay===p.id; return (
              <Tap key={p.id} onClick={()=>setPay(p.id)} style={{ display:'flex', alignItems:'center', gap:12, padding:'14px', borderRadius:12, background:'#fff', border:'none', boxShadow:on?`inset 0 0 0 2px ${OLIVE}`:'inset 0 0 0 1px rgba(26,26,26,0.08)', cursor:'pointer' }}>
                <p.I size={20} color={on?OLIVE:'#777'} />
                <span style={{ flex:1, textAlign:'left', fontWeight:600, fontSize:15, color:INK }}>{p.label}{p.sub && <span style={{ color:'#999', fontWeight:500, marginLeft:8, fontVariantNumeric:'tabular-nums' }}>{p.sub}</span>}</span>
                <span style={{ width:20, height:20, borderRadius:999, border:on?`6px solid ${OLIVE}`:'2px solid rgba(26,26,26,0.25)', flex:'none' }} />
              </Tap>
            ); })}
          </div>

          {/* totals */}
          <div style={{ marginTop:18, padding:16, borderRadius:16, background:INK, color:CREAM, display:'flex', flexDirection:'column', gap:8 }}>
            <div style={{ display:'flex', justifyContent:'space-between', fontSize:14, color:'rgba(245,240,232,0.8)' }}><span>{T[lang].subtotal}</span><span style={{ fontVariantNumeric:'tabular-nums' }}>{fmt(subtotal)}</span></div>
            {orderType==='delivery' && <div style={{ display:'flex', justifyContent:'space-between', fontSize:14, color:'rgba(245,240,232,0.8)' }}><span>{T[lang].deliveryFee}</span><span style={{ color:GREEN, fontWeight:700 }}>{T[lang].free}</span></div>}
            <div style={{ display:'flex', justifyContent:'space-between', fontSize:14 }}><span style={{ color:'rgba(245,240,232,0.8)' }}>{T[lang].earn}</span><span style={{ color:GREEN, fontWeight:700, fontVariantNumeric:'tabular-nums' }}>+{earn} P</span></div>
            <div style={{ height:1, background:'rgba(255,255,255,0.14)', margin:'4px 0' }} />
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline' }}><span style={{ fontWeight:700, fontSize:16 }}>{T[lang].total}</span><span style={{ fontWeight:900, fontSize:24, color:GREEN, fontVariantNumeric:'tabular-nums', letterSpacing:'-0.015em' }}>{fmt(total)}</span></div>
          </div>
        </div>
      </div>
      <div style={{ position:'absolute', bottom:0, left:0, right:0, padding:'14px 16px calc(20px + env(safe-area-inset-bottom,0px))', background:'linear-gradient(to top, var(--avb-cream) 62%, rgba(245,240,232,0))' }}>
        <PrimaryButton full onClick={()=>onPlace(pay, total, earn)}><span>{T[lang].placeOrder}</span><span style={{ fontWeight:800, fontVariantNumeric:'tabular-nums', marginLeft:'auto' }}>{fmt(total)}</span></PrimaryButton>
      </div>
    </div>
  );
}

// ── Payment result ──
function PaymentResultScreen({ lang, ok, onTrack, onHome, onRetry }) {
  const [mounted, setMounted] = useState(false);
  useEffect(()=>{ const r=requestAnimationFrame(()=>setMounted(true)); return ()=>cancelAnimationFrame(r); },[]);
  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', padding:'40px 28px', textAlign:'center' }}>
      <div style={{ width:96, height:96, borderRadius:999, background:ok?GREEN:'#F9E1DC', display:'flex', alignItems:'center', justifyContent:'center', transform:mounted?'scale(1)':'scale(0.6)', opacity:mounted?1:0, transition:'transform 420ms var(--ease), opacity 300ms' }}>
        {ok ? <Icon.check size={44} color={INK} /> : <Icon.close size={44} color="#8A3224" />}
      </div>
      <div style={{ marginTop:24, fontWeight:900, fontSize:26, color:INK, letterSpacing:'-0.02em' }}>{ok?T[lang].paySuccess:T[lang].payFailed}</div>
      <div style={{ marginTop:8, fontSize:15, color:'#777', lineHeight:1.5, maxWidth:300 }}>{ok?T[lang].paySuccessDesc:T[lang].payFailedDesc}</div>
      {ok && <div style={{ marginTop:14, padding:'8px 16px', borderRadius:999, background:'#fff', boxShadow:'inset 0 0 0 1px rgba(26,26,26,0.08)', fontWeight:800, fontSize:14, color:INK, fontVariantNumeric:'tabular-nums' }}>{T[lang].orderNo} · AVB-02817</div>}
      <div style={{ marginTop:32, width:'100%', maxWidth:320, display:'flex', flexDirection:'column', gap:10 }}>
        {ok ? <>
          <PrimaryButton full onClick={onTrack}>{T[lang].trackOrder}</PrimaryButton>
          <GhostButton full onClick={onHome}>{T[lang].backHome}</GhostButton>
        </> : <>
          <PrimaryButton full onClick={onRetry}>{T[lang].tryAgain}</PrimaryButton>
          <GhostButton full onClick={onHome}>{T[lang].backHome}</GhostButton>
        </>}
      </div>
    </div>
  );
}

Object.assign(window.AvbX = window.AvbX || {}, { ScreenHeader, CartLine, CartScreen, TableSelectScreen, PickupTimeScreen, AddressScreen, ConfirmScreen, PaymentResultScreen });
})();
