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

// ══════════════════════════════════════════════════════════════
//  FONDOS DE ESCENARIO — 20 zonas
// ══════════════════════════════════════════════════════════════
const SCENARIO_BG = [
  `linear-gradient(180deg,#87CEEB 0%,#87CEEB 42%,#5fa832 42%,#5fa832 54%,#3d6e1a 54%,#3d6e1a 100%)`,
  `linear-gradient(180deg,#0d1f0d 0%,#1a3a12 40%,#102a10 40%,#102a10 60%,#0a1a08 60%,#0a1a08 100%)`,
  `linear-gradient(180deg,#1a1008 0%,#2d1c0e 35%,#1a0e06 35%,#1a0e06 65%,#0d0804 65%,#0d0804 100%)`,
  `linear-gradient(180deg,#1a0500 0%,#3d0a00 28%,#600f00 28%,#600f00 54%,#1a0500 54%,#0d0300 100%)`,
  `linear-gradient(180deg,#0a2a4d 0%,#0d3b6e 40%,#0a4f8a 40%,#0a4f8a 65%,#062a52 65%,#041830 100%)`,
  `linear-gradient(180deg,#040f1a 0%,#062040 35%,#08305a 35%,#08305a 65%,#041830 65%,#020d1a 100%)`,
  `linear-gradient(180deg,#1a0a00 0%,#3d1500 25%,#6b2600 25%,#8a3800 50%,#5a2800 50%,#2a1000 100%)`,
  `linear-gradient(180deg,#05010d 0%,#0d0320 30%,#150540 30%,#0a0230 55%,#05011a 55%,#020009 100%)`,
  `linear-gradient(180deg,#00000d 0%,#050520 35%,#0a0a35 35%,#070725 60%,#030315 60%,#000008 100%)`,
  `linear-gradient(180deg,#1a0000 0%,#3d0505 25%,#600a0a 25%,#8a0000 50%,#3d0000 50%,#0d0000 100%)`,
  `linear-gradient(180deg,#080010 0%,#120020 30%,#1a0035 30%,#120025 58%,#08001a 58%,#040008 100%)`,
  `linear-gradient(180deg,#100800 0%,#2a1400 28%,#402000 28%,#5a3000 52%,#2a1800 52%,#100800 100%)`,
  `linear-gradient(180deg,#c5e0ff 0%,#a0c8ff 30%,#88b4e0 30%,#6890c0 58%,#4a6a9a 58%,#2a4a6a 100%)`,
  `linear-gradient(180deg,#030a00 0%,#061205 28%,#0a1e06 28%,#061205 55%,#030a00 55%,#010500 100%)`,
  `linear-gradient(180deg,#150000 0%,#3a0000 25%,#640000 25%,#900000 50%,#400000 50%,#100000 100%)`,
  `linear-gradient(180deg,#000510 0%,#000a20 30%,#001030 30%,#001540 58%,#000a28 58%,#000510 100%)`,
  `linear-gradient(180deg,#050010 0%,#0a0025 28%,#120040 28%,#0d0030 55%,#08001e 55%,#030008 100%)`,
  `linear-gradient(180deg,#040408 0%,#080818 28%,#0c0c28 28%,#08080f 55%,#040410 55%,#010105 100%)`,
  `linear-gradient(180deg,#0a0805 0%,#1a1408 28%,#2a2010 28%,#1a1408 55%,#0a0805 55%,#050403 100%)`,
  `linear-gradient(180deg,#0d0005 0%,#1a0010 28%,#2a0020 28%,#1a0015 55%,#0d0008 55%,#050002 100%)`,
];

function ScenarioBg({ scenarioIdx, children }) {
  const s  = SCENARIOS[scenarioIdx]||SCENARIOS[0];
  const bg = SCENARIO_BG[scenarioIdx]||SCENARIO_BG[0];
  const i  = scenarioIdx;
  const dayPhase = getDayPhase();
  const tint = DAY_TINTS[dayPhase];

  const hasSun=i===0, hasMoon=i===8||i===10;
  const hasStars=i===7||i===8||i===10||i===16||i===17||i===19;
  const hasFire=i===3||i===9||i===14, hasLava=i===14;
  const hasWaves=i===4||i===5||i===15, hasBubbles=i===5||i===15;
  const hasCity=i===7, hasGlow=i===9||i===19;
  const hasIce=i===12, hasLightning=i===17;

  return (
    <div style={{ position:'absolute',inset:0,background:bg,overflow:'hidden' }}>
      {/* Nubes */}
      {(i<=1||i===6)&&<>
        <div style={{ position:'absolute',top:14,left:20,width:38,height:12,background:'rgba(255,255,255,0.7)',borderRadius:8 }}/>
        <div style={{ position:'absolute',top:10,left:50,width:28,height:10,background:'rgba(255,255,255,0.55)',borderRadius:8 }}/>
        <div style={{ position:'absolute',top:18,right:28,width:46,height:13,background:'rgba(255,255,255,0.65)',borderRadius:8 }}/>
      </>}
      {hasSun&&<div style={{ position:'absolute',top:10,right:18,width:22,height:22,borderRadius:'50%',background:'#FFD700',boxShadow:'0 0 14px #FFD700' }}/>}
      {hasMoon&&<div style={{ position:'absolute',top:8,right:22,width:18,height:18,borderRadius:'50%',background:'#C0C0FF',boxShadow:'0 0 10px #8888FF' }}>
        <div style={{ position:'absolute',top:3,right:2,width:13,height:13,borderRadius:'50%',background:'#050520' }}/>
      </div>}
      {hasStars&&[[12,6],[55,12],[90,4],[130,9],[175,5],[210,14],[35,18],[160,18]].map(([x,y],k)=>(
        <div key={k} style={{ position:'absolute',left:x,top:y,width:2,height:2,borderRadius:'50%',background:'#fff',opacity:0.85,animation:`twinkle ${1.2+k*0.2}s infinite alternate` }}/>
      ))}
      {hasFire&&[20,55,90,140,175,210].map((x,k)=>(
        <div key={k} style={{ position:'absolute',bottom:0,left:x,width:5,height:10+k*2,background:hasLava?'#FF4400':'#FF6600',borderRadius:'50% 50% 0 0',opacity:0.85,animation:`float_${k%4} ${0.7+k*0.15}s infinite alternate` }}/>
      ))}
      {hasLava&&<div style={{ position:'absolute',bottom:0,left:0,right:0,height:14,background:'linear-gradient(90deg,#FF2200,#FF6600,#FF2200)',opacity:0.7 }}/>}
      {hasWaves&&<div style={{ position:'absolute',bottom:0,left:0,right:0,height:20,background:'repeating-linear-gradient(90deg,#0a4f8a 0px,#0a6aaa 18px,#0a4f8a 36px)',opacity:0.55 }}/>}
      {hasBubbles&&[18,52,88,136,184,216].map((x,k)=>(
        <div key={k} style={{ position:'absolute',left:x,bottom:6+k*10,width:4,height:4,borderRadius:'50%',border:'1px solid #4af',opacity:0.45,animation:`float_${k%4} ${1+k*0.3}s infinite alternate` }}/>
      ))}
      {hasCity&&[8,40,75,110,150,188].map((x,k)=>(
        <div key={k} style={{ position:'absolute',bottom:0,left:x,width:20+k*2,height:28+k*6,background:'#0d0320',border:'1px solid #200840' }}>
          {[0,1,2].map(j=><div key={j} style={{ position:'absolute',top:4+j*7,left:3+(j%2)*10,width:4,height:4,background:k%2===0&&j===1?'#FFD700':'transparent' }}/>)}
        </div>
      ))}
      {hasGlow&&<div style={{ position:'absolute',bottom:0,left:'50%',transform:'translateX(-50%)',width:140,height:6,background:s.accent,borderRadius:'50%',filter:'blur(6px)',opacity:0.5 }}/>}
      {hasIce&&[10,60,110,160,200].map((x,k)=>(
        <div key={k} style={{ position:'absolute',bottom:0,left:x,width:22+k*4,height:18+k*3,background:'rgba(180,220,255,0.35)',borderRadius:'4px 4px 0 0',border:'1px solid rgba(180,220,255,0.6)' }}/>
      ))}
      {hasLightning&&[40,120,200].map((x,k)=>(
        <div key={k} style={{ position:'absolute',top:10+k*8,left:x,width:2,height:30+k*5,background:'#FACC15',opacity:0.6,transform:`rotate(${10+k*5}deg)`,animation:`twinkle ${1+k*0.4}s infinite alternate` }}/>
      ))}
      <div style={{ position:'absolute',bottom:18,left:0,right:0,height:2,background:s.accent,opacity:0.4 }}/>
      {/* Tinte día/noche */}
      <div style={{ position:'absolute',inset:0,background:tint,pointerEvents:'none' }}/>
      {children}
    </div>
  );
}

// ── Widgets básicos ────────────────────────────────────────
function HpBar({ hp, maxHp, width=100, height=7 }) {
  const pct=maxHp>0?Math.max(0,hp/maxHp):0;
  const color=pct>0.5?C.green:pct>0.25?C.yellow:C.red;
  return (
    <div style={{ width,height,background:'#1a1a1a',borderRadius:2,overflow:'hidden',border:'1px solid #333' }}>
      <div style={{ width:`${pct*100}%`,height:'100%',background:color,transition:'width 0.25s',borderRadius:2 }}/>
    </div>
  );
}
function XpBar({ xp, xpNeeded, width=100 }) {
  const pct=xpNeeded>0?Math.min(1,xp/xpNeeded):0;
  return (
    <div style={{ width,height:3,background:'#1a1a1a',borderRadius:1,overflow:'hidden' }}>
      <div style={{ width:`${pct*100}%`,height:'100%',background:'#818CF8',borderRadius:1 }}/>
    </div>
  );
}
function TypeBadge({ type }) {
  return (
    <span style={{ fontSize:5,fontFamily:'Press Start 2P,monospace',color:TYPE_COL[type]||C.dim,
      background:'rgba(0,0,0,0.6)',padding:'2px 4px',borderRadius:2,
      border:`1px solid ${TYPE_COL[type]||C.dim}`,textTransform:'uppercase',letterSpacing:1 }}>
      {type}
    </span>
  );
}

// ── Overlay de evolución ───────────────────────────────────
function EvolutionOverlay({ evolution, onComplete }) {
  const [phase,setPhase]=useState('flash');
  const [parts,setParts]=useState([]);
  useEffect(()=>{
    SFX.evolution();
    setParts(Array.from({length:18},(_,i)=>({
      id:i,x:10+Math.random()*220,y:30+Math.random()*180,
      color:Object.values(TYPE_COL)[i%16],size:3+Math.random()*5,delay:Math.random()*0.8,
    })));
    const t1=setTimeout(()=>setPhase('white'),600);
    const t2=setTimeout(()=>setPhase('morph'),1400);
    const t3=setTimeout(()=>setPhase('restore'),2600);
    const t4=setTimeout(()=>{ setPhase('done'); onComplete(); },3600);
    return()=>{ [t1,t2,t3,t4].forEach(clearTimeout); };
  },[]);
  const isWhite=phase==='white'||phase==='morph';
  const showNew=phase==='morph'||phase==='restore'||phase==='done';
  const sid=showNew?evolution.toId:evolution.fromId;
  return (
    <div style={{ position:'absolute',inset:0,zIndex:100,background:'rgba(0,0,0,0.93)',
      display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',gap:10 }}>
      <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:7,color:C.orange,textAlign:'center',lineHeight:1.8 }}>
        {showNew?`¡${PNAMES[evolution.toId]}!`:'¿Qué?'}
      </div>
      <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim,textAlign:'center',lineHeight:1.8 }}>
        {showNew?`${PNAMES[evolution.fromId]} → ${PNAMES[evolution.toId]}`:`${PNAMES[evolution.fromId]} evoluciona...`}
      </div>
      <div style={{ position:'relative',width:96,height:96 }}>
        <img src={spriteAnimated(sid)} alt="" style={{ width:96,height:96,imageRendering:'pixelated',
          filter:isWhite?'brightness(10) saturate(0)':'brightness(1) saturate(1)',transition:'filter 0.4s' }}
          onError={e=>{ e.target.src=spriteStatic(sid); }}/>
        {isWhite&&<div style={{ position:'absolute',inset:-12,borderRadius:'50%',
          background:'radial-gradient(circle,rgba(255,255,255,0.4) 0%,transparent 70%)',animation:'evoGlow 0.3s infinite alternate' }}/>}
      </div>
      {parts.map(p=>(
        <div key={p.id} style={{ position:'absolute',left:p.x,top:p.y,width:p.size,height:p.size,
          borderRadius:'50%',background:p.color,opacity:isWhite?0.9:0,transition:'opacity 0.3s',
          animation:`particle 0.8s ${p.delay}s infinite` }}/>
      ))}
      <div style={{ width:120,height:4,background:'#222',borderRadius:2,overflow:'hidden' }}>
        <div style={{ height:'100%',background:C.orange,borderRadius:2,transition:'width 0.5s',
          width:phase==='flash'?'25%':phase==='white'?'50%':phase==='morph'?'75%':'100%' }}/>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════
//  SPLASH
// ══════════════════════════════════════════════════════════════
function SplashScreen({ onStart }) {
  const [phase,setPhase]=useState('title');
  const [sel,setSel]=useState(null);
  const [blink,setBlink]=useState(true);
  useEffect(()=>{ const iv=setInterval(()=>setBlink(b=>!b),600); return()=>clearInterval(iv); },[]);
  if(phase==='title') return (
    <div onClick={()=>setPhase('choose')} style={{ width:240,height:282,background:C.bg,
      display:'flex',flexDirection:'column',alignItems:'center',justifyContent:'center',gap:14,cursor:'pointer' }}>
      <div style={{ textAlign:'center' }}>
        <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:10,color:C.orange,lineHeight:1.8 }}>POKENAV</div>
        <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:8,color:'#FF3300',lineHeight:1.4 }}>V0.3 R1</div>
      </div>
      <img src={spriteAnimated(25)} alt="" style={{ width:64,height:64,imageRendering:'pixelated' }} onError={e=>{ e.target.src=spriteStatic(25); }}/>
      <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:6,color:blink?C.text:'transparent' }}>TAP PARA INICIAR</div>
      <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim }}>GEN I · 150 PKM · 20 ZONAS</div>
    </div>
  );
  return (
    <div style={{ width:240,height:282,background:C.bg,color:C.text,display:'flex',flexDirection:'column',padding:8,gap:6,overflow:'hidden' }}
      onWheel={e=>{ e.preventDefault(); setSel(prev=>{ const idx=STARTERS.findIndex(s=>s.id===prev?.id); return STARTERS[((idx<0?0:idx)+(e.deltaY>0?1:-1)+STARTERS.length)%STARTERS.length]; }); }}>
      <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:7,color:C.orange,textAlign:'center',paddingTop:4 }}>ELIGE TU INICIAL</div>
      <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim,textAlign:'center' }}>rueda · tap seleccionar</div>
      <div style={{ display:'flex',justifyContent:'space-around',alignItems:'flex-end',flex:1,paddingBottom:4 }}>
        {STARTERS.map(st=>{ const is=sel?.id===st.id; return (
          <div key={st.id} onClick={()=>setSel(st)} style={{ display:'flex',flexDirection:'column',alignItems:'center',gap:4,
            padding:'5px 4px',borderRadius:4,cursor:'pointer',border:`2px solid ${is?C.orange:'#222'}`,
            background:is?'rgba(255,107,0,0.12)':'transparent',transform:is?'translateY(-4px)':'none',transition:'all 0.15s' }}>
            <img src={spriteAnimated(st.id)} alt={st.name} style={{ width:54,height:54,imageRendering:'pixelated' }} onError={e=>{ e.target.src=spriteStatic(st.id); }}/>
            <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:is?C.orange:C.dim }}>{st.name}</div>
            <TypeBadge type={st.type}/>
          </div>
        );})}
      </div>
      <button onClick={()=>sel&&onStart(sel)} style={{ background:sel?C.orange:'#222',color:sel?'#000':C.dim,
        border:'none',borderRadius:3,padding:'9px 0',fontFamily:'Press Start 2P,monospace',fontSize:6,
        cursor:sel?'pointer':'default',marginBottom:4,letterSpacing:1,transition:'background 0.2s' }}>
        {sel?`VAMOS CON ${sel.name.toUpperCase()}`:'ELIGE UN POKEMON'}
      </button>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════
//  LOBBY — 5 opciones: Explorar / Gimnasio / Curar / Caja / Mochila
// ══════════════════════════════════════════════════════════════
function LobbyScreen({ state, dispatch }) {
  const pkm=state.pokemon[state.activePkmIndex];
  const sc=SCENARIOS[state.scenario]||SCENARIOS[0];
  const gym=GYMS[state.scenario];
  const now=Date.now();
  const isFainted=pkm?.faintedAt&&(now-pkm.faintedAt<COOLDOWN_MS);
  const cooldownH=isFainted?Math.ceil((COOLDOWN_MS-(now-pkm.faintedAt))/3600000):0;
  const gymDefeated=(state.defeatedGyms||[]).includes(state.scenario);
  const dayPhase=getDayPhase();
  const team=getActiveTeamIndexes(state);
  const cannotBattle=!pkm||pkm.hp<=0||isFainted;

  const MENU=[
    {label:'Explorar',  sub:sc.name,                       disabled:cannotBattle},
    {label:'Gimnasio',  sub:gym?`${gym.leader}${gymDefeated?' ✓':''}`:'-',
                                                           disabled:cannotBattle||!gym},
    {label:'Curar',     sub:`Bayas x${state.inventory.berries}`,
                                                           disabled:isFainted||state.inventory.berries<=0||pkm?.hp>=pkm?.maxHp},
    {label:'Equipo PKM',sub:`${team.length}/${ACTIVE_TEAM_SIZE} Caja ${state.pokemon.length}/${BOX_CAPACITY}`},
    {label:'Mochila',   sub:`Balls x${(state.inventory.pokeballs||0)+(state.inventory.greatballs||0)+(state.inventory.ultraballs||0)+(state.inventory.masterballs||0)}`},
  ];

  useEffect(()=>{
    const h=e=>{ e.preventDefault(); dispatch({type:'LOBBY_SCROLL',delta:e.deltaY>0?1:-1}); };
    window.addEventListener('wheel',h,{passive:false}); return()=>window.removeEventListener('wheel',h);
  },[]);

  const acts=['START_EXPLORE','START_GYM','USE_BERRY','OPEN_BOX','OPEN_INVENTORY'];
  return (
    <div style={{ width:240,height:282,background:C.bg,display:'flex',flexDirection:'column',overflow:'hidden' }}>
      {/* Header */}
      <div style={{ background:C.panel,padding:'3px 8px',display:'flex',justifyContent:'space-between',
        alignItems:'center',borderBottom:`1px solid ${sc.accent}`,flexShrink:0 }}>
        <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:sc.accent }}>{sc.name}</span>
        <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim }}>{DAY_LABELS[dayPhase]}</span>
        <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim }}>LV{pkm?.level||'?'}</span>
      </div>
      {/* Pokemon activo */}
      <div style={{ display:'flex',alignItems:'center',padding:'5px 10px',gap:8,
        borderBottom:`1px solid ${C.border}`,flexShrink:0 }}>
        <div style={{ position:'relative',flexShrink:0,cursor:'pointer' }}
          onClick={()=>dispatch({type:'OPEN_STATS'})}>
          <img src={spriteAnimated(pkm?.id)} alt={pkm?.name}
            style={{ width:60,height:60,imageRendering:'pixelated',
              opacity:isFainted?0.25:1,filter:isFainted?'grayscale(1) brightness(0.5)':'none' }}
            onError={e=>{ e.target.src=spriteStatic(pkm?.id); }}/>
          {isFainted&&<div style={{ position:'absolute',inset:0,display:'flex',flexDirection:'column',
            alignItems:'center',justifyContent:'center',fontFamily:'Press Start 2P,monospace',
            fontSize:5,color:C.red,textAlign:'center',lineHeight:1.6 }}><div>DEBIL</div><div>{cooldownH}h</div></div>}
          {/* Indicador "tap stats" */}
          {!isFainted&&<div style={{ position:'absolute',bottom:-2,right:-2,background:C.orange,
            borderRadius:2,padding:'1px 3px',fontFamily:'Press Start 2P,monospace',fontSize:4,color:'#000' }}>★</div>}
        </div>
        <div style={{ flex:1,display:'flex',flexDirection:'column',gap:3 }}>
          <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:7,color:isFainted?C.red:C.text }}>{pkm?.name}</span>
          <TypeBadge type={pkm?.type||'normal'}/>
          <HpBar hp={pkm?.hp||0} maxHp={pkm?.maxHp||1} width={126} height={6}/>
          <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim }}>{pkm?.hp}/{pkm?.maxHp} HP</div>
          <XpBar xp={pkm?.xp||0} xpNeeded={pkm?.xpNeeded||100} width={126}/>
          <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:'#818CF8' }}>XP {pkm?.xp}/{pkm?.xpNeeded}</div>
        </div>
      </div>
      {/* Menú */}
      <div style={{ flex:1,display:'flex',flexDirection:'column' }}>
        {MENU.map((opt,i)=>{ const sel=i===state.lobbyMenuIndex; return (
          <div key={i} onClick={()=>!opt.disabled&&dispatch({type:acts[i]})}
            style={{ display:'flex',alignItems:'center',padding:'5px 10px',gap:6,
              background:sel?C.orange:'transparent',cursor:opt.disabled?'not-allowed':'pointer',
              opacity:opt.disabled?0.4:1,borderBottom:`1px solid ${C.border}` }}>
            <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:7,color:sel?'#000':C.orange,width:8 }}>{sel?'▶':''}</span>
            <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:6,color:sel?'#000':C.text,flex:1 }}>{opt.label}</span>
            <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:sel?'#3a2000':C.dim }}>{opt.sub}</span>
          </div>
        );})}
      </div>
      {state.exploreLog.length>0&&(
        <div style={{ padding:'3px 8px',borderTop:`1px solid ${C.border}`,fontFamily:'Press Start 2P,monospace',
          fontSize:5,color:C.dim,overflow:'hidden',whiteSpace:'nowrap',textOverflow:'ellipsis',flexShrink:0 }}>
          {state.exploreLog[state.exploreLog.length-1]}
        </div>
      )}
    </div>
  );
}

// ══════════════════════════════════════════════════════════════
//  EXPLORACIÓN
// ══════════════════════════════════════════════════════════════
function ExploreScreen({ state, dispatch }) {
  const pkm=state.pokemon[state.activePkmIndex];
  const sc=SCENARIOS[state.scenario]||SCENARIOS[0];
  const [bounce,setBounce]=useState(false);
  const timer=useRef(null);
  useEffect(()=>{ const iv=setInterval(()=>setBounce(b=>!b),600); return()=>clearInterval(iv); },[]);
  useEffect(()=>{
    if(!state.exploring||state.pendingEvolution) return;
    const go=()=>{ timer.current=setTimeout(()=>{ dispatch({type:'EXPLORE_EVENT'}); go(); },5000+Math.random()*5000); };
    go(); return()=>clearTimeout(timer.current);
  },[state.exploring,!!state.pendingEvolution]);
  return (
    <div style={{ width:240,height:282,overflow:'hidden',position:'relative',cursor:'pointer' }}
      onClick={()=>dispatch({type:'STOP_EXPLORE'})}>
      <ScenarioBg scenarioIdx={state.scenario}>
        <div style={{ position:'absolute',top:0,left:0,right:0,padding:'4px 8px',background:'rgba(0,0,0,0.55)',
          borderBottom:`1px solid ${sc.accent}`,display:'flex',justifyContent:'space-between',alignItems:'center',zIndex:10 }}>
          <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:6,color:sc.accent }}>{sc.name}</span>
          <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim }}>TAP=VOLVER</span>
        </div>
        <div style={{ position:'absolute',left:'50%',bottom:bounce?82:74,
          transform:'translateX(-50%)',transition:'bottom 0.5s ease-in-out',zIndex:5 }}>
          <img src={spriteAnimated(pkm?.id)} alt={pkm?.name}
            style={{ width:72,height:72,imageRendering:'pixelated' }}
            onError={e=>{ e.target.src=spriteStatic(pkm?.id); }}/>
        </div>
        {[...Array(4)].map((_,i)=>(
          <div key={i} style={{ position:'absolute',left:`${15+i*22}%`,top:`${35+(i%2)*15}%`,
            width:4,height:4,borderRadius:'50%',background:TYPE_COL[pkm?.type]||C.orange,opacity:0.6,
            animation:`float_${i} ${2+i*0.5}s infinite alternate ease-in-out`,zIndex:4 }}/>
        ))}
        <div style={{ position:'absolute',bottom:0,left:0,right:0,background:'rgba(0,0,0,0.85)',
          borderTop:`1px solid ${sc.accent}`,padding:'5px 8px',height:66,overflow:'hidden',zIndex:10 }}>
          {state.exploreLog.slice(-4).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.9,overflow:'hidden',textOverflow:'ellipsis',whiteSpace:'nowrap' }}>
              {i===arr.length-1?'▶ ':'  '}{line}
            </div>
          ))}
        </div>
      </ScenarioBg>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════
//  CAJA
// ══════════════════════════════════════════════════════════════
function BoxScreen({ state, dispatch }) {
  const [cursor,setCursor]=useState(0);
  const [slot,setSlot]=useState(0);
  const listRef=useRef(null);
  const now=Date.now();
  const total=state.pokemon.length;
  const team=getActiveTeamIndexes(state);
  const selectedSlot=Math.max(0,Math.min(slot,Math.max(0,team.length-1)));

  useEffect(()=>{
    const h=e=>{ e.preventDefault();
      setCursor(c=>{ const n=Math.max(0,Math.min(total-1,c+(e.deltaY>0?1:-1)));
        if(listRef.current) listRef.current.scrollTop=Math.max(0,n*48-84); return n; }); };
    window.addEventListener('wheel',h,{passive:false}); return()=>window.removeEventListener('wheel',h);
  },[total]);
  useEffect(()=>{ if(slot>=team.length&&team.length>0) setSlot(team.length-1); },[slot,team.length]);

  const ActionButton=({label,color,onClick,disabled=false})=>(
    <div onClick={e=>{ e.stopPropagation(); if(!disabled) onClick(); }}
      style={{ padding:'5px 5px',minWidth:32,textAlign:'center',cursor:disabled?'not-allowed':'pointer',
        fontFamily:'Press Start 2P,monospace',fontSize:4,color:disabled?C.dim:color,
        border:`1px solid ${disabled?C.border:color+'66'}`,borderRadius:3,opacity:disabled?0.45:1 }}>
      {label}
    </div>
  );

  return (
    <div style={{ width:240,height:282,background:C.bg,display:'flex',flexDirection:'column',overflow:'hidden' }}>
      <div style={{ padding:'5px 8px',background:C.panel,borderBottom:`1px solid ${C.orange}`,
        display:'flex',justifyContent:'space-between',alignItems:'center',flexShrink:0 }}>
        <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:7,color:C.orange }}>EQUIPO PKM</span>
        <span onClick={()=>dispatch({type:'CLOSE_BOX'})} style={{ fontFamily:'Press Start 2P,monospace',fontSize:7,color:C.dim,cursor:'pointer',padding:'2px 4px' }}>X</span>
      </div>

      <div style={{ display:'flex',gap:4,padding:'6px 6px 5px',borderBottom:`1px solid ${C.border}`,flexShrink:0 }}>
        {Array.from({length:ACTIVE_TEAM_SIZE},(_,s)=>{
          const idx=team[s];
          const p=state.pokemon[idx];
          const selected=s===selectedSlot;
          const lead=idx===state.activePkmIndex;
          return (
            <div key={s} onClick={()=>setSlot(s)}
              style={{ flex:1,height:50,borderRadius:4,cursor:'pointer',position:'relative',overflow:'hidden',
                border:`1px solid ${selected?C.orange:lead?C.green:C.border}`,
                background:selected?'rgba(255,107,0,0.12)':'rgba(255,255,255,0.03)',
                display:'flex',alignItems:'center',justifyContent:'center' }}>
              {p?(
                <>
                  <img src={spriteStatic(p.id)} alt={p.name}
                    style={{ width:34,height:34,imageRendering:'pixelated',filter:p.faintedAt&&now-p.faintedAt<COOLDOWN_MS?'grayscale(1)':'none' }}
                    onError={e=>{ e.target.style.display='none'; }}/>
                  <div style={{ position:'absolute',left:3,right:3,bottom:3,display:'flex',justifyContent:'space-between',alignItems:'center' }}>
                    <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:4,color:lead?C.green:C.dim }}>{lead?'ACT':`PKM${s+1}`}</span>
                    <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:4,color:C.text }}>L{p.level}</span>
                  </div>
                </>
              ):(
                <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:selected?C.orange:C.dim }}>VACIO</span>
              )}
            </div>
          );
        })}
      </div>

      <div ref={listRef} style={{ flex:1,overflowY:'auto',padding:4 }}>
        {total===0&&<div style={{ fontFamily:'Press Start 2P,monospace',fontSize:6,color:C.dim,textAlign:'center',marginTop:20 }}>Caja vacia</div>}
        {state.pokemon.map((p,i)=>{
          const fainted=p.faintedAt&&now-p.faintedAt<COOLDOWN_MS;
          const inTeam=team.includes(i);
          const isLead=i===state.activePkmIndex;
          const isCursor=i===cursor;
          const hrs=fainted?Math.ceil((COOLDOWN_MS-(now-p.faintedAt))/3600000):0;
          return (
            <div key={p.uid||i} onClick={()=>dispatch({type:'OPEN_STATS',index:i})}
              style={{ display:'flex',alignItems:'center',gap:6,padding:'4px 5px',marginBottom:3,borderRadius:4,
                background:isCursor?'rgba(255,107,0,0.1)':'transparent',cursor:'pointer',
                border:`1px solid ${isLead?C.green:inTeam?C.orange:isCursor?'#444':'transparent'}`,opacity:fainted?0.58:1 }}>
              <img src={spriteStatic(p.id)} alt={p.name}
                style={{ width:30,height:30,imageRendering:'pixelated',filter:fainted?'grayscale(1)':'none',flexShrink:0 }}
                onError={e=>{ e.target.style.display='none'; }}/>
              <div style={{ flex:1,minWidth:0 }}>
                <div style={{ display:'flex',alignItems:'center',gap:4,marginBottom:2 }}>
                  <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:6,color:C.text,whiteSpace:'nowrap',overflow:'hidden',textOverflow:'ellipsis' }}>{p.name}</span>
                  {isLead&&<span style={{ fontFamily:'Press Start 2P,monospace',fontSize:4,color:C.green }}>ACT</span>}
                  {!isLead&&inTeam&&<span style={{ fontFamily:'Press Start 2P,monospace',fontSize:4,color:C.orange }}>PKM</span>}
                  {EVOLUTIONS[p.id]&&p.level>=EVOLUTIONS[p.id].level&&<span style={{ fontFamily:'Press Start 2P,monospace',fontSize:4,color:C.yellow }}>EVO</span>}
                </div>
                <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim,marginBottom:2 }}>
                  LV{p.level} - {fainted?`${hrs}h`:`${p.hp}/${p.maxHp}HP`}
                </div>
                <HpBar hp={p.hp} maxHp={p.maxHp} width={92} height={4}/>
              </div>
              <div style={{ display:'flex',gap:3,flexShrink:0 }}>
                {fainted&&(state.inventory.revivals||0)>0?(
                  <>
                    <ActionButton label="REV" color={'#F97316'} onClick={()=>dispatch({type:'USE_REVIVE',index:i})}/>
                    {inTeam&&<ActionButton label="SAC" color={C.red} disabled={team.length<=1} onClick={()=>dispatch({type:'REMOVE_FROM_TEAM',index:i})}/>}
                  </>
                ):inTeam?(
                  <>
                    <ActionButton label="ACT" color={C.green} disabled={isLead||fainted||p.hp<=0} onClick={()=>dispatch({type:'SET_ACTIVE',index:i})}/>
                    <ActionButton label="SAC" color={C.red} disabled={team.length<=1} onClick={()=>dispatch({type:'REMOVE_FROM_TEAM',index:i})}/>
                  </>
                ):(team.length<ACTIVE_TEAM_SIZE?(
                  <ActionButton label="METER" color={C.orange} onClick={()=>dispatch({type:'ADD_TO_TEAM',index:i})}/>
                ):(
                  <ActionButton label="CAMB" color={C.blue} onClick={()=>dispatch({type:'SET_TEAM_SLOT',slot:selectedSlot,index:i})}/>
                ))}
              </div>
            </div>
          );
        })}
      </div>
      <div style={{ padding:'4px 8px',borderTop:`1px solid ${C.border}`,fontFamily:'Press Start 2P,monospace',
        fontSize:5,color:C.dim,display:'flex',justifyContent:'space-between',flexShrink:0 }}>
        <span>{team.length}/{ACTIVE_TEAM_SIZE} Equipo</span><span>{total}/{BOX_CAPACITY} Caja</span>
      </div>
    </div>
  );
}

function StatsScreen({ state, dispatch }) {
  const idx = state.statsTarget !== null && state.statsTarget !== undefined
    ? state.statsTarget : state.activePkmIndex;
  const p = state.pokemon[idx];
  const [confirmDelete,setConfirmDelete]=useState(false);
  if(!p) return null;

  const team=getActiveTeamIndexes(state);
  const inTeam=team.includes(idx);
  const isLead=idx===state.activePkmIndex;
  const canDelete=state.pokemon.length>1;
  const atk  = calcAtk(p.baseAtk||49, p.level);
  const def  = calcDef(p.baseDef||49, p.level);
  const spd  = calcSpd(p.baseSpd||45, p.level);
  const typeColor = TYPE_COL[p.type]||C.dim;
  const evo = EVOLUTIONS[p.id];

  const StatRow = ({label,val,max,color})=>(
    <div style={{ display:'flex',alignItems:'center',gap:6,marginBottom:4 }}>
      <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim,width:28,flexShrink:0 }}>{label}</div>
      <div style={{ flex:1,height:6,background:'#1a1a1a',borderRadius:2,overflow:'hidden',border:'1px solid #333' }}>
        <div style={{ width:`${Math.min(100,(val/max)*100)}%`,height:'100%',background:color,borderRadius:2,transition:'width 0.3s' }}/>
      </div>
      <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.text,width:24,textAlign:'right',flexShrink:0 }}>{val}</div>
    </div>
  );

  return (
    <div style={{ width:240,height:282,background:C.bg,display:'flex',flexDirection:'column',overflow:'hidden' }}>
      <div style={{ padding:'5px 8px',background:C.panel,borderBottom:`1px solid ${typeColor}`,
        display:'flex',justifyContent:'space-between',alignItems:'center',flexShrink:0 }}>
        <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:7,color:typeColor }}>STATS</span>
        <span onClick={()=>dispatch({type:'CLOSE_STATS'})} style={{ fontFamily:'Press Start 2P,monospace',fontSize:7,color:C.dim,cursor:'pointer',padding:'2px 4px' }}>✕</span>
      </div>

      <div style={{ display:'flex',alignItems:'center',gap:10,padding:'8px 12px',
        borderBottom:`1px solid ${C.border}`,flexShrink:0 }}>
        <img src={spriteAnimated(p.id)} alt={p.name}
          style={{ width:72,height:72,imageRendering:'pixelated' }}
          onError={e=>{ e.target.src=spriteStatic(p.id); }}/>
        <div style={{ flex:1 }}>
          <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:8,color:C.text,marginBottom:4 }}>{p.name}</div>
          <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim,marginBottom:4 }}>#{p.id.toString().padStart(3,'0')}</div>
          <TypeBadge type={p.type||'normal'}/>
          <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim,marginTop:5 }}>
            NIVEL <span style={{ color:C.orange }}>{p.level}</span>
          </div>
          <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:inTeam?C.orange:C.dim,marginTop:4 }}>
            {inTeam?(isLead?'LIDER':'EQUIPO PKM'):'CAJA'}
          </div>
        </div>
      </div>

      <div style={{ flex:1,padding:'10px 12px',overflowY:'auto' }}>
        <StatRow label="HP"  val={p.maxHp} max={400} color={C.green}/>
        <StatRow label="ATK" val={atk}     max={300} color={C.red}/>
        <StatRow label="DEF" val={def}     max={300} color={C.blue}/>
        <StatRow label="VEL" val={spd}     max={300} color={C.yellow}/>

        <div style={{ marginTop:8,borderTop:`1px solid ${C.border}`,paddingTop:8 }}>
          <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim,lineHeight:2.2 }}>
            <div>XP: <span style={{ color:'#818CF8' }}>{p.xp}/{p.xpNeeded}</span></div>
            <div>HP: <span style={{ color:C.green }}>{p.hp}/{p.maxHp}</span></div>
            {evo&&p.level>=evo.level&&<div style={{ color:C.yellow }}>★ LISTA PARA EVOLUCIONAR</div>}
            {evo&&p.level<evo.level&&<div>EVO: <span style={{ color:C.dim }}>{PNAMES[evo.to]} Lv{evo.level}</span></div>}
            {!evo&&<div style={{ color:C.dim }}>FORMA FINAL</div>}
          </div>
        </div>

        <XpBar xp={p.xp} xpNeeded={p.xpNeeded} width={200}/>
        <div onClick={()=>{ if(!canDelete) return; confirmDelete?dispatch({type:'DELETE_POKEMON',index:idx}):setConfirmDelete(true); }}
          style={{ marginTop:9,padding:'7px 0',textAlign:'center',cursor:canDelete?'pointer':'not-allowed',
            fontFamily:'Press Start 2P,monospace',fontSize:6,color:canDelete?C.red:C.dim,
            border:`1px solid ${canDelete?C.red+'66':C.border}`,borderRadius:3,
            background:confirmDelete?'rgba(239,68,68,0.18)':'transparent',opacity:canDelete?1:0.5 }}>
          {canDelete?(confirmDelete?'CONFIRMAR BORRAR':'BORRAR PKM'):'ULTIMO PKM'}
        </div>
      </div>
    </div>
  );
}

// ══════════════════════════════════════════════════════════════
//  INVENTARIO — tabs Items / Zonas / Medallas
// ══════════════════════════════════════════════════════════════
function InventoryScreen({ state, dispatch }) {
  const [tab,setTab]=useState('items');
  const [zoneCursor,setZoneCursor]=useState(state.scenario);
  const [showReset,setShowReset]=useState(false);
  const pkm=state.pokemon[state.activePkmIndex];
  const inv=state.inventory;
  const badges=state.badges||[];

  useEffect(()=>{
    const h=e=>{ e.preventDefault();
      if(tab==='zonas') setZoneCursor(c=>Math.max(0,Math.min(SCENARIOS.length-1,c+(e.deltaY>0?1:-1))));
    };
    window.addEventListener('wheel',h,{passive:false}); return()=>window.removeEventListener('wheel',h);
  },[tab]);

  const allItems=[
    {key:'pokeballs',  label:'Pokéball',   color:C.red,      desc:'x1.0 captura'},
    {key:'greatballs', label:'Superball',  color:C.blue,     desc:'x1.5 captura'},
    {key:'ultraballs', label:'Ultraball',  color:C.yellow,   desc:'x2.0 captura'},
    {key:'masterballs',label:'Masterball', color:'#A855F7',  desc:'100% captura'},
    {key:'berries',    label:'Bayas',      color:C.green,    desc:'+30 HP al usar'},
    {key:'revivals',   label:'Revivir',    color:'#F97316',  desc:'Suprime cooldown'},
  ];

  return (
    <div style={{ width:240,height:282,background:C.bg,display:'flex',flexDirection:'column',overflow:'hidden' }}>
      <div style={{ padding:'5px 8px',background:C.panel,borderBottom:`1px solid ${C.orange}`,
        display:'flex',justifyContent:'space-between',alignItems:'center',flexShrink:0 }}>
        <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:7,color:C.orange }}>MOCHILA</span>
        <span onClick={()=>dispatch({type:'CLOSE_INVENTORY'})} style={{ fontFamily:'Press Start 2P,monospace',fontSize:7,color:C.dim,cursor:'pointer',padding:'2px 4px' }}>✕</span>
      </div>

      {/* Tabs */}
      <div style={{ display:'flex',borderBottom:`1px solid ${C.border}`,flexShrink:0 }}>
        {['items','zonas','badges'].map(t=>(
          <div key={t} onClick={()=>setTab(t)} style={{ flex:1,padding:'5px 0',textAlign:'center',cursor:'pointer',
            fontFamily:'Press Start 2P,monospace',fontSize:5,color:tab===t?C.orange:C.dim,
            borderBottom:tab===t?`2px solid ${C.orange}`:'2px solid transparent',
            background:tab===t?'rgba(255,107,0,0.07)':'transparent' }}>
            {t==='badges'?'MEDALLAS':t.toUpperCase()}
          </div>
        ))}
      </div>

      {/* Items */}
      {tab==='items'&&(
        <div style={{ flex:1,padding:7,display:'flex',flexDirection:'column',gap:4,overflowY:'auto' }}>
          {allItems.map(item=>(
            <div key={item.key} style={{ display:'flex',alignItems:'center',gap:8,padding:'6px 8px',
              background:C.panel,borderRadius:4,border:`1px solid ${C.border}` }}>
              <div style={{ width:24,height:24,borderRadius:'50%',background:item.color,opacity:0.85,flexShrink:0,
                display:'flex',alignItems:'center',justifyContent:'center',fontFamily:'Press Start 2P,monospace',fontSize:8,color:'#000',fontWeight:'bold' }}>
                {(inv[item.key]||0)>9?'+':(inv[item.key]||0)}
              </div>
              <div>
                <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:6,color:C.text,marginBottom:2 }}>{item.label}</div>
                <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim }}>x{inv[item.key]||0} · {item.desc}</div>
              </div>
            </div>
          ))}
          {/* Borrar partida */}
          <div style={{ marginTop:6 }}>
            {!showReset?(
              <div onClick={()=>setShowReset(true)} style={{ padding:'6px 0',textAlign:'center',cursor:'pointer',
                fontFamily:'Press Start 2P,monospace',fontSize:6,color:C.red,
                border:`1px solid ${C.red}44`,borderRadius:3,background:`${C.red}10` }}>BORRAR PARTIDA</div>
            ):(
              <div style={{ padding:7,background:'#1a0000',border:`1px solid ${C.red}`,borderRadius:4 }}>
                <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:6,color:C.red,textAlign:'center',marginBottom:7,lineHeight:1.8 }}>
                  ¿SEGURO?<br/><span style={{ fontSize:5,color:C.dim }}>Se pierde todo</span>
                </div>
                <div style={{ display:'flex',gap:6 }}>
                  <div onClick={()=>{ dispatch({type:'RESET_GAME'}); setShowReset(false); }}
                    style={{ flex:1,padding:'6px 0',textAlign:'center',cursor:'pointer',
                      fontFamily:'Press Start 2P,monospace',fontSize:6,color:'#000',background:C.red,borderRadius:3 }}>
                    SÍ, BORRAR
                  </div>
                  <div onClick={()=>setShowReset(false)}
                    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 }}>CANCELAR</div>
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Zonas */}
      {tab==='zonas'&&(
        <div style={{ flex:1,display:'flex',flexDirection:'column',overflow:'hidden' }}>
          <div style={{ padding:'4px 8px',fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim,borderBottom:`1px solid ${C.border}`,flexShrink:0 }}>
            rueda=nav · tap=ir
          </div>
          <div style={{ flex:1,overflowY:'auto',padding:'3px 5px' }}>
            {SCENARIOS.map((s,i)=>{
              const isUnlocked=pkm&&pkm.level>=s.minLv;
              const isCurrent=state.scenario===i;
              const isCursor=zoneCursor===i;
              const gymDone=(state.defeatedGyms||[]).includes(i);
              return (
                <div key={s.id} onClick={()=>isUnlocked&&dispatch({type:'SET_SCENARIO',id:i})}
                  style={{ display:'flex',alignItems:'center',gap:6,padding:'5px 6px',marginBottom:2,
                    borderRadius:3,cursor:isUnlocked?'pointer':'not-allowed',
                    background:isCursor?(isUnlocked?`${s.accent}18`:'rgba(255,0,0,0.05)'):'transparent',
                    border:`1px solid ${isCurrent?s.accent:isCursor?'#333':'transparent'}`,opacity:isUnlocked?1:0.4 }}>
                  <div style={{ width:14,height:14,borderRadius:2,flexShrink:0,background:SCENARIO_BG[i],border:`1px solid ${s.accent}55` }}/>
                  <div style={{ flex:1,minWidth:0 }}>
                    <div style={{ display:'flex',alignItems:'center',gap:4 }}>
                      <span style={{ fontFamily:'Press Start 2P,monospace',fontSize:6,color:isCurrent?s.accent:isUnlocked?C.text:C.dim }}>{s.name}</span>
                      {isCurrent&&<span style={{ fontSize:5,fontFamily:'Press Start 2P,monospace',color:s.accent }}>◀</span>}
                      {gymDone&&<span style={{ fontSize:5,fontFamily:'Press Start 2P,monospace',color:C.yellow }}>✓</span>}
                    </div>
                    <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:C.dim,marginTop:1 }}>
                      {isUnlocked?`LV${s.minLv}+`:`LV${s.minLv} REQ`}
                    </div>
                  </div>
                  {isCursor&&isUnlocked&&!isCurrent&&<span style={{ fontFamily:'Press Start 2P,monospace',fontSize:5,color:s.accent,flexShrink:0 }}>IR▶</span>}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* Medallas */}
      {tab==='badges'&&(
        <div style={{ flex:1,padding:8,overflowY:'auto' }}>
          <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:6,color:C.orange,marginBottom:8 }}>
            {badges.length}/20 MEDALLAS
          </div>
          {badges.length===0&&(
            <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:6,color:C.dim,textAlign:'center',marginTop:16 }}>
              Derrota líderes<br/>de gimnasio
            </div>
          )}
          <div style={{ display:'flex',flexWrap:'wrap',gap:5 }}>
            {GYMS.map(g=>{
              const has=badges.includes(g.badge);
              return (
                <div key={g.id} style={{ display:'flex',flexDirection:'column',alignItems:'center',gap:2,
                  padding:'5px 4px',borderRadius:4,border:`1px solid ${has?g.color:'#222'}`,
                  background:has?`${g.color}18`:'transparent',opacity:has?1:0.35,
                  width:44 }}>
                  <div style={{ width:20,height:20,borderRadius:'50%',background:has?g.color:'#333',
                    display:'flex',alignItems:'center',justifyContent:'center',
                    fontSize:10 }}>{has?'★':'·'}</div>
                  <div style={{ fontFamily:'Press Start 2P,monospace',fontSize:4,color:has?g.color:C.dim,
                    textAlign:'center',lineHeight:1.4 }}>{g.badge}</div>
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window,{
  HpBar,XpBar,TypeBadge,ScenarioBg,SCENARIO_BG,
  SplashScreen,LobbyScreen,ExploreScreen,BoxScreen,InventoryScreen,StatsScreen,
  EvolutionOverlay,
});
})();
