/* ============================================================
   CHWAZI — finger picker (multi-touch) + wheel fallback
   ============================================================ */
const { useState: useC, useEffect: useEC, useRef: useRC } = React;

function FingerPicker({ players, onChosen }){
  const [pointers,setPointers]=useC(()=>new Map());
  const [phase,setPhase]=useC('wait');        // wait | counting | pick | done
  const [count,setCount]=useC(3);
  const [chosenId,setChosenId]=useC(null);
  const [winner,setWinner]=useC(null);
  const areaRef=useRC(null);
  const ptsRef=useRC(pointers); ptsRef.current=pointers;
  const locked=phase==='pick'||phase==='done';

  const update=(fn)=>setPointers(prev=>{ const m=new Map(prev); fn(m); return m; });

  const down=(e)=>{
    if(locked) return;
    areaRef.current.setPointerCapture?.(e.pointerId);
    const r=areaRef.current.getBoundingClientRect();
    update(m=>m.set(e.pointerId,{x:e.clientX-r.left,y:e.clientY-r.top,color:PALETTE[m.size%PALETTE.length]}));
  };
  const move=(e)=>{
    if(locked||!ptsRef.current.has(e.pointerId)) return;
    const r=areaRef.current.getBoundingClientRect();
    update(m=>{ const p=m.get(e.pointerId); if(p){p.x=e.clientX-r.left;p.y=e.clientY-r.top;} });
  };
  const up=(e)=>{ if(locked) return; update(m=>m.delete(e.pointerId)); };

  useEC(()=>{
    if(locked) return;
    if(pointers.size>=2){
      if(phase!=='counting'){ setPhase('counting'); setCount(3); }
    } else if(phase==='counting'){
      setPhase('wait'); setCount(3);
    }
  },[pointers.size,phase,locked]);

  useEC(()=>{
    if(phase!=='counting') return;
    if(count<=0){
      const ids=[...ptsRef.current.keys()];
      const winId=ids[Math.floor(Math.random()*ids.length)];
      setChosenId(winId);
      setPhase('pick');
      window.partySounds?.play('pick');
      return;
    }
    window.partySounds?.play('tick');
    const t=setTimeout(()=>setCount(c=>c-1),800);
    return ()=>clearTimeout(t);
  },[phase,count]);

  const pickPlayer=(name)=>{
    setWinner(name);
    setPhase('done');
    onChosen&&onChosen(name);
  };

  return (
    <div ref={areaRef} className="finger-area"
      onPointerDown={down} onPointerMove={move} onPointerUp={up} onPointerCancel={up} onPointerLeave={up}>
      {[...pointers.entries()].map(([id,p])=>{
        const isWin=chosenId===id, dim=locked&&!isWin;
        return <div key={id} className={'finger-ring'+(isWin?' win':'')} style={{
          left:p.x,top:p.y,borderColor:p.color,
          opacity:dim?0:1, transform:`translate(-50%,-50%) scale(${isWin?1.5:1})`,
        }}>
          <span style={{background:p.color}}></span>
        </div>;
      })}

      {phase==='wait' && pointers.size<2 && (
        <div className="finger-hint center">
          <div className="stamp sh-coral" style={{fontSize:44}}>Fingers<br/>down!</div>
          <p className="muted mt16" style={{maxWidth:280}}>Everyone press &amp; <b>hold</b> one finger on the screen. The chosen one gets picked.</p>
          {pointers.size===1 && <p className="serif-i" style={{fontSize:20,color:'#FFD79A',marginTop:14}}>need one more finger…</p>}
        </div>
      )}
      {phase==='counting' && (
        <div className="finger-count center"><div key={count} className="bigcount count-anim">{count===0?'!':count}</div></div>
      )}
      {phase==='pick' && (
        <div className="finger-pick center" style={{gap:14}}>
          <div className="stamp sh-teal" style={{fontSize:40}}>Who was<br/>chosen?</div>
          <p className="muted" style={{maxWidth:280,fontSize:14}}>Tap the player with the glowing finger.</p>
          <div className="wrap" style={{gap:9,justifyContent:'center',marginTop:6}}>
            {players.map(p=>(
              <button key={p} className="chip selectable" style={{fontSize:15,cursor:'pointer'}} onClick={()=>pickPlayer(p)}>
                <Avatar name={p} size={22}/>{p}
              </button>
            ))}
          </div>
        </div>
      )}
      {phase==='done' && winner && (
        <div className="finger-won center" style={{gap:10}}>
          <div className="kicker">chosen</div>
          <Avatar name={winner} size={44}/>
          <div className="stamp sh-teal" style={{fontSize:46}}>{winner}</div>
        </div>
      )}
    </div>
  );
}

function Wheel({ players, onChosen }){
  const [angle,setAngle]=useC(0);
  const [spinning,setSpinning]=useC(false);
  const [winner,setWinner]=useC(null);
  const n=players.length;
  const seg=360/n;

  const spin=()=>{
    if(spinning) return;
    setWinner(null); setSpinning(true);
    window.partySounds?.play('spin');
    const turns=5+Math.random()*3;
    const target=angle+turns*360+Math.random()*360;
    setAngle(target);
    setTimeout(()=>{
      const norm=(360-(target%360))%360;
      const idx=Math.floor(norm/seg)%n;
      const w=players[idx];
      setWinner(w); setSpinning(false);
      window.partySounds?.play('pick');
      onChosen&&onChosen(w);
    },4200);
  };

  const grad=players.map((p,i)=>`${PALETTE[i%PALETTE.length]} ${i*seg}deg ${(i+1)*seg}deg`).join(',');
  return (
    <div className="center" style={{flex:1,gap:24,padding:'10px 20px 30px'}}>
      <div className="wheel-wrap">
        <div className="wheel-ptr">▼</div>
        <div className="wheel" style={{background:`conic-gradient(${grad})`,transform:`rotate(${angle}deg)`,transition:spinning?'transform 4.1s cubic-bezier(.17,.67,.16,1)':'none'}}>
          {players.map((p,i)=>(
            <div key={i} className="wheel-label" style={{transform:`rotate(${i*seg+seg/2}deg)`}}>
              <span style={{transform:'rotate(90deg)'}}>{p}</span>
            </div>
          ))}
          <div className="wheel-hub"></div>
        </div>
      </div>
      {winner
        ? <div className="center" style={{gap:4}}><div className="kicker">the wheel has spoken</div><div className="stamp sh-pink" style={{fontSize:46}}>{winner}</div></div>
        : <Btn color="coral" size="lg" onClick={spin} disabled={spinning} style={{maxWidth:300}}>{spinning?'Spinning…':'Spin the wheel'}</Btn>}
    </div>
  );
}

function GameChwazi({ game, players, onExit, onHome }){
  const leave=onHome||onExit;
  const touch = ('ontouchstart' in window) || navigator.maxTouchPoints>0;
  const [mode,setMode]=useC(touch?'fingers':'wheel');
  const [fired,setFired]=useC(false);
  const [round,setRound]=useC(0);

  const onPick=(name)=>{ setFired(true); };

  return (
    <div className="app screen" style={{overflow:'hidden'}}>
      <Burst fire={fired}/>
      <TopBar onBack={onExit} title="Chwazi · let fate pick" color={game.color}
        right={<button className="iconbtn" onClick={()=>{setMode(mode==='fingers'?'wheel':'fingers');setFired(false);setRound(r=>r+1);}} title="Switch mode">{mode==='fingers'?'🎡':'☝️'}</button>}/>

      {mode==='fingers'
        ? <FingerPicker key={round} players={players} onChosen={onPick}/>
        : <Wheel key={round} players={players} onChosen={onPick}/>}

      <div className="pad" style={{paddingTop:6}}>
        <div className="btn-row">
          <Btn variant="ghost" onClick={()=>{setFired(false);setRound(r=>r+1);}}>↻ Pick again</Btn>
          <Btn color="teal" onClick={leave}>Done</Btn>
        </div>
        <div className="tcenter mono" style={{fontSize:11,color:'#7E70AE',marginTop:12}}>
          {mode==='fingers'?'Tip: tap 🎡 for a spin wheel instead':'Tip: tap ☝️ for multi-touch finger mode'}
        </div>
      </div>
    </div>
  );
}
window.GameChwazi = GameChwazi;
