// =============================================================
// BATTLE SYSTEM — turn-based vs NPC trainers
// 1. Trainer list
// 2. Team selection from your collection
// 3. Battle screen with attacks, switching, log
// 4. Victory / defeat
// =============================================================
const { useState: useBatState, useEffect: useBatEffect, useRef: useBatRef, useMemo: useBatMemo } = React;

function Battles({ state, setState, onBack }) {
  // sub-phase: list | team | fight | result
  const [phase, setPhase] = useBatState("list");
  const [trainer, setTrainer] = useBatState(null);
  const [team, setTeam] = useBatState([]);     // player team (pokemon objects)
  const [result, setResult] = useBatState(null); // {win, trainer, log}

  function selectTrainer(t) {
    setTrainer(t);
    setPhase("team");
  }
  function startBattle(playerTeam) {
    setTeam(playerTeam);
    setPhase("fight");
  }
  function finishBattle(winInfo) {
    setResult(winInfo);
    if (winInfo.win) {
      setState(prev => {
        const next = { ...prev };
        if (!next.badges.includes(trainer.id)) next.badges = [...next.badges, trainer.id];
        next.battlesWon = (next.battlesWon || 0) + 1;
        next.coins = (next.coins || 0) + trainer.reward * 10;
        return next;
      });
    }
    setPhase("result");
  }

  if (phase === "list")   return <TrainerList state={state} onPick={selectTrainer} onBack={onBack}/>;
  if (phase === "team")   return <TeamSelect state={state} trainer={trainer} onStart={startBattle} onBack={()=>setPhase("list")}/>;
  if (phase === "fight")  return <BattleScreen trainer={trainer} playerTeam={team} trainerName={state.trainerName || "ENTRENADOR"} onFinish={finishBattle}/>;
  if (phase === "result") return <BattleResult result={result} trainer={trainer} onBack={()=>setPhase("list")} onHub={onBack}/>;
  return null;
}

// =============================================================
// TRAINER LIST
// =============================================================
function TrainerList({ state, onPick, onBack }) {
  return (
    <div style={{minHeight:"100vh", background:"var(--bg-base)"}}>
      <div style={{padding:"20px 40px", borderBottom:"1px solid var(--border-hairline)", display:"flex", justifyContent:"space-between", alignItems:"center"}}>
        <button onClick={onBack} style={btnGhost()}>← VOLVER</button>
        <div style={{textAlign:"center"}}>
          <div className="eyebrow" style={{color:"var(--accent-orange)"}}>ARENA NPC</div>
          <div style={{fontFamily:"var(--font-sans)", fontWeight:700, fontSize:18, color:"#fff"}}>SELECCIONA ENTRENADOR</div>
        </div>
        <div style={{fontFamily:"var(--font-mono)", fontSize:12, color:"var(--fg-3)"}}>
          MEDALLAS: <span style={{color:"var(--accent-orange)", fontWeight:700}}>{state.badges.length}/{TRAINERS.length}</span>
        </div>
      </div>

      <div style={{padding:"32px 40px", display:"grid", gridTemplateColumns:"repeat(auto-fill, minmax(320px, 1fr))", gap:16, maxWidth:1400, margin:"0 auto"}}>
        {TRAINERS.map(t => {
          const earned = state.badges.includes(t.id);
          return (
            <div
              key={t.id}
              onClick={() => onPick(t)}
              style={{
                background: "linear-gradient(135deg, #161B22 0%, #0D1117 100%)",
                border: `1px solid ${earned ? "var(--accent-orange)" : "var(--border-hairline)"}`,
                borderRadius: 4,
                padding: 20,
                cursor:"pointer",
                position:"relative",
                boxShadow: earned ? "0 0 16px var(--accent-orange-glow)" : "var(--elev-offset-1)",
                transition:"all 200ms",
              }}
              onMouseEnter={e => e.currentTarget.style.transform="translateY(-2px)"}
              onMouseLeave={e => e.currentTarget.style.transform="none"}
            >
              {earned && (
                <div style={{
                  position:"absolute", top:12, right:12,
                  width:32, height:32, borderRadius:"50%",
                  background:"linear-gradient(135deg, var(--accent-orange), var(--accent-yellow))",
                  display:"flex", alignItems:"center", justifyContent:"center",
                  fontSize:16, boxShadow:"0 0 12px var(--accent-orange-glow)",
                }}>✓</div>
              )}

              <div style={{display:"flex", gap:14, alignItems:"center", marginBottom:14}}>
                <div style={{
                  width:64, height:64, borderRadius:2,
                  background:"var(--bg-inset)",
                  border:`1px solid ${earned ? "var(--accent-orange)" : "var(--border-solid)"}`,
                  display:"flex", alignItems:"center", justifyContent:"center",
                  fontSize:36,
                }}>{t.avatar}</div>
                <div style={{flex:1, minWidth:0}}>
                  <div className="eyebrow" style={{color: earned ? "var(--accent-orange)" : "var(--fg-4)"}}>{t.badge}</div>
                  <div style={{fontFamily:"var(--font-sans)", fontWeight:800, fontSize:22, color:"#fff", lineHeight:1.1}}>{t.name}</div>
                  <div style={{fontFamily:"var(--font-mono)", fontSize:11, color:"var(--fg-3)", marginTop:2}}>{t.title}</div>
                </div>
              </div>

              <div style={{fontFamily:"var(--font-mono)", fontSize:12, color:"var(--fg-3)", fontStyle:"italic", marginBottom:12, lineHeight:1.4, minHeight:34}}>
                "{t.quote}"
              </div>

              <div style={{display:"flex", justifyContent:"space-between", alignItems:"center", paddingTop:12, borderTop:"1px dashed var(--border-hairline)"}}>
                <div>
                  <div style={{fontFamily:"var(--font-mono)", fontSize:9, color:"var(--fg-4)", letterSpacing:"0.15em"}}>DIFICULTAD</div>
                  <div style={{display:"flex", gap:2, marginTop:3}}>
                    {Array.from({length:5}).map((_,i)=>(
                      <div key={i} style={{
                        width:14, height:14,
                        background: i < t.difficulty ? "var(--accent-orange)" : "var(--bg-inset)",
                        border:"1px solid var(--border-solid)",
                      }}/>
                    ))}
                  </div>
                </div>
                <div style={{display:"flex", gap:4}}>
                  {t.deck.map(id => {
                    const p = DEX_BY_ID[id];
                    return p ? (
                      <div key={id} style={{
                        width:32, height:32, borderRadius:2,
                        background: `linear-gradient(135deg, ${TYPE_INFO[p.types[0]].gradient[0]}33, ${TYPE_INFO[p.types[0]].gradient[1]}33)`,
                        border:`1px solid ${TYPE_INFO[p.types[0]].color}77`,
                        overflow:"hidden",
                      }}>
                        <img src={SPRITE(p.id)} style={{width:"100%", height:"100%", objectFit:"contain"}}/>
                      </div>
                    ) : null;
                  })}
                </div>
                <div style={{textAlign:"right"}}>
                  <div style={{fontFamily:"var(--font-mono)", fontSize:9, color:"var(--fg-4)", letterSpacing:"0.15em"}}>RECOMP.</div>
                  <div style={{fontFamily:"var(--font-mono)", fontSize:14, color:"var(--accent-yellow)", fontWeight:700}}>+{t.reward * 10}c</div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// =============================================================
// TEAM SELECT
// =============================================================
function TeamSelect({ state, trainer, onStart, onBack }) {
  const owned = useBatMemo(() => {
    let list = Object.keys(state.collection).map(id => DEX_BY_ID[+id]).filter(Boolean);
    // If no collection, grant starter team
    if (list.length === 0) {
      list = [DEX_BY_ID[4], DEX_BY_ID[7], DEX_BY_ID[1], DEX_BY_ID[25]];
    }
    return list.sort((a,b) => b.hp - a.hp);
  }, [state.collection]);

  const [selected, setSelected] = useBatState([]);
  const max = 4;

  function toggle(p) {
    if (selected.find(x => x.id === p.id)) setSelected(selected.filter(x => x.id !== p.id));
    else if (selected.length < max) setSelected([...selected, p]);
  }

  return (
    <div style={{minHeight:"100vh", background:"var(--bg-base)"}}>
      <div style={{padding:"20px 40px", borderBottom:"1px solid var(--border-hairline)", display:"flex", justifyContent:"space-between", alignItems:"center"}}>
        <button onClick={onBack} style={btnGhost()}>← CAMBIAR RIVAL</button>
        <div style={{textAlign:"center"}}>
          <div className="eyebrow" style={{color:"var(--accent-orange)"}}>BATALLA VS {trainer.name.toUpperCase()}</div>
          <div style={{fontFamily:"var(--font-sans)", fontWeight:700, fontSize:18, color:"#fff"}}>SELECCIONA TU EQUIPO (1–4)</div>
        </div>
        <div style={{fontFamily:"var(--font-mono)", fontSize:12, color:"var(--accent-cyan)"}}>{selected.length}/{max} SELECCIONADOS</div>
      </div>

      <div style={{padding:"24px 40px", display:"grid", gridTemplateColumns:"1fr 320px", gap:24, maxWidth:1500, margin:"0 auto"}}>
        <div>
          <div style={{fontFamily:"var(--font-mono)", fontSize:11, color:"var(--fg-3)", marginBottom:16, letterSpacing:"0.1em"}}>
            TU COLECCIÓN · {owned.length} POKÉMON DISPONIBLES
          </div>
          <div style={{display:"grid", gridTemplateColumns:"repeat(auto-fill, minmax(170px, 1fr))", gap:14}}>
            {owned.map(p => {
              const isSel = selected.find(x => x.id === p.id);
              return (
                <div key={p.id} style={{position:"relative"}}>
                  {isSel && (
                    <div style={{
                      position:"absolute", top:-6, left:-6, zIndex:6,
                      width:28, height:28, borderRadius:"50%",
                      background:"var(--accent-lime)", color:"#0a0d12",
                      display:"flex", alignItems:"center", justifyContent:"center",
                      fontWeight:900, fontSize:14,
                      boxShadow:"0 0 12px var(--accent-lime-glow)",
                    }}>{selected.indexOf(isSel) + 1}</div>
                  )}
                  <PokemonCard
                    pokemon={p}
                    size="sm"
                    onClick={() => toggle(p)}
                    glow={!!isSel}
                  />
                </div>
              );
            })}
          </div>
        </div>

        {/* Side panel */}
        <div style={{
          position:"sticky", top:24, alignSelf:"start",
          background:"var(--bg-surface)",
          border:"1px solid var(--border-hairline)",
          borderRadius:2,
          padding:20,
        }}>
          <div className="eyebrow" style={{color:"var(--accent-orange)"}}>RIVAL</div>
          <div style={{display:"flex", gap:12, alignItems:"center", margin:"8px 0 16px"}}>
            <div style={{fontSize:36}}>{trainer.avatar}</div>
            <div>
              <div style={{fontFamily:"var(--font-sans)", fontWeight:800, fontSize:18, color:"#fff"}}>{trainer.name}</div>
              <div style={{fontFamily:"var(--font-mono)", fontSize:10, color:"var(--fg-3)"}}>{trainer.title}</div>
            </div>
          </div>

          <div className="eyebrow" style={{marginBottom:8}}>SU EQUIPO</div>
          <div style={{display:"flex", flexDirection:"column", gap:6, marginBottom:16}}>
            {trainer.deck.map(id => {
              const p = DEX_BY_ID[id];
              return p ? (
                <div key={id} style={{display:"flex", alignItems:"center", gap:8, padding:"6px 8px", background:"var(--bg-inset)", borderRadius:2}}>
                  <img src={SPRITE(p.id)} style={{width:32, height:32, objectFit:"contain"}}/>
                  <div style={{flex:1}}>
                    <div style={{fontFamily:"var(--font-sans)", fontSize:13, fontWeight:600, color:"#fff"}}>{p.name}</div>
                    <div style={{fontFamily:"var(--font-mono)", fontSize:10, color:"var(--fg-3)"}}>{p.hp} PS · {RARITY[p.rarity].name}</div>
                  </div>
                  <TypeRibbon types={p.types}/>
                </div>
              ) : null;
            })}
          </div>

          <div className="eyebrow" style={{marginBottom:8}}>TU EQUIPO</div>
          <div style={{display:"flex", flexDirection:"column", gap:6, marginBottom:20, minHeight: 60}}>
            {selected.length === 0 && (
              <div style={{fontFamily:"var(--font-mono)", fontSize:11, color:"var(--fg-4)", padding:"12px 0", textAlign:"center", border:"1px dashed var(--border-hairline)"}}>
                ▸ ELIGE 1–4 POKÉMON
              </div>
            )}
            {selected.map((p,i) => (
              <div key={p.id} style={{display:"flex", alignItems:"center", gap:8, padding:"6px 8px", background:"var(--bg-inset)", borderRadius:2, borderLeft: `2px solid ${TYPE_INFO[p.types[0]].color}`}}>
                <span style={{fontFamily:"var(--font-mono)", fontSize:10, color:"var(--accent-lime)", fontWeight:700, width:14}}>{i+1}.</span>
                <img src={SPRITE(p.id)} style={{width:28, height:28, objectFit:"contain"}}/>
                <div style={{flex:1, fontFamily:"var(--font-sans)", fontSize:13, fontWeight:600, color:"#fff"}}>{p.name}</div>
                <button onClick={() => setSelected(selected.filter(x=>x.id!==p.id))} style={{background:"transparent", border:"none", color:"var(--fg-4)", cursor:"pointer", fontSize:14}}>×</button>
              </div>
            ))}
          </div>

          <button
            onClick={() => onStart(selected)}
            disabled={selected.length === 0}
            style={selected.length === 0 ? {...btnPrimary(true), width:"100%"} : {...btnPrimary(false), width:"100%"}}
          >
            ▶ INICIAR COMBATE
          </button>
          {Object.keys(state.collection).length === 0 && (
            <div style={{fontFamily:"var(--font-mono)", fontSize:10, color:"var(--fg-4)", marginTop:10, textAlign:"center", lineHeight:1.4}}>
              ⓘ Recibes un equipo prestado de prueba si aún no tienes colección
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// =============================================================
// BATTLE SCREEN — actual turn-based combat
// =============================================================
function BattleScreen({ trainer, playerTeam, trainerName, onFinish }) {
  // Each combatant: {p: pokemon, hp: currentHP, idx}
  const mkUnit = (p, idx) => ({ p, hp: p.hp, idx });

  const [player, setPlayer] = useBatState(() => playerTeam.map(mkUnit));
  const [enemy, setEnemy] = useBatState(() => trainer.deck.map(id => DEX_BY_ID[id]).filter(Boolean).map(mkUnit));
  const [activeP, setActiveP] = useBatState(0);
  const [activeE, setActiveE] = useBatState(0);
  const [turn, setTurn] = useBatState("player"); // player | enemy
  const [turnNum, setTurnNum] = useBatState(1);
  const [log, setLog] = useBatState([
    { kind:"system", text:`¡${trainer.name} reta a un combate!` },
    { kind:"system", text:`Va con ${DEX_BY_ID[trainer.deck[0]]?.name.toUpperCase()}.` },
  ]);
  const [busy, setBusy] = useBatState(false);
  const [attackFlash, setAttackFlash] = useBatState(null); // "player" | "enemy" | null
  const [hitFlash, setHitFlash] = useBatState(null);
  const [shake, setShake] = useBatState(null);

  const playerUnit = player[activeP];
  const enemyUnit = enemy[activeE];

  function pushLog(entry) { setLog(l => [...l, entry]); }

  // ---- effects ----
  function performAttack(attacker, defender, attack, side) {
    return new Promise(resolve => {
      setBusy(true);
      setAttackFlash(side);
      const dmg = GameEngine.applyEffectiveness(attacker.p.types[0], defender.p, attack.dmg);
      const isWeak = dmg > attack.dmg;
      pushLog({ kind: side, text: `${attacker.p.name.toUpperCase()} usa ${attack.name}!` });

      setTimeout(() => {
        setAttackFlash(null);
        setHitFlash(side === "player" ? "enemy" : "player");
        setShake(side === "player" ? "enemy" : "player");
        if (attack.dmg > 0) {
          pushLog({ kind:"dmg", text: `${defender.p.name} recibe ${dmg} de daño${isWeak ? " (¡SUPER EFECTIVO! ×2)" : ""}.` });
          if (side === "player") {
            setEnemy(prev => prev.map((u,i) => i === activeE ? {...u, hp: Math.max(0, u.hp - dmg)} : u));
          } else {
            setPlayer(prev => prev.map((u,i) => i === activeP ? {...u, hp: Math.max(0, u.hp - dmg)} : u));
          }
        } else if (attack.note) {
          if (attack.note.includes("Cura")) {
            const heal = parseInt(attack.note.match(/\d+/)?.[0] || "0");
            if (side === "player") setPlayer(p => p.map((u,i) => i === activeP ? {...u, hp: Math.min(u.p.hp, u.hp + heal)} : u));
            else setEnemy(p => p.map((u,i) => i === activeE ? {...u, hp: Math.min(u.p.hp, u.hp + heal)} : u));
            pushLog({ kind:"heal", text: `${attacker.p.name} recupera ${heal} PS.` });
          } else {
            pushLog({ kind:"effect", text: attack.note });
          }
        }
        setTimeout(() => {
          setHitFlash(null);
          setShake(null);
          resolve();
        }, 380);
      }, 520);
    });
  }

  async function playerAttack(attack) {
    if (busy || turn !== "player") return;
    await performAttack(playerUnit, enemyUnit, attack, "player");
    // Check KO
    const newEnemyHP = Math.max(0, enemyUnit.hp - GameEngine.applyEffectiveness(playerUnit.p.types[0], enemyUnit.p, attack.dmg));
    if (newEnemyHP <= 0) {
      pushLog({ kind:"ko", text:`¡${enemyUnit.p.name.toUpperCase()} fue debilitado!` });
      await sleep(700);
      // Find next enemy
      const nextE = enemy.findIndex((u, i) => i !== activeE && (i === activeE ? false : true) && (function(){ // need updated hp
        // we use enemy state directly; but state may lag. Use predicted.
        return u.hp > 0;
      })());
      // Compute fresh next using post-damage values
      const updated = enemy.map((u,i)=> i===activeE ? {...u, hp:0} : u);
      const next = updated.findIndex(u => u.hp > 0);
      if (next === -1) {
        onFinish({ win:true, log });
        return;
      }
      setActiveE(next);
      pushLog({ kind:"system", text:`${trainer.name} envía a ${updated[next].p.name.toUpperCase()}.` });
      setBusy(false);
      setTurn("enemy");
      setTimeout(enemyTurn, 800);
      return;
    }
    setBusy(false);
    setTurn("enemy");
    setTimeout(enemyTurn, 700);
  }

  function playerSwitch(toIdx) {
    if (busy || turn !== "player") return;
    if (toIdx === activeP || player[toIdx].hp <= 0) return;
    pushLog({ kind:"system", text:`¡Vuelve, ${playerUnit.p.name.toUpperCase()}! ¡Adelante ${player[toIdx].p.name.toUpperCase()}!` });
    setActiveP(toIdx);
    setTurn("enemy");
    setTimeout(enemyTurn, 700);
  }

  async function enemyTurn() {
    const e = enemy[activeE];
    if (!e || e.hp <= 0) { setBusy(false); setTurn("player"); return; }
    const atk = GameEngine.aiPickAttack(e.p, turnNum);
    await performAttack(e, player[activeP], atk, "enemy");
    // Check player KO
    const dmg = GameEngine.applyEffectiveness(e.p.types[0], player[activeP].p, atk.dmg);
    const newHP = Math.max(0, player[activeP].hp - dmg);
    if (newHP <= 0) {
      pushLog({ kind:"ko", text:`¡Tu ${player[activeP].p.name.toUpperCase()} fue debilitado!` });
      await sleep(700);
      const updated = player.map((u,i)=> i===activeP ? {...u, hp:0} : u);
      const next = updated.findIndex(u => u.hp > 0);
      if (next === -1) {
        onFinish({ win:false, log });
        return;
      }
      setActiveP(next);
      pushLog({ kind:"system", text:`¡Adelante, ${updated[next].p.name.toUpperCase()}!` });
    }
    setTurnNum(t => t + 1);
    setBusy(false);
    setTurn("player");
  }

  function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }

  const playerInfo = TYPE_INFO[playerUnit.p.types[0]];
  const enemyInfo = TYPE_INFO[enemyUnit.p.types[0]];

  return (
    <div style={{
      minHeight:"100vh",
      background: `
        linear-gradient(180deg, rgba(249,85,135,0.05) 0%, transparent 30%, transparent 70%, rgba(0,240,255,0.05) 100%),
        var(--bg-base)
      `,
      display:"flex", flexDirection:"column",
      position:"relative", overflow:"hidden",
    }}>
      <style>{`
        @keyframes shakeIt { 0%,100%{transform:translateX(0)} 25%{transform:translateX(-8px) rotate(-1deg)} 75%{transform:translateX(8px) rotate(1deg)} }
        @keyframes attackPulse { 0%{transform:translateY(0) scale(1)} 50%{transform:translateY(-12px) scale(1.05)} 100%{transform:translateY(0) scale(1)} }
        @keyframes hitFlash { 0%,100%{filter:none} 50%{filter:brightness(2) hue-rotate(20deg)} }
        @keyframes damageNumber { 0%{transform:translateY(0); opacity:1} 100%{transform:translateY(-60px); opacity:0} }
      `}</style>

      {/* Top bar */}
      <div style={{display:"flex", justifyContent:"space-between", padding:"12px 24px", borderBottom:"1px solid var(--border-hairline)", fontFamily:"var(--font-mono)", fontSize:11, color:"var(--fg-3)", letterSpacing:"0.1em"}}>
        <span>COMBATE · TURNO {turnNum} · {turn === "player" ? <span style={{color:"var(--accent-cyan)"}}>TU TURNO</span> : <span style={{color:"var(--accent-orange)"}}>RIVAL ACTÚA</span>}</span>
        <span>VS {trainer.name.toUpperCase()}</span>
      </div>

      {/* Enemy side */}
      <div style={{padding:"24px 40px", display:"flex", justifyContent:"space-between", alignItems:"flex-start", gap:24}}>
        {/* Enemy bench */}
        <div style={{display:"flex", flexDirection:"column", gap:6}}>
          <div className="eyebrow" style={{color:"var(--accent-orange)"}}>BANCA RIVAL</div>
          <div style={{display:"flex", gap:8}}>
            {enemy.map((u,i) => i === activeE ? null : (
              <BenchSlot key={i} unit={u}/>
            ))}
          </div>
        </div>
        {/* Enemy active */}
        <ActiveCombatant
          unit={enemyUnit}
          side="enemy"
          isAttacking={attackFlash === "enemy"}
          isHit={hitFlash === "enemy"}
          shake={shake === "enemy"}
          trainerName={trainer.name}
          trainerAvatar={trainer.avatar}
        />
      </div>

      {/* Center log */}
      <div style={{
        flex:1,
        margin:"0 40px",
        background:"var(--bg-inset)",
        border:"1px solid var(--border-hairline)",
        borderRadius:2,
        padding:16,
        display:"flex", flexDirection:"column-reverse",
        gap:6, overflowY:"auto",
        maxHeight: 160, minHeight: 100,
        fontFamily:"var(--font-mono)", fontSize:12, lineHeight:1.5,
      }}>
        {[...log].reverse().slice(0, 30).map((e, i) => {
          const color =
            e.kind === "player" ? "var(--accent-cyan)" :
            e.kind === "enemy"  ? "var(--accent-orange)" :
            e.kind === "dmg"    ? "var(--accent-yellow)" :
            e.kind === "ko"     ? "var(--accent-red)" :
            e.kind === "heal"   ? "var(--accent-lime)" :
            "var(--fg-3)";
          const prefix =
            e.kind === "player" ? "▸ TÚ" :
            e.kind === "enemy"  ? "◂ RIVAL" :
            e.kind === "dmg"    ? "✦ DMG" :
            e.kind === "ko"     ? "✕ KO" :
            e.kind === "heal"   ? "+ HEAL" :
            "·  LOG";
          return (
            <div key={log.length - i} style={{color, opacity: i === 0 ? 1 : Math.max(0.3, 1 - i*0.08)}}>
              <span style={{color:"var(--fg-4)", marginRight:8}}>{prefix}</span>{e.text}
            </div>
          );
        })}
      </div>

      {/* Player side */}
      <div style={{padding:"24px 40px", display:"flex", justifyContent:"space-between", alignItems:"flex-end", gap:24}}>
        <ActiveCombatant
          unit={playerUnit}
          side="player"
          isAttacking={attackFlash === "player"}
          isHit={hitFlash === "player"}
          shake={shake === "player"}
          trainerName={trainerName}
          trainerAvatar="🎮"
        />
        <div style={{display:"flex", flexDirection:"column", gap:6, alignItems:"flex-end"}}>
          <div className="eyebrow" style={{color:"var(--accent-cyan)"}}>TU BANCA · click para cambiar</div>
          <div style={{display:"flex", gap:8}}>
            {player.map((u,i) => i === activeP ? null : (
              <BenchSlot key={i} unit={u} clickable={turn==="player" && !busy && u.hp > 0} onClick={() => playerSwitch(i)}/>
            ))}
          </div>
        </div>
      </div>

      {/* Action bar */}
      <div style={{padding:"16px 40px 24px", borderTop:"1px solid var(--border-hairline)", background:"var(--bg-surface)"}}>
        <div style={{display:"flex", gap:12, alignItems:"center", justifyContent:"space-between"}}>
          <div style={{display:"flex", gap:12, flex:1}}>
            {playerUnit.p.attacks.map((atk, i) => {
              const projected = GameEngine.applyEffectiveness(playerUnit.p.types[0], enemyUnit.p, atk.dmg);
              const isWeak = projected > atk.dmg;
              return (
                <button
                  key={i}
                  onClick={() => playerAttack(atk)}
                  disabled={busy || turn !== "player"}
                  style={{
                    flex:1,
                    fontFamily:"var(--font-sans)",
                    background: "linear-gradient(180deg, var(--bg-inset), #050810)",
                    border: `1px solid ${(busy || turn!=="player") ? "var(--border-hairline)" : (isWeak ? "var(--accent-yellow)" : playerInfo.color)}`,
                    color:"#fff",
                    padding:"14px 18px",
                    borderRadius:2,
                    cursor: (busy || turn!=="player") ? "not-allowed" : "pointer",
                    opacity: (busy || turn!=="player") ? 0.5 : 1,
                    textAlign:"left",
                    boxShadow: !busy && turn==="player" && !isWeak ? `inset 0 0 0 1px ${playerInfo.color}33` : "none",
                    transition:"all 150ms",
                  }}
                >
                  <div style={{display:"flex", justifyContent:"space-between", alignItems:"flex-start", gap:8}}>
                    <div style={{flex:1, minWidth:0}}>
                      <div style={{display:"flex", gap:3, marginBottom:4}}>
                        {atk.cost.map((c,j) => <EnergyChip key={j} type={c} size={14}/>)}
                      </div>
                      <div style={{fontWeight:700, fontSize:15}}>{atk.name}</div>
                      {atk.note && <div style={{fontFamily:"var(--font-mono)", fontSize:10, color:"var(--fg-3)", marginTop:2}}>{atk.note}</div>}
                    </div>
                    <div style={{textAlign:"right"}}>
                      <div style={{fontWeight:900, fontSize:24, color: isWeak ? "var(--accent-yellow)" : "#fff", lineHeight:1}}>
                        {projected > 0 ? projected : "—"}
                      </div>
                      {isWeak && <div style={{fontFamily:"var(--font-mono)", fontSize:9, color:"var(--accent-yellow)", letterSpacing:"0.1em"}}>×2 DÉBIL</div>}
                    </div>
                  </div>
                </button>
              );
            })}
          </div>
          <button onClick={() => onFinish({ win:false, forfeit:true, log })} style={{...btnGhost(), border:"1px solid var(--accent-red)", color:"var(--accent-red)"}}>
            HUIR
          </button>
        </div>
      </div>
    </div>
  );
}

// Active combatant card with HP bar + image
function ActiveCombatant({ unit, side, isAttacking, isHit, shake, trainerName, trainerAvatar }) {
  const info = TYPE_INFO[unit.p.types[0]];
  const hpPct = (unit.hp / unit.p.hp) * 100;
  const hpColor = hpPct > 50 ? "var(--accent-lime)" : hpPct > 20 ? "var(--accent-yellow)" : "var(--accent-red)";

  return (
    <div style={{
      flex:1, maxWidth: 520, minWidth: 360,
      display:"flex", flexDirection: side === "enemy" ? "row" : "row-reverse", gap:16, alignItems:"center",
      animation: shake ? "shakeIt 320ms" : "none",
    }}>
      {/* Mini trainer + nameplate */}
      <div style={{
        display:"flex", flexDirection:"column", gap:6,
        textAlign: side === "enemy" ? "left" : "right",
        minWidth: 140,
      }}>
        <div style={{display:"flex", alignItems:"center", gap:8, flexDirection: side === "enemy" ? "row" : "row-reverse"}}>
          <div style={{fontSize:22}}>{trainerAvatar}</div>
          <div>
            <div className="eyebrow" style={{color: side === "enemy" ? "var(--accent-orange)" : "var(--accent-cyan)", fontSize: 9}}>{trainerName.toUpperCase()}</div>
            <div style={{fontFamily:"var(--font-sans)", fontSize:20, fontWeight:800, color:"#fff", letterSpacing:"0.05em", textTransform:"uppercase"}}>{unit.p.name}</div>
          </div>
        </div>
        <div style={{display:"flex", gap:6, alignItems:"center", flexDirection: side === "enemy" ? "row" : "row-reverse"}}>
          <TypeRibbon types={unit.p.types}/>
          <span style={{fontFamily:"var(--font-mono)", fontSize:11, color:"var(--fg-3)", letterSpacing:"0.05em"}}>
            #{String(unit.p.id).padStart(3,"0")}
          </span>
        </div>
        {/* HP bar */}
        <div style={{display:"flex", alignItems:"center", gap:6, flexDirection: side === "enemy" ? "row" : "row-reverse"}}>
          <span style={{fontFamily:"var(--font-mono)", fontSize:10, color:"var(--fg-4)"}}>PS</span>
          <div style={{flex:1, height:14, background:"var(--bg-inset)", border:"1px solid var(--border-solid)", borderRadius:1, overflow:"hidden", position:"relative"}}>
            <div style={{
              height:"100%", width: `${hpPct}%`,
              background: `linear-gradient(90deg, ${hpColor}, ${hpColor}AA)`,
              boxShadow: `0 0 8px ${hpColor}88`,
              transition: "width 380ms cubic-bezier(0.16,1,0.3,1)",
            }}/>
            {/* HP segments */}
            {Array.from({length: Math.floor(unit.p.hp/30)}).map((_,i) => (
              <div key={i} style={{position:"absolute", top:0, bottom:0, left:`${(i+1) * (100 / (unit.p.hp/30))}%`, width:1, background:"rgba(0,0,0,0.4)"}}/>
            ))}
          </div>
          <span style={{fontFamily:"var(--font-mono)", fontSize:13, fontWeight:700, color: hpColor, minWidth: 60, textAlign: side === "enemy" ? "left" : "right"}}>
            {unit.hp}/{unit.p.hp}
          </span>
        </div>
      </div>

      {/* Big sprite */}
      <div style={{
        position:"relative",
        width: 200, height: 200,
        display:"flex", alignItems:"center", justifyContent:"center",
        animation: isAttacking ? "attackPulse 520ms cubic-bezier(0.16,1,0.3,1)" : (isHit ? "hitFlash 380ms" : "none"),
      }}>
        {/* Platform */}
        <div style={{
          position:"absolute", bottom: 0, left:"50%", transform:"translateX(-50%)",
          width: 180, height: 36,
          borderRadius:"50%",
          background: `radial-gradient(ellipse, ${info.glow} 0%, transparent 70%)`,
        }}/>
        <div style={{
          position:"absolute", bottom: 8, left:"50%", transform:"translateX(-50%) scaleY(0.4)",
          width: 140, height: 30,
          borderRadius:"50%",
          background:"rgba(0,0,0,0.55)",
          filter:"blur(8px)",
        }}/>
        <img
          src={SPRITE(unit.p.id)}
          alt={unit.p.name}
          style={{
            maxWidth:"100%", maxHeight:"95%",
            objectFit:"contain",
            filter: `drop-shadow(0 6px 10px rgba(0,0,0,0.6)) drop-shadow(0 0 18px ${info.glow})`,
            transform: side === "enemy" ? "scaleX(-1)" : "none",
            opacity: unit.hp <= 0 ? 0.25 : 1,
            transition: "opacity 400ms",
          }}
        />
      </div>
    </div>
  );
}

function BenchSlot({ unit, onClick, clickable }) {
  const info = TYPE_INFO[unit.p.types[0]];
  const hpPct = (unit.hp / unit.p.hp) * 100;
  const dead = unit.hp <= 0;
  return (
    <div
      onClick={clickable ? onClick : undefined}
      style={{
        width: 70, height: 90,
        borderRadius: 2,
        background: `linear-gradient(180deg, ${info.gradient[0]}22, ${info.gradient[1]}22)`,
        border: `1px solid ${clickable ? info.color : (dead ? "var(--accent-red)" : "var(--border-solid)")}`,
        padding: 4, display:"flex", flexDirection:"column",
        cursor: clickable ? "pointer" : "default",
        opacity: dead ? 0.4 : 1,
        position:"relative",
        boxShadow: clickable ? `0 0 8px ${info.glow}` : "none",
        transition:"all 150ms",
      }}>
      <div style={{
        flex:1, display:"flex", alignItems:"center", justifyContent:"center",
        background:"var(--bg-inset)", borderRadius:1, overflow:"hidden", position:"relative",
      }}>
        <img src={SPRITE(unit.p.id)} style={{maxWidth:"100%", maxHeight:"100%", filter: dead ? "grayscale(1)" : "none"}}/>
      </div>
      <div style={{marginTop:3, height:5, background:"var(--bg-inset)", borderRadius:1, overflow:"hidden"}}>
        <div style={{width:`${hpPct}%`, height:"100%", background: hpPct > 50 ? "var(--accent-lime)" : hpPct > 20 ? "var(--accent-yellow)" : "var(--accent-red)"}}/>
      </div>
      {dead && <div style={{position:"absolute", top:"40%", left:"50%", transform:"translate(-50%,-50%)", color:"var(--accent-red)", fontWeight:900, fontSize:20}}>✕</div>}
    </div>
  );
}

// =============================================================
// BATTLE RESULT
// =============================================================
function BattleResult({ result, trainer, onBack, onHub }) {
  const win = result.win;
  return (
    <div style={{
      minHeight:"100vh",
      background: `radial-gradient(ellipse at 50% 30%, ${win ? "rgba(57,255,20,0.15)" : "rgba(255,45,85,0.12)"}, transparent 60%), var(--bg-base)`,
      display:"flex", flexDirection:"column", alignItems:"center", justifyContent:"center",
      padding: 40, gap: 32,
    }}>
      <div className="eyebrow" style={{color: win ? "var(--accent-lime)" : "var(--accent-red)", fontSize:14}}>
        ─── RESULTADO DEL COMBATE ───
      </div>
      <h1 style={{
        fontFamily:"var(--font-sans)", fontWeight:900,
        fontSize: 120, color: "#fff", letterSpacing:"-0.04em", lineHeight:1, margin:0,
        textShadow: win ? "0 0 60px var(--accent-lime-glow)" : "0 0 60px rgba(255,45,85,0.4)",
      }}>
        {win ? "VICTORIA" : "DERROTA"}
      </h1>
      <div style={{display:"flex", alignItems:"center", gap:24, padding:"20px 32px", background:"var(--bg-surface)", border:`1px solid ${win ? "var(--accent-lime)" : "var(--accent-red)"}`, borderRadius:2}}>
        <div style={{fontSize:48}}>{trainer.avatar}</div>
        <div>
          <div style={{fontFamily:"var(--font-sans)", fontWeight:700, fontSize:24, color:"#fff"}}>{trainer.name}</div>
          <div style={{fontFamily:"var(--font-mono)", fontSize:12, color:"var(--fg-3)"}}>{trainer.title}</div>
        </div>
      </div>

      {win ? (
        <div style={{display:"flex", flexDirection:"column", alignItems:"center", gap:12}}>
          <div style={{
            width:80, height:80, borderRadius:"50%",
            background:"linear-gradient(135deg, var(--accent-orange), var(--accent-yellow))",
            border:"3px solid #fff",
            display:"flex", alignItems:"center", justifyContent:"center",
            fontSize:32,
            boxShadow:"0 0 32px var(--accent-orange-glow)",
          }}>{trainer.avatar}</div>
          <div style={{fontFamily:"var(--font-mono)", fontSize:14, color:"var(--accent-orange)", letterSpacing:"0.2em"}}>MEDALLA OBTENIDA</div>
          <div style={{fontFamily:"var(--font-sans)", fontWeight:700, fontSize:20, color:"#fff"}}>{trainer.badge}</div>
          <div style={{fontFamily:"var(--font-mono)", fontSize:13, color:"var(--accent-yellow)"}}>+{trainer.reward * 10} Pokécoins</div>
        </div>
      ) : (
        <div style={{fontFamily:"var(--font-mono)", fontSize:14, color:"var(--fg-3)", maxWidth: 400, textAlign:"center", lineHeight:1.6}}>
          La derrota es maestra. Vuelve cuando tengas mejores cartas. Abre más sobres y prueba otra vez.
        </div>
      )}

      <div style={{display:"flex", gap:12, marginTop:12}}>
        <button onClick={onBack} style={btnPrimary(false)}>↻ ELEGIR OTRO RIVAL</button>
        <button onClick={onHub} style={btnGhost()}>← VOLVER AL HUB</button>
      </div>
    </div>
  );
}

window.Battles = Battles;
