// Combos hub + Build-your-menu wizard + Wallet QR — namespaced under window.AvbX
(function(){
const { useState, useRef } = React;
const {
  INK, GREEN, OLIVE, CREAM,
  ITEMS, COMBOS, COMBO_TAGS, MOODS,
  T, Icon, Tap, DishImage, IconButton, useScrollY, fmt,
  ScreenHeader,
} = window.AvbX;

// faux-but-deterministic QR pattern (no external lib, no emoji)
function FauxQR({ seed='AVK-83812', size=180 }) {
  const n = 21; // modules
  const cell = size / n;
  // deterministic pseudo-random from seed
  let h = 0; for (let i=0;i<seed.length;i++) h = (h*31 + seed.charCodeAt(i)) >>> 0;
  const rng = () => { h = (h*1103515245 + 12345) & 0x7fffffff; return h / 0x7fffffff; };
  const rects = [];
  for (let y=0;y<n;y++) for (let x=0;x<n;x++) {
    const finder = (x<7&&y<7)||(x>=n-7&&y<7)||(x<7&&y>=n-7);
    if (finder) continue;
    if (rng() > 0.52) rects.push(<rect key={x+'-'+y} x={x*cell} y={y*cell} width={cell} height={cell} rx={cell*0.18} fill={INK} />);
  }
  const finder = (fx, fy) => (<g>
    <rect x={fx*cell} y={fy*cell} width={cell*7} height={cell*7} rx={cell*1.6} fill="none" stroke={INK} strokeWidth={cell*0.9} />
    <rect x={(fx+2)*cell} y={(fy+2)*cell} width={cell*3} height={cell*3} rx={cell*0.9} fill={INK} />
  </g>);
  return (
    <svg viewBox={`0 0 ${size} ${size}`} width={size} height={size} style={{ display:'block' }}>
      <rect x="0" y="0" width={size} height={size} fill="#fff" />
      {rects}
      {finder(0,0)}{finder(n-7,0)}{finder(0,n-7)}
    </svg>
  );
}

// ── Build-your-menu: 3 steps (count → mood → combos) ──
function BuildMenuScreen({ lang, onBack, onAddCombo, onOpenCombo }) {
  const [step, setStep] = useState(0);
  const [count, setCount] = useState(null);
  const [mood, setMood] = useState(null);
  const suggested = COMBOS.filter(c => !mood || c.mood === mood);

  const stepTitle = [T[lang].howMany, T[lang].mood, T[lang].perfectCombos][step];
  const stepDesc = [T[lang].howManyDesc, T[lang].moodDesc, ''][step];

  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column' }}>
      <ScreenHeader title={T[lang].buildMenu} onBack={step===0?onBack:()=>setStep(s=>s-1)} scrolled />
      <div style={{ flex:1, overflowY:'auto', padding:'8px 18px 120px' }}>
        {/* progress dots */}
        <div style={{ display:'flex', gap:6, marginBottom:18 }}>
          {[0,1,2].map(i=>(<div key={i} style={{ flex:1, height:4, borderRadius:999, background:i<=step?OLIVE:'rgba(26,26,26,0.12)', transition:'background 240ms var(--ease)' }} />))}
        </div>
        <div style={{ fontWeight:800, fontSize:24, color:INK, letterSpacing:'-0.02em', lineHeight:1.1 }}>{stepTitle}</div>
        {stepDesc && <div style={{ fontSize:14.5, color:'#999', marginTop:6 }}>{stepDesc}</div>}

        {step===0 && (
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:10, marginTop:20 }}>
            {[1,2,3,4].map(nn=>{ const on=count===nn; return (
              <Tap key={nn} onClick={()=>{ setCount(nn); setStep(1); }} style={{ aspectRatio:'1.5', 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:2 }}>
                <span style={{ fontWeight:900, fontSize:30, color:INK, letterSpacing:'-0.02em' }}>{nn}{nn===4?'+':''}</span>
                <span style={{ fontSize:12, color:on?'rgba(26,26,26,0.6)':'#999', fontWeight:600 }}>{nn===1?T[lang].person:T[lang].people}</span>
              </Tap>
            ); })}
          </div>
        )}

        {step===1 && (
          <div style={{ display:'flex', flexDirection:'column', gap:10, marginTop:20 }}>
            {MOODS.map(m=>{ const on=mood===m.id; return (
              <Tap key={m.id} onClick={()=>{ setMood(m.id); setStep(2); }} style={{ display:'flex', alignItems:'center', gap:14, padding:'16px', 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' }}>
                <span style={{ flex:1 }}>
                  <span style={{ display:'block', fontWeight:700, fontSize:16, color:INK }}>{m[lang].n}</span>
                  <span style={{ display:'block', fontSize:13, color:'#999', marginTop:2 }}>{m[lang].d}</span>
                </span>
                <Icon.chevron size={16} color="#bbb" />
              </Tap>
            ); })}
          </div>
        )}

        {step===2 && (
          <div style={{ display:'flex', flexDirection:'column', gap:14, marginTop:18 }}>
            {suggested.map(c=><ComboCard key={c.id} combo={c} lang={lang} onAdd={onAddCombo} onOpen={()=>onOpenCombo(c)} />)}
            <Tap onClick={()=>{ setStep(0); setCount(null); setMood(null); }} style={{ alignSelf:'center', marginTop:6, background:'transparent', border:'none', color:OLIVE, fontWeight:700, fontSize:14, cursor:'pointer', fontFamily:'var(--font-body)', textDecoration:'underline', textUnderlineOffset:3 }}>{T[lang].startOver}</Tap>
          </div>
        )}
      </div>
    </div>
  );
}

// ── Combo card ──
function ComboCard({ combo, lang, onAdd, onOpen }) {
  const L = combo[lang];
  const photo = (combo.items.map(id=>ITEMS.find(i=>i.id===id)).find(it=>it&&it.photo)||{}).photo || null;
  const tone = (ITEMS.find(i=>i.id===combo.items[0])||{}).tone || 'green';
  const tag = combo.tag ? COMBO_TAGS[combo.tag] : null;
  return (
    <div onClick={onOpen} style={{ background:'#fff', borderRadius:20, overflow:'hidden', boxShadow:'0 1px 0 rgba(0,0,0,0.04), 0 8px 24px rgba(40,40,30,0.06)', cursor:'pointer' }}>
      <div style={{ position:'relative' }}>
        <DishImage photo={photo} tone={tone} radius={0} style={{ width:'100%', height:130 }} />
        {tag && <span style={{ position:'absolute', top:12, left:12, background:INK, color:GREEN, padding:'5px 11px', borderRadius:999, fontSize:11, fontWeight:800, letterSpacing:'0.02em' }}>{tag[lang]}</span>}
      </div>
      <div style={{ padding:'14px 16px' }}>
        <div style={{ fontWeight:800, fontSize:17, color:INK, letterSpacing:'-0.015em' }}>{L.n}</div>
        <div style={{ fontSize:13, color:'#999', marginTop:3 }}>{L.d}</div>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginTop:12 }}>
          <span style={{ fontWeight:900, fontSize:19, color:INK, fontVariantNumeric:'tabular-nums', letterSpacing:'-0.01em' }}>{fmt(combo.price)}</span>
          <Tap onClick={(e)=>{ e.stopPropagation(); onAdd(combo); }} style={{ background:OLIVE, color:GREEN, border:'none', borderRadius:12, padding:'10px 16px', fontWeight:700, fontSize:13, cursor:'pointer', display:'inline-flex', alignItems:'center', gap:6, fontFamily:'var(--font-body)' }}><Icon.plus size={15} color={GREEN} />{T[lang].addCombo}</Tap>
        </div>
      </div>
    </div>
  );
}

// ── Combos hub (preset list + entry to builder) ──
function CombosScreen({ lang, onBack, onBuild, onAddCombo, onOpenCombo }) {
  const ref=useRef(null); const y=useScrollY(ref); const scrolled=y>6;
  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column' }}>
      <div ref={ref} style={{ flex:1, overflowY:'auto' }}>
        <ScreenHeader title={T[lang].combos} onBack={onBack} scrolled={scrolled} />
        <div style={{ padding:'4px 18px 110px' }}>
          {/* build-your-menu entry */}
          <Tap onClick={onBuild} style={{ width:'100%', background:INK, color:CREAM, borderRadius:20, padding:'18px', border:'none', cursor:'pointer', display:'flex', alignItems:'center', gap:14, textAlign:'left', position:'relative', overflow:'hidden' }}>
            <div style={{ position:'absolute', right:-30, top:-30, width:120, height:120, borderRadius:999, background:'radial-gradient(circle, rgba(207,216,41,0.2) 0%, rgba(207,216,41,0) 70%)' }} />
            <span style={{ width:46, height:46, borderRadius:14, background:GREEN, display:'inline-flex', alignItems:'center', justifyContent:'center', flex:'none' }}><Icon.sparkle size={22} color={INK} /></span>
            <span style={{ flex:1 }}>
              <span style={{ display:'block', fontWeight:800, fontSize:18, color:GREEN, letterSpacing:'-0.01em' }}>{T[lang].buildMenu}</span>
              <span style={{ display:'block', fontSize:13, color:'rgba(245,240,232,0.75)', marginTop:2 }}>{T[lang].moodDesc}</span>
            </span>
            <Icon.chevron size={18} color={CREAM} />
          </Tap>

          <div style={{ display:'flex', flexDirection:'column', gap:14, marginTop:18 }}>
            {COMBOS.map(c=><ComboCard key={c.id} combo={c} lang={lang} onAdd={onAddCombo} onOpen={()=>onOpenCombo(c)} />)}
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Wallet QR — full screen "show to waiter" ──
function WalletQRScreen({ lang, points, customerNo, onClose }) {
  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column', background:INK, position:'relative' }}>
      <div style={{ position:'absolute', top:0, left:0, right:0, height:54, zIndex:2 }} />
      <div style={{ position:'relative', zIndex:3, paddingTop:50, display:'flex', justifyContent:'flex-end', padding:'50px 16px 0' }}>
        <IconButton onClick={onClose} size={38} style={{ background:'rgba(255,255,255,0.12)', boxShadow:'none' }}><Icon.close size={18} color={CREAM} /></IconButton>
      </div>
      <div style={{ flex:1, overflowY:'auto', padding:'8px 24px 30px', display:'flex', flexDirection:'column', alignItems:'center' }}>
        <div style={{ fontSize:11, textTransform:'uppercase', letterSpacing:'0.18em', color:GREEN, fontWeight:800 }}>{T[lang].avkWallet}</div>
        <div style={{ marginTop:6, color:'rgba(245,240,232,0.7)', fontSize:13 }}>{T[lang].showWaiter}</div>

        <div style={{ margintop:0, marginTop:22, background:'#fff', borderRadius:24, padding:20, boxShadow:'0 20px 50px rgba(0,0,0,0.4)' }}>
          <FauxQR seed={customerNo} size={196} />
        </div>

        <div style={{ marginTop:18, textAlign:'center' }}>
          <div style={{ fontSize:11, textTransform:'uppercase', letterSpacing:'0.1em', color:'rgba(245,240,232,0.6)', fontWeight:700 }}>{T[lang].customerNo}</div>
          <div style={{ fontWeight:900, fontSize:22, color:CREAM, fontVariantNumeric:'tabular-nums', letterSpacing:'0.04em', marginTop:4 }}>{customerNo}</div>
        </div>

        <div style={{ marginTop:20, width:'100%', display:'flex', gap:10 }}>
          <div style={{ flex:1, background:'rgba(255,255,255,0.08)', borderRadius:16, padding:'14px', textAlign:'center' }}>
            <div style={{ fontSize:11, color:'rgba(245,240,232,0.6)', textTransform:'uppercase', letterSpacing:'0.08em', fontWeight:700 }}>{T[lang].myPoints}</div>
            <div style={{ fontWeight:900, fontSize:26, color:GREEN, fontVariantNumeric:'tabular-nums', marginTop:4 }}>{points} P</div>
          </div>
        </div>

        <div style={{ marginTop:20, width:'100%' }}>
          <div style={{ fontSize:11, textTransform:'uppercase', letterSpacing:'0.1em', color:'rgba(245,240,232,0.55)', fontWeight:700, marginBottom:10 }}>{T[lang].howItWorks}</div>
          <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
            {[[Icon.gift,T[lang].loyaltyP1],[Icon.clock,T[lang].loyaltyP2],[Icon.sparkle,T[lang].loyaltyP3]].map(([Ic,txt],i)=>(
              <div key={i} style={{ display:'flex', alignItems:'center', gap:12, background:'rgba(255,255,255,0.06)', borderRadius:14, padding:'12px 14px' }}>
                <Ic size={18} color={GREEN} />
                <span style={{ fontSize:14, color:CREAM, fontWeight:500 }}>{txt}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window.AvbX = window.AvbX || {}, { FauxQR, BuildMenuScreen, ComboCard, CombosScreen, WalletQRScreen });
})();
