;(function(){
const useState  = React.useState;
const useEffect = React.useEffect;
const useRef    = React.useRef;

// ══════════════════════════════════════════════════════════════
//  COMBATE PRINCIPAL
// ══════════════════════════════════════════════════════════════
function CombatScreen({ state, dispatch }) {
  const pkm    = state.pokemon[state.activePkmIndex];
  const { combat } = state;
  if (!combat || !pkm) return null;

  // Pantallas especiales por fase
  if (combat.phase === 'victory' || combat.phase === 'capture_anim')
    return <CaptureScreen state={state} dispatch={dispatch} pkm={pkm} combat={combat}/>;
  if (combat.phase === 'player_fainted')
    return <SwitchScreen state={state} dispatch={dispatch} combat={combat}/>;
  if (combat.phase === 'gym_victory')
    return <GymVictoryScreen state={state} dispatch={dispatch} combat={combat}/>;

  const enemyType   = PTYPE[combat.enemy.id] || 'normal';
  const playerType  = pkm.type || 'normal';
  const enemyColor  = TYPE_COL[enemyType]  || C.dim;
  const playerColor = TYPE_COL[playerType] || C.dim;
  const isGym = combat.isGymBattle;
  const gym   = isGym ? GYMS[combat.gymId] : null;

  return (
    <div style={{ width:240,height:282,display:'flex',flexDirection:'column',
      overflow:'hidden',position:'relative',background:SCENARIO_BG[state.scenario]||SCENARIO_BG[0] }}>
      <div style={{ position:'absolute',inset:0,background:'rgba(0,0,0,0.52)',pointerEvents:'none' }}/>

      {/* Header del gimnasio (si aplica) */}
      {isGym && gym && (
        <div style={{ position:'relative',zIndex:3,background:`${gym.color}22`,
          borderBottom:`1px solid ${gym.color}`,padding:'3px 8px',
          display:'flex',justifyContent:'space-between',alignItems:'center' }}>
          <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:gym.color }}>{gym.leader}</span>
          <div style={{ display:'flex',gap:3 }}>
            {gym.team.map((_,i)=>(
              <div key={i} style={{ width:8,height:8,borderRadius:'50%',
                background: i<=(combat.gymPokemonIndex||0) ? gym.color : '#333',
                border:`1px solid ${gym.color}` }}/>
            ))}
          </div>
          <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:gym.color }}>{gym.title}</span>
        </div>
      )}

      {/* Stats enemigo */}
      <div style={{ position:'relative',zIndex:2,padding:'5px 10px 3px',
        borderBottom:'1px solid #1a1a1a',background:'rgba(0,0,0,0.65)' }}>
        <div style={{ display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:3 }}>
          <div style={{ display:'flex',alignItems:'center',gap:5 }}>
            <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:6,color:C.text }}>{combat.enemy.name}</span>
            <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:enemyColor,
              background:'rgba(0,0,0,0.5)',padding:'1px 4px',borderRadius:2,border:`1px solid ${enemyColor}` }}>
              LV{combat.enemy.level}
            </span>
          </div>
          <TypeBadge type={enemyType}/>
        </div>
        <HpBar hp={combat.enemyHp} maxHp={combat.enemy.maxHp} width={isGym?168:196} height={6}/>
        <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim,marginTop:2 }}>
          {combat.enemyHp}/{combat.enemy.maxHp}
        </div>
      </div>

      {/* Arena de combate */}
      <div style={{ position:'relative',zIndex:2,flex:1,overflow:'hidden' }}>
        {/* Enemigo — pequeño, lejos, arriba-derecha */}
        <div style={{ position:'absolute',top:4,right:10,
          animation:combat.phase==='player_attack'?'combatShake 0.3s':'none' }}>
          <img src={spriteAnimated(combat.enemy.id)} alt={combat.enemy.name}
            style={{ width:62,height:62,imageRendering:'pixelated',
              opacity:combat.enemyHp<=0?0.1:1,
              filter:combat.enemyHp<=0?'grayscale(1)':`drop-shadow(0 0 5px ${enemyColor}70)` }}
            onError={e=>{ e.target.src=spriteStatic(combat.enemy.id); }}/>
        </div>
        <div style={{ position:'absolute',top:62,right:16,width:55,height:7,
          background:'rgba(255,255,255,0.05)',borderRadius:'50%' }}/>

        {/* Jugador — grande, cerca, abajo-izquierda */}
        <div style={{ position:'absolute',bottom:6,left:-6,
          animation:combat.phase==='enemy_attack'?'combatShake 0.3s':'none' }}>
          <img src={spriteBack(pkm.id)} alt={pkm.name}
            style={{ width:118,height:118,imageRendering:'pixelated',
              opacity:combat.playerHp<=0?0.1:1,
              filter:combat.playerHp<=0?'grayscale(1)':`drop-shadow(0 0 8px ${playerColor}80)` }}
            onError={e=>{ e.target.src=spriteStatic(pkm.id); }}/>
        </div>
        <div style={{ position:'absolute',bottom:6,left:8,width:88,height:10,
          background:'rgba(255,255,255,0.06)',borderRadius:'50%' }}/>

        {/* Partículas */}
        {combat.particles&&combat.particles.map(p=>(
          <div key={p.id} style={{ position:'absolute',left:p.x,top:p.y,width:5,height:5,
            borderRadius:'50%',background:p.color,animation:'particle 0.5s forwards',pointerEvents:'none' }}/>
        ))}
      </div>

      {/* Stats jugador */}
      <div style={{ position:'relative',zIndex:2,padding:'4px 10px 4px',
        borderTop:'1px solid #1a1a1a',background:'rgba(0,0,0,0.65)' }}>
        <div style={{ display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:3 }}>
          <div style={{ display:'flex',alignItems:'center',gap:5 }}>
            <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:6,color:C.text }}>{pkm.name}</span>
            <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:playerColor,
              background:'rgba(0,0,0,0.5)',padding:'1px 4px',borderRadius:2,border:`1px solid ${playerColor}` }}>
              LV{pkm.level}
            </span>
          </div>
          <TypeBadge type={playerType}/>
        </div>
        <HpBar hp={combat.playerHp} maxHp={pkm.maxHp} width={196} height={6}/>
        <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim,marginTop:2 }}>
          {combat.playerHp}/{pkm.maxHp}
        </div>
      </div>

      {/* Log */}
      <div style={{ position:'relative',zIndex:2,background:'rgba(0,0,0,0.9)',
        borderTop:`1px solid ${C.border}`,padding:'4px 8px',height:42,overflow:'hidden' }}>
        {combat.log.slice(-2).map((line,i,arr)=>(
          <div key={i} style={{ fontFamily:'Press Start 2P,monospace',fontSize:6,
            color:i===arr.length-1?C.text:C.dim,lineHeight:1.8 }}>
            {i===arr.length-1?'► ':'  '}{line}
          </div>
        ))}
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════
//  CAPTURA (post-victoria salvaje)
// ══════════════════════════════════════════════════════════════
function CaptureScreen({ state, dispatch, pkm, combat }) {
  const [ballAnim,setBallAnim]=useState(null);
  const [wobble,setWobble]=useState(0);
  const inv=state.inventory;

  useEffect(()=>{
    if(combat.phase!=='capture_anim') return;
    setBallAnim('throw');
    const t1=setTimeout(()=>{ setBallAnim('wobble'); setWobble(1); },700);
    const t2=setTimeout(()=>setWobble(2),1200);
    const t3=setTimeout(()=>setWobble(3),1700);
    const t4=setTimeout(()=>{ setBallAnim('done'); dispatch({type:'FINISH_CAPTURE'}); },2400);
    return()=>{ [t1,t2,t3,t4].forEach(clearTimeout); };
  },[combat.phase]);

  const ball=BALL_TYPES.find(b=>b.id===combat.captureBall)||BALL_TYPES[0];
  const isAnim=combat.phase==='capture_anim';

  return (
    <div style={{ width:240,height:282,display:'flex',flexDirection:'column',overflow:'hidden',
      position:'relative',background:SCENARIO_BG[state.scenario]||SCENARIO_BG[0] }}>
      <div style={{ position:'absolute',inset:0,background:'rgba(0,0,0,0.72)',pointerEvents:'none' }}/>

      <div style={{ position:'relative',zIndex:2,flex:1,display:'flex',alignItems:'center',justifyContent:'center' }}>
        {!isAnim&&(
          <div style={{ textAlign:'center' }}>
            <img src={spriteAnimated(combat.enemy.id)} alt={combat.enemy.name}
              style={{ width:80,height:80,imageRendering:'pixelated',
                filter:`drop-shadow(0 0 8px ${TYPE_COL[PTYPE[combat.enemy.id]||'normal']}80)` }}
              onError={e=>{ e.target.src=spriteStatic(combat.enemy.id); }}/>
            <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:7,color:C.text,marginTop:6 }}>
              {combat.enemy.name}
            </div>
            <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim,marginTop:2,marginBottom:4 }}>
              LV{combat.enemy.level} · HP {combat.enemyHp}/{combat.enemy.maxHp}
            </div>
            <HpBar hp={combat.enemyHp} maxHp={combat.enemy.maxHp} width={120} height={5}/>
          </div>
        )}
        {isAnim&&(
          <div style={{ display:'flex',flexDirection:'column',alignItems:'center',gap:14 }}>
            <div style={{ animation:ballAnim==='throw'?'ballThrow 0.6s ease-out forwards':
              ballAnim==='wobble'?`ballWobble 0.35s ${wobble} ease-in-out`:'none' }}>
              <img src={ball.sprite} alt={ball.name}
                style={{ width:42,height:42,imageRendering:'pixelated' }}
                onError={e=>{ e.target.style.cssText=`width:42px;height:42px;background:${ball.color};border-radius:50%;display:block;`; }}/>
            </div>
            <div style={{ display:'flex',gap:8 }}>
              {[0,1,2].map(k=>(
                <div key={k} style={{ width:10,height:10,borderRadius:'50%',
                  background:wobble>k?C.green:'#333',transition:'background 0.2s',
                  border:`1px solid ${wobble>k?C.green:'#555'}` }}/>
              ))}
            </div>
            <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:6,color:C.dim }}>
              {ballAnim==='done'?(combat.captureSuccess?'¡CAPTURADO!':'ESCAPÓ...'):'...'}
            </div>
          </div>
        )}
      </div>

      {!isAnim&&(
        <div style={{ position:'relative',zIndex:2,background:'rgba(0,0,0,0.93)',
          borderTop:`1px solid ${C.orange}`,padding:'7px 8px 6px' }}>
          <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:6,color:C.orange,marginBottom:5 }}>
            ¿LANZAR POKÉBALL?
          </div>
          <div style={{ display:'flex',gap:4,marginBottom:5,flexWrap:'wrap' }}>
            {BALL_TYPES.map(b=>{
              const count=inv[b.id]||0;
              if(count<=0) return null;
              return (
                <div key={b.id} onClick={()=>dispatch({type:'THROW_BALL',ballId:b.id})}
                  style={{ display:'flex',flexDirection:'column',alignItems:'center',gap:2,
                    padding:'4px 5px',borderRadius:3,cursor:'pointer',
                    border:`1px solid ${b.color}55`,background:`${b.color}18` }}>
                  <img src={b.sprite} alt={b.name} style={{ width:22,height:22,imageRendering:'pixelated' }}
                    onError={e=>{ e.target.style.cssText=`width:22px;height:22px;background:${b.color};border-radius:50%;`; }}/>
                  <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:4,color:b.color }}>x{count}</div>
                </div>
              );
            })}
          </div>
          <div style={{ display:'flex',gap:5 }}>
            <div onClick={()=>dispatch({type:'CLAIM_VICTORY'})}
              style={{ flex:1,padding:'6px 0',textAlign:'center',cursor:'pointer',
                fontFamily:'Press Start 2P,monospace',fontSize:6,color:C.green,
                border:`1px solid ${C.green}44`,borderRadius:3,background:`${C.green}15` }}>OK</div>
            <div onClick={()=>dispatch({type:'FLEE_COMBAT'})}
              style={{ flex:1,padding:'6px 0',textAlign:'center',cursor:'pointer',
                fontFamily:'Press Start 2P,monospace',fontSize:6,color:C.dim,
                border:`1px solid ${C.border}`,borderRadius:3 }}>HUIR</div>
          </div>
        </div>
      )}
    </div>
  );
}

// ══════════════════════════════════════════════════════════════
//  CAMBIO DE POKÉMON (cuando el activo cae en combate)
// ══════════════════════════════════════════════════════════════
function SwitchScreen({ state, dispatch, combat }) {
  const now=Date.now();
  const available=getActiveTeamIndexes(state)
    .map(i=>({p:state.pokemon[i],i}))
    .filter(({p,i})=>
      p&&i!==state.activePkmIndex&&p.hp>0&&(!p.faintedAt||(now-p.faintedAt>=COOLDOWN_MS)));

  return (
    <div style={{ width:240,height:282,background:'#0a0005',display:'flex',flexDirection:'column',overflow:'hidden' }}>
      <div style={{ padding:'6px 10px',background:'rgba(239,68,68,0.15)',
        borderBottom:`1px solid ${C.red}`,flexShrink:0 }}>
        <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:7,color:C.red,marginBottom:3 }}>
          ¡{state.pokemon[state.activePkmIndex]?.name} CAYÓ!
        </div>
        <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim }}>
          Elige tu próximo Pokémon
        </div>
      </div>

      <div style={{ flex:1,padding:6,overflowY:'auto' }}>
        {available.length===0&&(
          <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:6,color:C.dim,textAlign:'center',marginTop:20 }}>
            No hay más Pokémon<br/>disponibles
          </div>
        )}
        {available.map(({p,i})=>{
          const playerColor=TYPE_COL[p.type||'normal']||C.dim;
          return (
            <div key={p.uid||i} onClick={()=>dispatch({type:'SWITCH_POKEMON',index:i})}
              style={{ display:'flex',alignItems:'center',gap:8,padding:'6px 8px',marginBottom:4,
                borderRadius:4,cursor:'pointer',background:'rgba(255,255,255,0.04)',
                border:`1px solid ${playerColor}44`,transition:'border-color 0.15s' }}>
              <img src={spriteStatic(p.id)} alt={p.name}
                style={{ width:40,height:40,imageRendering:'pixelated',flexShrink:0,
                  filter:`drop-shadow(0 0 4px ${playerColor}60)` }}
                onError={e=>{ e.target.style.display='none'; }}/>
              <div style={{ flex:1 }}>
                <div style={{ display:'flex',alignItems:'center',gap:5,marginBottom:3 }}>
                  <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:7,color:C.text }}>{p.name}</span>
                  <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:playerColor,
                    padding:'1px 3px',borderRadius:2,border:`1px solid ${playerColor}` }}>LV{p.level}</span>
                </div>
                <HpBar hp={p.hp} maxHp={p.maxHp} width={130} height={5}/>
                <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim,marginTop:2 }}>
                  {p.hp}/{p.maxHp} HP
                </div>
              </div>
              <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:7,color:playerColor,flexShrink:0 }}>▶</span>
            </div>
          );
        })}
      </div>

      {/* Botón huir (solo combates salvajes) */}
      {!combat.isGymBattle&&(
        <div onClick={()=>dispatch({type:'FLEE_COMBAT'})}
          style={{ padding:'8px',textAlign:'center',cursor:'pointer',
            fontFamily:'Press Start 2P,monospace',fontSize:6,color:C.dim,
            borderTop:`1px solid ${C.border}`,flexShrink:0 }}>
          HUIR DEL COMBATE
        </div>
      )}
    </div>
  );
}

// ══════════════════════════════════════════════════════════════
//  VICTORIA DE GIMNASIO
// ══════════════════════════════════════════════════════════════
function GymVictoryScreen({ state, dispatch, combat }) {
  const gym=GYMS[combat.gymId];
  if(!gym) return null;
  const [anim,setAnim]=useState(false);
  useEffect(()=>{ setTimeout(()=>setAnim(true),200); },[]);

  // Recompensas a mostrar
  const rewards=Object.entries(gym.reward||{}).filter(([,v])=>v>0);

  return (
    <div style={{ width:240,height:282,background:'#0a0500',display:'flex',flexDirection:'column',
      alignItems:'center',justifyContent:'center',padding:16,gap:12,overflow:'hidden',position:'relative' }}>

      {/* Fondo con brillo */}
      <div style={{ position:'absolute',inset:0,
        background:`radial-gradient(ellipse at 50% 40%,${gym.color}22 0%,transparent 70%)`,
        pointerEvents:'none' }}/>

      {/* Sprite del líder (primer Pokémon del equipo) */}
      <img src={spriteAnimated(gym.team[0].id)} alt={gym.leader}
        style={{ width:80,height:80,imageRendering:'pixelated',
          filter:`drop-shadow(0 0 12px ${gym.color})`,
          transform:anim?'scale(1)':'scale(0.3)',opacity:anim?1:0,
          transition:'all 0.4s ease-out',flexShrink:0 }}
        onError={e=>{ e.target.src=spriteStatic(gym.team[0].id); }}/>

      <div style={{ textAlign:'center',position:'relative',zIndex:1 }}>
        <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:8,color:C.orange,lineHeight:1.8,marginBottom:4 }}>
          ¡VICTORIA!
        </div>
        <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:6,color:gym.color,lineHeight:1.8,marginBottom:2 }}>
          {gym.leader} derrotado
        </div>
        <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim }}>
          {gym.title}
        </div>
      </div>

      {/* Medalla */}
      <div style={{ display:'flex',flexDirection:'column',alignItems:'center',gap:4,
        padding:'8px 14px',border:`2px solid ${gym.color}`,borderRadius:8,
        background:`${gym.color}15`,position:'relative',zIndex:1 }}>
        <div style={{ width:28,height:28,borderRadius:'50%',background:gym.color,
          display:'flex',alignItems:'center',justifyContent:'center',fontSize:16 }}>★</div>
        <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:6,color:gym.color }}>
          Medalla {gym.badge}
        </div>
      </div>

      {/* Recompensas */}
      {rewards.length>0&&(
        <div style={{ display:'flex',gap:6,flexWrap:'wrap',justifyContent:'center',position:'relative',zIndex:1 }}>
          {rewards.map(([k,v])=>(
            <div key={k} style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim,
              background:'rgba(255,255,255,0.05)',padding:'3px 6px',borderRadius:3 }}>
              +{v} {k.replace('balls',' ball').replace('pokeballs','Pokéball').replace('greatballs','Superball').replace('ultraballs','Ultraball').replace('masterballs','Masterball').replace('berries','Baya').replace('revivals','Revivir')}
            </div>
          ))}
        </div>
      )}

      <div onClick={()=>dispatch({type:'CLAIM_GYM_VICTORY'})}
        style={{ padding:'10px 24px',background:C.orange,color:'#000',border:'none',borderRadius:4,
          fontFamily:'Press Start 2P,monospace',fontSize:7,cursor:'pointer',
          boxShadow:`0 0 12px ${C.orange}60`,position:'relative',zIndex:1 }}>
        CONTINUAR
      </div>
    </div>
  );
}

Object.assign(window,{
  CombatScreen,CaptureScreen,SwitchScreen,GymVictoryScreen,
});
})();
