/* ============================================================
   screen_cases.jsx — экран «Кейсы» (12, по 2 в ряд) + открытие кейса
   с горизонтальной CS-style рулеткой и модалкой приза.
   ============================================================ */
const { useState:useStateC, useRef:useRefC, useEffect:useEffectC, useMemo:useMemoC } = React;

// ---------- сетка кейсов -------------------------------------------------
function CasesScreen({ onOpen, dev, devPin }){
  return (
    <div className="screen">
      <div className="h1">Кейсы</div>
      <div className="sub">Открывай кейсы и собирай NFT-подарки</div>
      {dev && <div style={{position:'relative'}}>{devPin(4,{left:-2,top:6})}</div>}

      <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:13,marginTop:18,position:'relative'}}>
        {dev && devPin(5,{right:-2,top:-10})}
        {CASES.map((c,i)=> <CaseCard key={c.id} c={c} onOpen={onOpen} idx={i}/> )}
      </div>
    </div>
  );
}

function CaseCard({ c, onOpen, idx }){
  const chip = {display:'inline-flex',alignItems:'center',gap:5,background:'var(--surface-2)',
    borderRadius:999,padding:'5px 10px 5px 8px'};
  return (
    <button className="card" onClick={()=>onOpen(c)} style={{
      border:'none',cursor:'pointer',textAlign:'left',padding:0,overflow:'hidden',
      fontFamily:'var(--font)',position:'relative',
      boxShadow:'0 6px 18px rgba(0,0,0,.35)',
    }}>
      <div style={{position:'relative',height:124,display:'flex',alignItems:'center',justifyContent:'center',
        background:'radial-gradient(78% 78% at 50% 34%, rgba(150,168,205,.15) 0%, rgba(150,168,205,.05) 46%, rgba(0,0,0,0) 73%)'}}>
        <div style={{fontSize:62,lineHeight:1,filter:'drop-shadow(0 12px 18px rgba(0,0,0,.55))',
          animation:`floaty ${3+idx%3*0.4}s ease-in-out ${idx*0.2}s infinite`}}>{c.emoji}</div>
      </div>
      <div style={{padding:'2px 12px 13px'}}>
        <div style={{fontSize:16,fontWeight:800,letterSpacing:'-.2px'}}>{c.title}</div>
        <div style={{display:'flex',gap:6,marginTop:9,flexWrap:'wrap'}}>
          <span style={chip}><Price value={c.priceTon} currency="ton" size={13}/></span>
          <span style={chip}><Price value={c.priceStar} currency="star" size={13}/></span>
        </div>
      </div>
    </button>
  );
}

// ---------- открытие кейса (рулетка) -------------------------------------
const TILE = 92;   // шаг ленты, px
function CaseOpenView({ c, onClose, onSpin, onWin, flash, dev, devPin }){
  const [phase,setPhase] = useStateC('idle');      // idle | spin | done
  const [cur,setCur] = useStateC('ton');            // валюта оплаты
  const [win,setWin] = useStateC(null);
  const [tx,setTx] = useStateC(0);
  const [trans,setTrans] = useStateC('none');
  const wonRef = useRefC(null);
  const stripRef = useRefC(null);
  const vpRef = useRefC(null);

  // лента: длинный ряд случайных предметов из пула; победитель встанет на index WIN_IDX
  const WIN_IDX = 48;
  const [strip,setStrip] = useStateC(()=>{
    const pool = c.pool.map(giftById);
    return Array.from({length:60},()=> pool[Math.floor(Math.random()*pool.length)]);
  });

  async function spin(){
    if(phase==='spin') return;
    setPhase('spin');
    try{
      // POST /api/cases/:id/open — сервер списывает баланс и возвращает выпавший подарок
      const res = await onSpin(c, cur); // {gift, itemUid, balance}
      const w = res.gift;
      wonRef.current = { gift: w, itemUid: res.itemUid };

      setStrip(prev=>{ const next=[...prev]; next[WIN_IDX]=w; return next; });
      setTrans('none'); setTx(0);
      requestAnimationFrame(()=>requestAnimationFrame(()=>{
        const vp = vpRef.current.offsetWidth;
        const jitter = (Math.random()*0.6-0.3)*TILE; // остановка не строго по центру
        const target = -(WIN_IDX*TILE + TILE/2 - vp/2) + jitter;
        setTrans('transform 5.4s cubic-bezier(.12,.62,.16,1)');
        setTx(target);
      }));
      setTimeout(()=>{ setWin(w); setPhase('done'); },5500);
    }catch(err){
      setPhase('idle');
      const code = err.body && err.body.error;
      if(code==='insufficient_ton') flash && flash('Недостаточно TON');
      else if(code==='insufficient_star') flash && flash('Недостаточно Stars');
      else flash && flash('Не удалось открыть кейс');
    }
  }

  return (
    <div className="app" style={{position:'absolute',inset:0,zIndex:42}}>
      <div className="tg-head">
        <button className="tg-pill" onClick={onClose}><IconBack size={17}/>Назад</button>
        <div style={{flex:1}}/>
        <span className="bal-pill"><Price value={cur==='ton'?c.priceTon:c.priceStar} currency={cur} size={14}/></span>
      </div>

      <div className="screen" style={{paddingBottom:30,display:'flex',flexDirection:'column'}}>
        <div style={{textAlign:'center',marginTop:4}}>
          <div style={{fontSize:54,filter:'drop-shadow(0 8px 14px rgba(0,0,0,.5))',
            animation:phase==='spin'?'none':'floaty 3s ease-in-out infinite'}}>{c.emoji}</div>
          <div className="h2" style={{marginTop:2}}>Кейс «{c.title}»</div>
        </div>

        {/* рулетка */}
        <div style={{position:'relative',margin:'26px -16px 0'}}>
          {dev && devPin(5,{left:14,top:-14})}
          {/* центр-указатель */}
          <div style={{position:'absolute',left:'50%',top:-9,transform:'translateX(-50%)',zIndex:4}}>
            <div style={{width:0,height:0,borderLeft:'9px solid transparent',borderRight:'9px solid transparent',
              borderTop:'12px solid var(--accent)'}}/>
          </div>
          <div style={{position:'absolute',left:'50%',bottom:-9,transform:'translateX(-50%)',zIndex:4}}>
            <div style={{width:0,height:0,borderLeft:'9px solid transparent',borderRight:'9px solid transparent',
              borderBottom:'12px solid var(--accent)'}}/>
          </div>
          <div style={{position:'absolute',left:'50%',top:0,bottom:0,width:2,marginLeft:-1,zIndex:3,
            background:'var(--accent)',boxShadow:'0 0 16px 2px rgba(47,142,255,.7)'}}/>
          {/* затемнение по краям */}
          <div style={{position:'absolute',inset:0,zIndex:3,pointerEvents:'none',
            background:'linear-gradient(90deg,#000 0%,rgba(0,0,0,0) 16%,rgba(0,0,0,0) 84%,#000 100%)'}}/>
          <div ref={vpRef} style={{overflow:'hidden',height:124,
            borderTop:'1px solid var(--hairline)',borderBottom:'1px solid var(--hairline)',
            background:'rgba(255,255,255,.02)'}}>
            <div ref={stripRef} style={{display:'flex',height:'100%',transform:`translateX(${tx}px)`,
              transition:trans,willChange:'transform'}}>
              {strip.map((g,i)=>(
                <div key={i} style={{flex:`0 0 ${TILE}px`,height:'100%',display:'flex',flexDirection:'column',
                  alignItems:'center',justifyContent:'center',gap:3,
                  borderRight:'1px solid var(--hairline)'}}>
                  <div style={{position:'absolute',width:TILE-8,height:96,borderRadius:14,
                    background:rarityGlow(g.rarity),pointerEvents:'none'}}/>
                  <div style={{fontSize:38,filter:'drop-shadow(0 5px 8px rgba(0,0,0,.5))'}}>{g.emoji}</div>
                  <div style={{width:22,height:3,borderRadius:2,background:rarityRing(g.rarity)}}/>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div style={{flex:1}}/>

        {/* возможные дропы */}
        <div style={{marginTop:24}}>
          <div className="section-row" style={{margin:'0 2px 11px'}}>
            <span className="h2" style={{fontSize:16}}>Содержимое кейса</span>
            <span style={{color:'var(--text-sec)',fontSize:13}}>{c.pool.length} предметов</span>
          </div>
          <div style={{display:'flex',gap:9,overflowX:'auto',paddingBottom:4}}>
            {c.pool.map(giftById).sort((a,b)=>b.ton-a.ton).map(g=>(
              <div key={g.id} style={{flex:'0 0 78px'}}><GiftTile gift={g} size={66}/></div>
            ))}
          </div>
        </div>

        {/* CTA */}
        <div style={{position:'relative',marginTop:20}}>
          {dev && devPin(6,{right:6,top:-12})}
          {/* выбор валюты оплаты — цены/списание на бэке (DEV #6) */}
          <div style={{display:'flex',gap:8,marginBottom:11}}>
            {['ton','star'].map(k=>(
              <button key={k} onClick={()=>setCur(k)} disabled={phase==='spin'} style={{
                flex:1,height:46,borderRadius:14,cursor:'pointer',fontFamily:'var(--font)',
                display:'flex',alignItems:'center',justifyContent:'center',gap:7,color:'#fff',fontWeight:700,
                background:cur===k?'var(--accent-soft)':'var(--surface)',
                border:cur===k?'1.5px solid var(--accent)':'1px solid var(--hairline)'}}>
                <Price value={k==='ton'?c.priceTon:c.priceStar} currency={k} size={15}/>
              </button>
            ))}
          </div>
          <button className="btn btn-primary btn-block" onClick={spin} disabled={phase==='spin'}>
            {phase==='spin' ? 'Крутим…' : <>Открыть за <Price value={cur==='ton'?c.priceTon:c.priceStar} currency={cur} size={17} bold/></>}
          </button>
          <div style={{textAlign:'center',color:'var(--text-ter)',fontSize:12,marginTop:9}}>
            Честный розыгрыш · результат считает сервер
          </div>
        </div>
      </div>

      {/* модалка приза */}
      <PrizeModal win={win} open={phase==='done'} onClose={()=>setPhase('idle')}
        onKeep={()=>{ onWin(win,'keep',cur,wonRef.current.itemUid); setPhase('idle'); }}
        onSell={()=>{ onWin(win,'sell',cur,wonRef.current.itemUid); setPhase('idle'); }}/>
    </div>
  );
}

// ---------- модалка приза ------------------------------------------------
function PrizeModal({ win, open, onClose, onKeep, onSell }){
  if(!win) return null;
  const r = RARITY[win.rarity];
  return (
    <CenterModal open={open} onClose={onClose} dismissable={false}>
      <div style={{background:'#17171a',borderRadius:26,padding:'26px 22px 22px',textAlign:'center',
        border:`1px solid ${r.hex}55`,boxShadow:`0 0 60px ${r.hex}40`,position:'relative',overflow:'hidden'}}>
        {/* лучи */}
        <div style={{position:'absolute',top:-40,left:'50%',width:300,height:300,marginLeft:-150,
          background:`conic-gradient(from 0deg, ${r.hex}22, transparent 22%, ${r.hex}22 44%, transparent 66%, ${r.hex}22 88%, transparent)`,
          animation:'spinGlow 9s linear infinite',pointerEvents:'none',opacity:.6}}/>
        <div style={{position:'relative'}}>
          <div className="dev-tag" style={{color:r.hex,borderColor:`${r.hex}66`}}>Вам выпало</div>
          <div style={{fontSize:96,margin:'4px 0 2px',animation:'pop .5s var(--ease) both',
            filter:`drop-shadow(0 12px 22px ${r.hex}77)`}}>{win.emoji}</div>
          <div style={{fontSize:23,fontWeight:800,marginTop:6}}>{win.title}</div>
          <div style={{marginTop:8}}><RarityTag rarity={win.rarity}/></div>
          <div style={{marginTop:14,display:'flex',justifyContent:'center'}}>
            <span style={{background:'var(--surface-2)',borderRadius:999,padding:'8px 16px'}}>
              <Price value={win.ton} currency="ton" size={17}/>
            </span>
          </div>
          <div style={{display:'flex',gap:10,marginTop:20}}>
            <button className="btn btn-ghost" style={{flex:1,height:50}} onClick={onSell}>
              Продать
            </button>
            <button className="btn btn-primary" style={{flex:1.3,height:50}} onClick={onKeep}>
              Забрать
            </button>
          </div>
        </div>
      </div>
    </CenterModal>
  );
}

Object.assign(window, { CasesScreen, CaseOpenView });
