// Orders, Wallet, Favorites, Profile, DietProfile, Login, BottomTabs — namespaced under window.AvbX
(function(){
const { useState, useEffect, useRef } = React;
const {
  INK, GREEN, OLIVE, CREAM,
  ITEMS, REWARDS, TOPUP_PACKAGES, POINTS_RATES, VENUE,
  T, Icon, Tap, DishImage, IconButton, PrimaryButton, SecondaryButton, GhostButton, Wordmark, useScrollY, fmt,
  ScreenHeader, MenuRow,
} = window.AvbX;

// ── Order tracker timeline ──
function OrderTracker({ step, lang, orderType }) {
  const base = orderType==='delivery'
    ? ['statusReceived','statusConfirmed','statusPreparing','statusOnway','statusDelivered']
    : ['statusReceived','statusConfirmed','statusPreparing','statusReady'];
  const times = ['14:02','14:03','~12 '+T[lang].min,'',''];
  return (
    <div style={{ background:'#fff', borderRadius:20, padding:'18px', boxShadow:'0 1px 0 rgba(0,0,0,0.04), 0 8px 24px rgba(40,40,30,0.06)' }}>
      {base.map((k,i)=>{ const done=i<step, now=i===step, last=i===base.length-1; return (
        <div key={k} style={{ display:'flex', gap:14, minHeight:44 }}>
          <div style={{ display:'flex', flexDirection:'column', alignItems:'center', width:22 }}>
            <div style={{ width:22, height:22, borderRadius:999, flex:'none', display:'flex', alignItems:'center', justifyContent:'center', background:done?OLIVE:now?GREEN:CREAM, boxShadow:now?'0 0 0 5px rgba(207,216,41,0.3)':(done?'none':'inset 0 0 0 1.5px rgba(26,26,26,0.15)'), transition:'all 300ms var(--ease)' }}>
              {done&&<Icon.check size={13} color={GREEN} />}{now&&<span style={{ width:8, height:8, borderRadius:999, background:INK }} />}
            </div>
            {!last && <div style={{ width:2, flex:1, background:done?OLIVE:'rgba(26,26,26,0.1)', margin:'2px 0' }} />}
          </div>
          <div style={{ flex:1, padding:'0 0 14px', display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
            <span style={{ fontWeight:now?800:done?600:500, color:now?INK:'#999', fontSize:15.5 }}>{T[lang][k]}</span>
            {times[i] && <span style={{ fontSize:12, color:'#999', fontVariantNumeric:'tabular-nums' }}>{times[i]}</span>}
          </div>
        </div>
      ); })}
    </div>
  );
}

function OrdersScreen({ lang, orders, step, orderType, onAdvance, onReorder, onBrowse }) {
  const ref=useRef(null); const y=useScrollY(ref); const scrolled=y>6;
  const hasActive = orders.length>0;
  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].yourOrders} scrolled={scrolled} />
        <div style={{ padding:'4px 18px 110px' }}>
          {!hasActive ? (
            <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.clock size={26} color="#999" /></div>
              <div style={{ marginTop:14, fontWeight:800, fontSize:19, color:INK }}>{lang==='tr'?'Aktif sipariş yok':'No active orders'}</div>
              <div style={{ marginTop:18 }}><SecondaryButton onClick={onBrowse}>{T[lang].browseMenu}</SecondaryButton></div>
            </div>
          ) : (<>
            <div style={{ fontSize:11, color:'#999', textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:700, margin:'8px 0 10px' }}>{T[lang].active}</div>
            <div style={{ background:GREEN, borderRadius:20, padding:'18px', color:INK, position:'relative', overflow:'hidden', marginBottom:14 }}>
              <div style={{ position:'absolute', right:-30, top:-30, width:140, height:140, borderRadius:999, background:'rgba(26,26,26,0.06)' }} />
              <div style={{ fontSize:11, textTransform:'uppercase', letterSpacing:'0.1em', fontWeight:700, opacity:0.65 }}>{T[lang].orderNo} · AVB-02817</div>
              <div style={{ fontWeight:900, fontSize:26, marginTop:6, letterSpacing:'-0.02em' }}>{step<3?T[lang].statusPreparing:(orderType==='delivery'?T[lang].statusOnway:T[lang].statusReady)}</div>
              <div style={{ fontSize:13.5, opacity:0.75, marginTop:2 }}>{typeLabel}{orderType==='dine_in'?' · '+T[lang].table+' 7':''}</div>
            </div>
            <OrderTracker step={step} lang={lang} orderType={orderType} />
            <div style={{ marginTop:12, display:'flex', gap:10 }}>
              <div style={{ flex:1 }}><GhostButton full onClick={onReorder}>{T[lang].reorder}</GhostButton></div>
              <div style={{ flex:1 }}><SecondaryButton full onClick={onAdvance}>{step<3?(lang==='tr'?'İlerlet':'Advance'):(lang==='tr'?'Yeni sipariş':'New order')}</SecondaryButton></div>
            </div>
          </>)}
        </div>
      </div>
    </div>
  );
}

// ── Wallet (prepaid balance + points/rewards coexist) ──
function TopUpSheet({ lang, onClose, onConfirm }) {
  const [mounted, setMounted] = useState(false);
  const [pkg, setPkg] = useState(TOPUP_PACKAGES[1]);
  const [custom, setCustom] = useState('');
  useEffect(()=>{ const r=requestAnimationFrame(()=>setMounted(true)); return ()=>cancelAnimationFrame(r); },[]);
  const close=()=>{ setMounted(false); setTimeout(onClose,280); };
  const customNum = parseInt(custom||'0',10);
  const amount = customNum>0 ? customNum : pkg.amount;
  const bonus = customNum>0 ? 0 : pkg.bonus;
  return (
    <div style={{ position:'absolute', inset:0, zIndex:120, display:'flex', flexDirection:'column', justifyContent:'flex-end' }}>
      <div onClick={close} style={{ position:'absolute', inset:0, background:'rgba(20,20,15,0.55)', opacity:mounted?1:0, transition:'opacity 280ms var(--ease)' }} />
      <div style={{ position:'relative', zIndex:2, background:CREAM, borderRadius:'24px 24px 0 0', display:'flex', flexDirection:'column', transform:mounted?'translateY(0)':'translateY(100%)', transition:'transform 340ms var(--ease)', boxShadow:'0 -12px 40px rgba(0,0,0,0.22)' }}>
        <div style={{ position:'relative', padding:'12px 14px 0', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <div style={{ position:'absolute', top:8, left:'50%', transform:'translateX(-50%)', width:40, height:5, borderRadius:999, background:'rgba(26,26,26,0.15)' }} />
          <div style={{ fontWeight:800, fontSize:18, color:INK, paddingLeft:4 }}>{T[lang].topUp}</div>
          <IconButton onClick={close} size={36}><Icon.close size={16} /></IconButton>
        </div>
        <div style={{ padding:'14px 18px 4px' }}>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10 }}>
            {TOPUP_PACKAGES.map(p=>{ const on=!customNum && pkg.amount===p.amount; return (
              <Tap key={p.amount} onClick={()=>{ setPkg(p); setCustom(''); }} style={{ position:'relative', padding:'16px 14px', borderRadius:16, 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', textAlign:'left' }}>
                <div style={{ fontWeight:900, fontSize:22, color:INK, letterSpacing:'-0.02em', fontVariantNumeric:'tabular-nums' }}>{fmt(p.amount)}</div>
                {p.bonus>0
                  ? <div style={{ marginTop:4, display:'inline-flex', alignItems:'center', gap:4, fontSize:11, fontWeight:800, color:'#3F6B2E', background:'#E6F2DD', padding:'3px 8px', borderRadius:999 }}>+{fmt(p.bonus)} {T[lang].bonusLabel}</div>
                  : <div style={{ marginTop:4, fontSize:12, color:'#999', fontWeight:600 }}>—</div>}
              </Tap>
            ); })}
          </div>
          <div style={{ marginTop:12 }}>
            <div style={{ fontSize:11, color:'#999', textTransform:'uppercase', letterSpacing:'0.06em', fontWeight:700, marginBottom:6 }}>{T[lang].customAmount}</div>
            <div style={{ display:'flex', alignItems:'center', gap:8, background:'#fff', borderRadius:12, padding:'12px 14px', boxShadow: customNum>0?`inset 0 0 0 2px ${OLIVE}`:'inset 0 0 0 1px rgba(26,26,26,0.08)' }}>
              <span style={{ fontWeight:800, fontSize:18, color:INK }}>₺</span>
              <input value={custom} onChange={e=>setCustom(e.target.value.replace(/[^0-9]/g,''))} inputMode="numeric" placeholder={T[lang].enterAmount} style={{ flex:1, border:'none', outline:'none', background:'transparent', fontFamily:'var(--font-body)', fontSize:16, fontWeight:700, color:INK, fontVariantNumeric:'tabular-nums' }} />
            </div>
          </div>
        </div>
        <div style={{ padding:'14px 18px calc(18px + env(safe-area-inset-bottom,0px))' }}>
          {bonus>0 && <div style={{ textAlign:'center', fontSize:13, color:'#3F6B2E', fontWeight:700, marginBottom:10 }}>{T[lang].willReceive}: {fmt(amount+bonus)} <span style={{ color:'#999', fontWeight:500 }}>({fmt(amount)} + {fmt(bonus)} {T[lang].bonusLabel})</span></div>}
          <PrimaryButton full disabled={amount<=0} onClick={()=>{ onConfirm(amount, bonus); close(); }}><span>{T[lang].confirmTopUp}</span><span style={{ fontWeight:800, fontVariantNumeric:'tabular-nums', marginLeft:'auto' }}>{fmt(amount)}</span></PrimaryButton>
        </div>
      </div>
    </div>
  );
}

function WalletScreen({ lang, balance, points, txns, autoReload, onTopUp, onRedeem, onToggleAuto, onShowQR }) {
  const ref=useRef(null); const y=useScrollY(ref); const scrolled=y>6;
  const [sheet, setSheet] = useState(false);
  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column' }}>
      <div ref={ref} style={{ flex:1, overflowY:'auto' }}>
        <ScreenHeader title={T[lang].wallet} scrolled={scrolled} />
        <div style={{ padding:'4px 18px 110px' }}>
          {/* BALANCE hero */}
          <div style={{ background:INK, color:CREAM, borderRadius:22, padding:'20px', position:'relative', overflow:'hidden' }}>
            <div style={{ position:'absolute', right:-40, bottom:-50, width:200, height:200, borderRadius:999, background:'radial-gradient(circle, rgba(207,216,41,0.2) 0%, rgba(207,216,41,0) 70%)' }} />
            <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
              <div style={{ fontSize:11, textTransform:'uppercase', letterSpacing:'0.1em', color:GREEN, fontWeight:700 }}>{T[lang].avkWallet}</div>
              <span style={{ display:'inline-flex', alignItems:'center', gap:5, background:'rgba(207,216,41,0.16)', color:GREEN, padding:'5px 10px', borderRadius:999, fontWeight:800, fontSize:12, fontVariantNumeric:'tabular-nums' }}><Icon.sparkle size={12} color={GREEN} />{points} P</span>
            </div>
            <div style={{ fontSize:12, color:'rgba(245,240,232,0.6)', marginTop:14, fontWeight:600, textTransform:'uppercase', letterSpacing:'0.06em' }}>{T[lang].balance}</div>
            <div style={{ display:'flex', alignItems:'baseline', marginTop:2 }}>
              <span style={{ fontWeight:900, fontSize:46, color:CREAM, lineHeight:0.9, fontVariantNumeric:'tabular-nums', letterSpacing:'-0.03em' }}>{fmt(balance)}</span>
            </div>
            <div style={{ display:'flex', gap:10, marginTop:18 }}>
              <Tap onClick={()=>setSheet(true)} style={{ flex:1, background:GREEN, color:INK, border:'none', borderRadius:12, padding:'13px', fontWeight:800, fontSize:14, cursor:'pointer', display:'inline-flex', alignItems:'center', justifyContent:'center', gap:6 }}><Icon.plus size={16} color={INK} />{T[lang].topUpShort}</Tap>
              <Tap onClick={onShowQR} style={{ flex:1, background:'rgba(255,255,255,0.12)', color:CREAM, border:'none', borderRadius:12, padding:'13px', fontWeight:800, fontSize:14, cursor:'pointer', display:'inline-flex', alignItems:'center', justifyContent:'center', gap:6 }}><Icon.qr size={16} color={CREAM} />{T[lang].payQr}</Tap>
            </div>
          </div>

          {/* quick top-up packages */}
          <div style={{ fontSize:11, color:'#999', textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:700, margin:'20px 0 10px' }}>{T[lang].quickTopUp}</div>
          <div className="avb-noscroll" style={{ display:'flex', gap:10, overflowX:'auto', paddingBottom:2 }}>
            {TOPUP_PACKAGES.map(p=>(
              <Tap key={p.amount} onClick={()=>onTopUp(p.amount, p.bonus)} style={{ flex:'none', minWidth:120, padding:'14px', borderRadius:16, background:'#fff', border:'none', boxShadow:'inset 0 0 0 1px rgba(26,26,26,0.08)', cursor:'pointer', textAlign:'left' }}>
                <div style={{ fontWeight:900, fontSize:20, color:INK, letterSpacing:'-0.02em', fontVariantNumeric:'tabular-nums' }}>{fmt(p.amount)}</div>
                {p.bonus>0
                  ? <div style={{ marginTop:6, display:'inline-flex', fontSize:11, fontWeight:800, color:'#3F6B2E', background:'#E6F2DD', padding:'3px 8px', borderRadius:999 }}>+{fmt(p.bonus)}</div>
                  : <div style={{ marginTop:6, fontSize:11, color:'#B3B3B3', fontWeight:600 }}>&nbsp;</div>}
              </Tap>
            ))}
          </div>

          {/* auto reload */}
          <Tap onClick={onToggleAuto} style={{ width:'100%', marginTop:14, display:'flex', alignItems:'center', gap:12, padding:'14px 16px', borderRadius:16, background:'#fff', border:'none', boxShadow:'inset 0 0 0 1px rgba(26,26,26,0.06)', cursor:'pointer' }}>
            <Icon.sparkle size={18} color={OLIVE} />
            <span style={{ flex:1, textAlign:'left' }}>
              <span style={{ display:'block', fontWeight:700, fontSize:14, color:INK }}>{T[lang].autoReload}</span>
              <span style={{ display:'block', fontSize:12, color:'#999', marginTop:2 }}>{T[lang].autoReloadDesc}</span>
            </span>
            <span style={{ width:46, height:28, borderRadius:999, background:autoReload?OLIVE:'rgba(26,26,26,0.12)', position:'relative', transition:'background 200ms', flex:'none' }}>
              <span style={{ position:'absolute', top:3, left:autoReload?21:3, width:22, height:22, borderRadius:999, background:'#fff', transition:'left 200ms var(--ease)', boxShadow:'0 1px 3px rgba(0,0,0,0.2)' }} />
            </span>
          </Tap>

          {/* POINTS-ONLY rewards */}
          <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', margin:'22px 0 12px' }}>
            <span style={{ fontSize:11, color:'#999', textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:700 }}>{T[lang].rewards}</span>
            <span style={{ fontSize:12, color:OLIVE, fontWeight:700, fontVariantNumeric:'tabular-nums' }}>{points} P {T[lang].available}</span>
          </div>
          <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
            {REWARDS.map(r=>{ const unlocked=points>=r.cost; return (
              <div key={r.id} style={{ display:'flex', alignItems:'center', gap:12, padding:12, borderRadius:16, background:'#fff', boxShadow:'inset 0 0 0 1px rgba(26,26,26,0.06)', opacity:unlocked?1:0.72 }}>
                <DishImage photo={r.photo} tone={r.tone} radius={12} style={{ width:56, height:56, filter:unlocked?'none':'grayscale(0.5)' }} />
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontWeight:700, fontSize:15, color:INK }}>{r[lang]}</div>
                  <div style={{ display:'inline-flex', alignItems:'center', gap:4, fontSize:13, color:OLIVE, fontWeight:700, fontVariantNumeric:'tabular-nums', marginTop:2 }}><Icon.sparkle size={12} color={OLIVE} />{r.cost} P</div>
                </div>
                {unlocked
                  ? <SecondaryButton small onClick={()=>onRedeem(r)}>{T[lang].redeem}</SecondaryButton>
                  : <span style={{ fontSize:12, color:'#999', fontWeight:700, fontVariantNumeric:'tabular-nums' }}>{r.cost-points} P</span>}
              </div>
            ); })}
          </div>

          {/* transactions */}
          <div style={{ fontSize:11, color:'#999', textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:700, margin:'22px 0 10px' }}>{T[lang].transactions}</div>
          <div style={{ background:'#fff', borderRadius:16, overflow:'hidden', boxShadow:'inset 0 0 0 1px rgba(26,26,26,0.06)' }}>
            {txns.map((t,i)=>(
              <div key={i} style={{ display:'flex', alignItems:'center', gap:12, padding:'13px 14px', borderBottom:i<txns.length-1?'1px solid rgba(26,26,26,0.06)':'none' }}>
                <span style={{ width:34, height:34, borderRadius:999, background:t.amount>0?'#E6F2DD':'rgba(26,26,26,0.05)', display:'inline-flex', alignItems:'center', justifyContent:'center', flex:'none' }}>{t.amount>0?<Icon.plus size={15} color="#3F6B2E" />:<Icon.bag size={15} color="#777" />}</span>
                <span style={{ flex:1, minWidth:0 }}>
                  <span style={{ display:'block', fontWeight:600, fontSize:14, color:INK }}>{t.amount>0?T[lang].topUpTxn:t.label}</span>
                  <span style={{ display:'block', fontSize:12, color:'#999' }}>{t.date}</span>
                </span>
                <span style={{ fontWeight:800, fontSize:15, color:t.amount>0?'#3F6B2E':INK, fontVariantNumeric:'tabular-nums' }}>{t.amount>0?'+':''}{fmt(Math.abs(t.amount))}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
      {sheet && <TopUpSheet lang={lang} onClose={()=>setSheet(false)} onConfirm={onTopUp} />}
    </div>
  );
}

// ── Favorites ──
function FavoritesScreen({ lang, favs, cart, onAddQuick, onOpen, onBrowse }) {
  const ref=useRef(null); const y=useScrollY(ref); const scrolled=y>6;
  const list = ITEMS.filter(it=>favs[it.id]);
  const qtyOf=(id)=>cart.filter(c=>c.itemId===id).reduce((a,c)=>a+c.qty,0);
  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column' }}>
      <div ref={ref} style={{ flex:1, overflowY:'auto' }}>
        <ScreenHeader title={T[lang].favorites} scrolled={scrolled} />
        <div style={{ padding:'4px 18px 110px' }}>
          {list.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.heart size={26} color="#999" /></div>
              <div style={{ marginTop:14, fontWeight:800, fontSize:19, color:INK }}>{lang==='tr'?'Henüz favori yok':'No favourites yet'}</div>
              <div style={{ marginTop:4, fontSize:14, color:'#999' }}>{lang==='tr'?'Beğendiğin tabakları kalp ile işaretle.':'Tap the heart on dishes you love.'}</div>
              <div style={{ marginTop:18 }}><SecondaryButton onClick={onBrowse}>{T[lang].browseMenu}</SecondaryButton></div>
            </div>
          ) : list.map(it=><MenuRow key={it.id} item={it} qty={qtyOf(it.id)} lang={lang} onAdd={onAddQuick} onOpen={()=>onOpen(it)} />)}
        </div>
      </div>
    </div>
  );
}

// ── Profile ──
function ProfileScreen({ lang, points, balance, onNav, onToggleLang, user }) {
  const ref=useRef(null); const y=useScrollY(ref); const scrolled=y>6;
  const rows = [
    { k:'favorites', label:T[lang].favorites, I:Icon.heart },
    { k:'myAddresses', label:T[lang].myAddresses, I:Icon.pin },
    { k:'orderHistory', label:T[lang].orderHistory, I:Icon.clock },
    { k:'dietProfile', label:T[lang].dietProfile, I:Icon.leaf },
    { k:'about', label:T[lang].about, I:Icon.note },
  ];
  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column' }}>
      <div ref={ref} style={{ flex:1, overflowY:'auto' }}>
        <ScreenHeader title={T[lang].profile} scrolled={scrolled} />
        <div style={{ padding:'4px 18px 110px', display:'flex', flexDirection:'column', gap:14 }}>
          <div style={{ background:'#fff', borderRadius:20, padding:16, display:'flex', alignItems:'center', gap:14, boxShadow:'inset 0 0 0 1px rgba(26,26,26,0.06)' }}>
            <div style={{ width:54, height:54, borderRadius:999, background:GREEN, color:INK, display:'flex', alignItems:'center', justifyContent:'center', fontWeight:900, fontSize:20 }}>{user.initials}</div>
            <div style={{ flex:1 }}>
              <div style={{ fontWeight:700, color:INK, fontSize:17 }}>{user.name}</div>
              <div style={{ fontSize:13, color:'#999', fontVariantNumeric:'tabular-nums' }}>{user.phone}</div>
            </div>
            <span style={{ display:'flex', flexDirection:'column', alignItems:'flex-end', gap:5 }}>
              <span style={{ display:'inline-flex', alignItems:'center', gap:5, background:INK, color:CREAM, padding:'7px 12px', borderRadius:999, fontWeight:800, fontSize:14, fontVariantNumeric:'tabular-nums' }}>{fmt(balance)}</span>
              <span style={{ display:'inline-flex', alignItems:'center', gap:4, color:OLIVE, fontWeight:800, fontSize:12, fontVariantNumeric:'tabular-nums' }}><Icon.sparkle size={12} color={OLIVE} />{points} P</span>
            </span>
          </div>

          <div style={{ background:'#fff', borderRadius:20, overflow:'hidden', boxShadow:'inset 0 0 0 1px rgba(26,26,26,0.06)' }}>
            {rows.map((r,i)=>(
              <Tap key={r.k} onClick={()=>onNav(r.k)} style={{ display:'flex', alignItems:'center', gap:12, width:'100%', padding:'14px 16px', background:'transparent', border:'none', borderBottom:i<rows.length-1?'1px solid rgba(26,26,26,0.06)':'none', cursor:'pointer', fontFamily:'var(--font-body)' }}>
                <r.I size={19} color={OLIVE} />
                <span style={{ flex:1, textAlign:'left', color:INK, fontSize:15, fontWeight:500 }}>{r.label}</span>
                <Icon.chevron size={14} color="rgba(26,26,26,0.3)" />
              </Tap>
            ))}
          </div>

          <div style={{ background:'#fff', borderRadius:20, overflow:'hidden', boxShadow:'inset 0 0 0 1px rgba(26,26,26,0.06)' }}>
            <Tap onClick={onToggleLang} style={{ display:'flex', alignItems:'center', gap:12, width:'100%', padding:'14px 16px', background:'transparent', border:'none', cursor:'pointer', fontFamily:'var(--font-body)' }}>
              <span style={{ flex:1, textAlign:'left', color:INK, fontSize:15, fontWeight:500 }}>{T[lang].language}</span>
              <span style={{ fontSize:14, color:OLIVE, fontWeight:700 }}>{lang==='tr'?'Türkçe':'English'}</span>
              <Icon.chevron size={14} color="rgba(26,26,26,0.3)" />
            </Tap>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Diet profile ──
function DietProfileScreen({ lang, onBack, diet, onToggle }) {
  const opts = [['vegan',T[lang].vegan,Icon.leaf],['vegetarian',T[lang].vegetarian,Icon.leaf],['glutenFree',T[lang].glutenFree,Icon.wheat],['dairyFree',T[lang].dairyFree,Icon.sparkle]];
  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column' }}>
      <ScreenHeader title={T[lang].dietProfile} onBack={onBack} scrolled />
      <div style={{ flex:1, overflowY:'auto', padding:'10px 18px 40px' }}>
        <div style={{ fontSize:14, color:'#999', lineHeight:1.5, marginBottom:16 }}>{T[lang].dietHint}</div>
        <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
          {opts.map(([k,label,I])=>{ const on=diet[k]; return (
            <Tap key={k} onClick={()=>onToggle(k)} style={{ display:'flex', alignItems:'center', gap:12, padding:'16px', borderRadius:14, background:'#fff', border:'none', boxShadow:'inset 0 0 0 1px rgba(26,26,26,0.08)', cursor:'pointer' }}>
              <I size={20} color={on?OLIVE:'#999'} />
              <span style={{ flex:1, textAlign:'left', fontWeight:700, fontSize:16, color:INK }}>{label}</span>
              <span style={{ width:46, height:28, borderRadius:999, background:on?OLIVE:'rgba(26,26,26,0.12)', position:'relative', transition:'background 200ms', flex:'none' }}>
                <span style={{ position:'absolute', top:3, left:on?21:3, width:22, height:22, borderRadius:999, background:'#fff', transition:'left 200ms var(--ease)', boxShadow:'0 1px 3px rgba(0,0,0,0.2)' }} />
              </span>
            </Tap>
          ); })}
        </div>
      </div>
    </div>
  );
}

// ── Login ──
// Country dial codes + digit grouping masks (no flag emoji — ISO + dial code text only).
const COUNTRIES = [
  { iso:'TR', dial:'+90',  groups:[3,3,2,2], name:{tr:'Türkiye', en:'Turkey'} },
  { iso:'GB', dial:'+44',  groups:[4,6],     name:{tr:'Birleşik Krallık', en:'United Kingdom'} },
  { iso:'DE', dial:'+49',  groups:[3,4,4],   name:{tr:'Almanya', en:'Germany'} },
  { iso:'NL', dial:'+31',  groups:[1,8],     name:{tr:'Hollanda', en:'Netherlands'} },
  { iso:'FR', dial:'+33',  groups:[1,2,2,2,2],name:{tr:'Fransa', en:'France'} },
  { iso:'US', dial:'+1',   groups:[3,3,4],   name:{tr:'ABD', en:'United States'} },
  { iso:'AE', dial:'+971', groups:[2,3,4],   name:{tr:'BAE', en:'UAE'} },
  { iso:'SA', dial:'+966', groups:[2,3,4],   name:{tr:'S. Arabistan', en:'Saudi Arabia'} },
  { iso:'RU', dial:'+7',   groups:[3,3,2,2], name:{tr:'Rusya', en:'Russia'} },
];
function formatPhone(digits, groups) {
  const max = groups.reduce((a,b)=>a+b,0);
  const d = digits.replace(/\D/g,'').slice(0, max);
  const out = []; let i = 0;
  for (const g of groups) { if (i>=d.length) break; out.push(d.slice(i, i+g)); i+=g; }
  return out.join(' ');
}

function LoginScreen({ lang, onLogin, onGuest, onToggleLang }) {
  const [stage, setStage] = useState('phone');
  const [country, setCountry] = useState(COUNTRIES[0]);
  const [pickerOpen, setPickerOpen] = useState(false);
  const [phone, setPhone] = useState('');   // raw digits only
  const [code, setCode] = useState('');
  const maxDigits = country.groups.reduce((a,b)=>a+b,0);
  const phoneComplete = phone.length === maxDigits;
  const onPhoneChange = (e) => setPhone(e.target.value.replace(/\D/g,'').slice(0, maxDigits));
  const placeholder = formatPhone('5'.repeat(maxDigits), country.groups).replace(/5/g,'X');
  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column', position:'relative' }}>
      <DishImage photo={VENUE.interior} tone="green" radius={0} style={{ position:'absolute', inset:0 }} />
      <div style={{ position:'absolute', inset:0, background:'linear-gradient(180deg, rgba(20,20,15,0.2) 0%, rgba(20,20,15,0.75) 65%, rgba(20,20,15,0.92) 100%)' }} />
      <div style={{ position:'absolute', top:54, right:18, zIndex:5 }}>
        <Tap onClick={onToggleLang} style={{ background:'rgba(255,255,255,0.18)', border:'none', color:'#fff', padding:'8px 14px', borderRadius:999, fontWeight:700, fontSize:13, cursor:'pointer', backdropFilter:'blur(8px)' }}>{lang==='tr'?'EN':'TR'}</Tap>
      </div>
      <div style={{ position:'relative', zIndex:2, marginTop:'auto', padding:'0 24px calc(36px + env(safe-area-inset-bottom,0px))' }}>
        <Wordmark color="#fff" size={1.3} />
        <div style={{ fontWeight:900, fontSize:38, color:'#fff', letterSpacing:'-0.03em', lineHeight:1.0, marginTop:16 }}>{T[lang].loginTagline}</div>
        <div style={{ marginTop:24 }}>
          {stage==='phone' ? (<>
            <div style={{ fontSize:12, fontWeight:700, color:'rgba(255,255,255,0.7)', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:8 }}>{T[lang].phoneLabel}</div>
            <div style={{ position:'relative' }}>
              <div style={{ display:'flex', gap:8 }}>
                {/* country selector */}
                <Tap onClick={()=>setPickerOpen(o=>!o)} style={{ flex:'none', display:'inline-flex', alignItems:'center', gap:7, background:'rgba(255,255,255,0.95)', border:'none', borderRadius:14, padding:'0 12px', height:52, cursor:'pointer' }}>
                  <span style={{ fontWeight:800, fontSize:14, color:INK }}>{country.iso}</span>
                  <span style={{ fontWeight:700, fontSize:15, color:'#777', fontVariantNumeric:'tabular-nums' }}>{country.dial}</span>
                  <span style={{ transform:pickerOpen?'rotate(-90deg)':'rotate(90deg)', transition:'transform 180ms var(--ease)', lineHeight:0 }}><Icon.chevron size={14} color="#999" /></span>
                </Tap>
                {/* number input */}
                <input value={formatPhone(phone, country.groups)} onChange={onPhoneChange} placeholder={placeholder} inputMode="tel" style={{ flex:1, minWidth:0, border:'none', outline:'none', background:'rgba(255,255,255,0.95)', borderRadius:14, padding:'15px 16px', fontFamily:'var(--font-body)', fontSize:16, color:INK, fontVariantNumeric:'tabular-nums', letterSpacing:'0.02em' }} />
              </div>
              {/* dropdown */}
              {pickerOpen && (
                <div style={{ position:'absolute', bottom:'calc(100% + 8px)', left:0, right:0, background:'#fff', borderRadius:16, boxShadow:'0 20px 50px rgba(0,0,0,0.35)', overflow:'hidden', maxHeight:260, overflowY:'auto', zIndex:10 }}>
                  {COUNTRIES.map(c=>{ const on=c.iso===country.iso; return (
                    <Tap key={c.iso} onClick={()=>{ setCountry(c); setPhone(''); setPickerOpen(false); }} style={{ display:'flex', alignItems:'center', gap:10, width:'100%', padding:'13px 16px', background:on?'rgba(207,216,41,0.16)':'transparent', border:'none', borderBottom:'1px solid rgba(26,26,26,0.06)', cursor:'pointer', fontFamily:'var(--font-body)' }}>
                      <span style={{ fontWeight:800, fontSize:14, color:INK, width:28 }}>{c.iso}</span>
                      <span style={{ flex:1, textAlign:'left', fontSize:14, color:'#555' }}>{c.name[lang]}</span>
                      <span style={{ fontWeight:700, fontSize:14, color:'#999', fontVariantNumeric:'tabular-nums' }}>{c.dial}</span>
                      {on && <Icon.check size={15} color={OLIVE} />}
                    </Tap>
                  ); })}
                </div>
              )}
            </div>
            <div style={{ marginTop:12 }}><PrimaryButton full disabled={!phoneComplete} onClick={()=>setStage('code')}>{T[lang].sendCode}</PrimaryButton></div>
          </>) : (<>
            <div style={{ fontSize:12, fontWeight:700, color:'rgba(255,255,255,0.7)', textTransform:'uppercase', letterSpacing:'0.06em', marginBottom:8 }}>{T[lang].enterCode}</div>
            <div style={{ fontSize:13, color:'rgba(255,255,255,0.85)', marginBottom:10 }}>{T[lang].codeSentTo} {country.dial} {formatPhone(phone, country.groups)}</div>
            <input value={code} onChange={e=>setCode(e.target.value.replace(/\D/g,'').slice(0,4))} placeholder="• • • •" inputMode="numeric" style={{ width:'100%', border:'none', outline:'none', background:'rgba(255,255,255,0.95)', borderRadius:14, padding:'15px 16px', fontFamily:'var(--font-body)', fontSize:22, color:INK, fontWeight:800, letterSpacing:'0.5em', textAlign:'center', fontVariantNumeric:'tabular-nums' }} />
            <div style={{ marginTop:12 }}><PrimaryButton full disabled={code.length<4} onClick={onLogin}>{T[lang].verify}</PrimaryButton></div>
            <div style={{ textAlign:'center', marginTop:12 }}><button onClick={()=>setStage('phone')} style={{ background:'none', border:'none', color:'rgba(255,255,255,0.7)', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'var(--font-body)' }}>{T[lang].resend}</button></div>
          </>)}
          <div style={{ textAlign:'center', marginTop:16 }}>
            <button onClick={onGuest} style={{ background:'none', border:'none', color:'#fff', fontSize:14, fontWeight:700, cursor:'pointer', fontFamily:'var(--font-body)', textDecoration:'underline', textUnderlineOffset:3, opacity:0.9 }}>{T[lang].continueGuest}</button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Bottom tabs ──
function BottomTabs({ active, onChange, cartCount, lang }) {
  const tabs = [
    { k:'menu', label:T[lang].menu, I:Icon.home },
    { k:'orders', label:T[lang].orders, I:Icon.clock },
    { k:'wallet', label:T[lang].wallet, I:Icon.gift },
    { k:'cart', label:T[lang].cart, I:Icon.bag },
    { k:'profile', label:T[lang].profile, I:Icon.user },
  ];
  return (
    <div style={{ position:'relative', zIndex:40, background:'rgba(245,240,232,0.92)', backdropFilter:'blur(14px) saturate(160%)', WebkitBackdropFilter:'blur(14px) saturate(160%)', borderTop:'1px solid rgba(26,26,26,0.08)', display:'flex', padding:'8px 4px 14px' }}>
      {tabs.map(t=>{ const on=active===t.k; return (
        <Tap key={t.k} onClick={()=>onChange(t.k)} style={{ flex:1, border:'none', background:'transparent', padding:'6px 4px', display:'flex', flexDirection:'column', alignItems:'center', gap:3, cursor:'pointer', position:'relative' }}>
          <span style={{ position:'relative', lineHeight:0 }}>
            <t.I size={22} color={on?INK:'#999'} />
            {t.k==='cart' && cartCount>0 && <span style={{ position:'absolute', top:-5, right:-9, minWidth:16, height:16, padding:'0 4px', background:OLIVE, color:GREEN, borderRadius:999, fontSize:10, fontWeight:800, display:'inline-flex', alignItems:'center', justifyContent:'center', border:'2px solid '+CREAM, fontVariantNumeric:'tabular-nums' }}>{cartCount}</span>}
          </span>
          <span style={{ fontSize:10, letterSpacing:'0.01em', fontWeight:on?700:500, color:on?INK:'#999' }}>{t.label}</span>
        </Tap>
      ); })}
    </div>
  );
}

Object.assign(window.AvbX = window.AvbX || {}, { OrderTracker, OrdersScreen, WalletScreen, TopUpSheet, FavoritesScreen, ProfileScreen, DietProfileScreen, LoginScreen, BottomTabs, COUNTRIES, formatPhone });
})();
