// =============================================================================
// BATTLE — Top Trumps duel vs Champion
// =============================================================================
const { useState } = React;

function BattleScreen({ state, actions, championId }) {
  const champion = window.GAME_DATA.CHAMPIONS.find(c => c.id === championId);
  const owned = state.collection;
  const { CARDS:BC, STATS:BS, getCard, RARITIES:BR } = window.GAME_DATA;
  const ownedCards = BC.filter(c => owned[c.id]);

  // Phases: deck-pick → playing → done
  const [phase, setPhase] = useState('deck-pick');
  const [yourDeck, setYourDeck] = useState([]); // card ids
  const [oppDeck, setOppDeck] = useState(champion.deck.slice());
  const [round, setRound] = useState(0); // 0..4
  const [yourScore, setYourScore] = useState(0);
  const [oppScore, setOppScore] = useState(0);
  const [yourCardRevealed, setYourCardRevealed] = useState(false);
  const [oppCardRevealed, setOppCardRevealed] = useState(false);
  const [selectedStat, setSelectedStat] = useState(null);
  const [roundResult, setRoundResult] = useState(null); // 'win' | 'lose' | 'draw'
  const [matchResult, setMatchResult] = useState(null); // 'win' | 'lose'
  const [history, setHistory] = useState([]);

  if (ownedCards.length < 5) {
    return (
      <div className="page" style={{display:'grid', placeItems:'center', minHeight:'70vh'}}>
        <div className="panel" style={{padding:'48px', maxWidth:'520px', textAlign:'center'}}>
          <PanelCorners color="var(--accent-orange)"/>
          <div style={{fontFamily:'var(--font-mono)', fontSize:'11px', color:'var(--accent-orange)', textTransform:'uppercase', letterSpacing:'0.12em', marginBottom:'12px'}}>
            ◈ MAZO INCOMPLETO
          </div>
          <div style={{fontFamily:'var(--font-sans)', fontWeight:700, fontSize:'32px', color:'var(--fg-1)', marginBottom:'12px', letterSpacing:'-0.02em'}}>
            NECESITAS 5 CARTAS
          </div>
          <div style={{fontFamily:'var(--font-mono)', fontSize:'13px', color:'var(--fg-3)', marginBottom:'24px', lineHeight:1.55}}>
            Tienes {ownedCards.length} carta{ownedCards.length===1?'':'s'} en tu colección.<br/>
            Abre más sobres para formar un mazo.
          </div>
          <div style={{display:'flex', gap:'12px', justifyContent:'center'}}>
            <button className="btn ghost" onClick={() => actions.go('champions')}>VOLVER</button>
            <button className="btn primary" onClick={() => actions.go('packs')}>◆ ABRIR SOBRES</button>
          </div>
        </div>
      </div>
    );
  }

  // ─── DECK PICK PHASE ──────────────────────────────────────────────────
  if (phase === 'deck-pick') {
    const toggle = (id) => {
      setYourDeck(prev => prev.includes(id) ? prev.filter(x=>x!==id) : (prev.length<5 ? [...prev, id] : prev));
    };
    const autoPick = () => {
      const sorted = ownedCards.slice().sort((a,b) => BR[b.rarity].tier - BR[a.rarity].tier || b.stats.fame - a.stats.fame);
      setYourDeck(sorted.slice(0,5).map(c=>c.id));
    };
    const start = () => {
      // Shuffle opp deck
      setOppDeck(champion.deck.slice().sort(() => Math.random() - 0.5));
      setYourDeck(yourDeck.slice().sort(() => Math.random() - 0.5));
      setPhase('playing');
    };
    return (
      <div className="page">
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:'24px', gap:'24px', flexWrap:'wrap'}}>
          <div>
            <div className="eyebrow" style={{marginBottom:'8px'}}>
              ◈ DESAFÍO · <strong style={{color:'var(--accent-orange)'}}>{champion.name}</strong>
            </div>
            <div style={{fontFamily:'var(--font-sans)', fontWeight:700, fontSize:'32px', color:'var(--fg-1)', letterSpacing:'-0.02em', lineHeight:1.05}}>
              ELIGE TU MAZO · <span style={{color:'var(--accent-cyan)'}}>{yourDeck.length}/5</span>
            </div>
          </div>
          <div style={{display:'flex', gap:'8px'}}>
            <button className="btn ghost" onClick={() => actions.go('champions')}>RETIRARSE</button>
            <button className="btn ghost" onClick={autoPick}>AUTO-PICK TOP 5</button>
            <button className="btn primary" disabled={yourDeck.length<5} onClick={start}>
              ▸ INICIAR DUELO
            </button>
          </div>
        </div>

        {/* Your hand preview */}
        <div className="your-hand">
          {[...Array(5)].map((_, i) => {
            const id = yourDeck[i];
            return id
              ? <TopTrumpsCard key={id} card={getCard(id)} onClick={() => toggle(id)}/>
              : <div key={i} className="empty-slot">SLOT {i+1}<br/>VACÍO</div>;
          })}
        </div>

        <div className="eyebrow-row">
          <span className="eyebrow">TU COLECCIÓN · <strong>{ownedCards.length} CARTAS</strong></span>
        </div>
        <div className="cards-row" style={{flexWrap:'wrap', gap:'12px'}}>
          {ownedCards.map(c => (
            <TopTrumpsCard key={c.id} card={c}
                           inDeck={yourDeck.includes(c.id)}
                           selected={yourDeck.includes(c.id)}
                           onClick={() => toggle(c.id)} />
          ))}
        </div>
      </div>
    );
  }

  // ─── PLAYING PHASE ────────────────────────────────────────────────────
  const yourCardId = yourDeck[round];
  const oppCardId = oppDeck[round];
  const yourCard = yourCardId ? getCard(yourCardId) : null;
  const oppCard = oppCardId ? getCard(oppCardId) : null;

  const pickStat = (statKey) => {
    if (selectedStat || phase !== 'playing') return;
    setSelectedStat(statKey);
    setYourCardRevealed(true);
    // Delay opp reveal
    setTimeout(() => setOppCardRevealed(true), 600);
    // After both revealed, compute winner
    setTimeout(() => {
      const yV = window.statForCompare(statKey, yourCard.stats[statKey]);
      const oV = window.statForCompare(statKey, oppCard.stats[statKey]);
      let res;
      if (yV > oV) { res = 'win'; setYourScore(s => s + 1); }
      else if (yV < oV) { res = 'lose'; setOppScore(s => s + 1); }
      else res = 'draw';
      setRoundResult(res);
      setHistory(h => [...h, { round, stat: statKey, your: yourCard.stats[statKey], opp: oppCard.stats[statKey], res }]);
    }, 1400);
  };

  const nextRound = () => {
    const nr = round + 1;
    if (nr >= 5) {
      // Match over
      const finalYour = yourScore;
      const finalOpp = oppScore;
      let res;
      if (finalYour > finalOpp) res = 'win';
      else if (finalYour < finalOpp) res = 'lose';
      else res = 'draw';
      setMatchResult(res);
      setPhase('done');
      return;
    }
    setRound(nr);
    setSelectedStat(null);
    setYourCardRevealed(false);
    setOppCardRevealed(false);
    setRoundResult(null);
  };

  // ─── DONE PHASE ────────────────────────────────────────────────────────
  if (phase === 'done') {
    const won = matchResult === 'win';
    return (
      <div className="page" style={{display:'grid', placeItems:'center', minHeight:'70vh'}}>
        <div className="panel" style={{padding:'48px', maxWidth:'640px', width:'100%'}}>
          <PanelCorners color={won?'var(--accent-lime)':'var(--accent-orange)'}/>
          <div style={{textAlign:'center', marginBottom:'24px'}}>
            <div style={{fontFamily:'var(--font-mono)', fontSize:'11px', color: won?'var(--accent-lime)':'var(--accent-orange)', textTransform:'uppercase', letterSpacing:'0.12em', marginBottom:'12px'}}>
              ◈ DUELO · {won?'VICTORIA':'DERROTA'}
            </div>
            <div style={{fontFamily:'var(--font-sans)', fontWeight:700, fontSize:'72px', color: won?'var(--accent-lime)':'var(--accent-orange)', letterSpacing:'-0.04em', lineHeight:0.95, marginBottom:'12px'}}>
              {won?'¡VENCISTE!':matchResult==='draw'?'EMPATE':'PERDISTE'}
            </div>
            <div style={{fontFamily:'var(--font-mono)', fontSize:'14px', color:'var(--fg-2)'}}>
              {yourScore} <span style={{color:'var(--fg-4)'}}>vs</span> {oppScore}
            </div>
          </div>

          {won && !state.defeatedChamps.includes(champion.id) && (
            <div style={{background:'var(--bg-inset)', border:'1px solid var(--accent-violet)', padding:'24px', marginBottom:'24px'}}>
              <div style={{fontFamily:'var(--font-mono)', fontSize:'11px', color:'var(--accent-violet)', textTransform:'uppercase', letterSpacing:'0.12em', marginBottom:'12px'}}>
                ◆ RECOMPENSA DESBLOQUEADA
              </div>
              <div style={{display:'flex', gap:'24px', alignItems:'center'}}>
                <div style={{transform:'scale(0.85)', transformOrigin:'left top', marginRight:'-30px'}}>
                  <TopTrumpsCard card={window.GAME_DATA.MYTHIC_CARDS[champion.reward.card]} />
                </div>
                <div style={{flex:1}}>
                  <div style={{fontFamily:'var(--font-sans)', fontWeight:700, fontSize:'22px', color:'var(--fg-1)', textTransform:'uppercase', letterSpacing:'-0.01em', marginBottom:'8px'}}>
                    +{champion.reward.credits.toLocaleString()} CRD
                  </div>
                  <div style={{fontFamily:'var(--font-sans)', fontWeight:700, fontSize:'18px', color:'var(--accent-violet)', textTransform:'uppercase', marginBottom:'12px'}}>
                    1× CARTA MÍTICA<br/>
                    <span style={{fontSize:'14px', color:'var(--fg-1)'}}>{window.GAME_DATA.MYTHIC_CARDS[champion.reward.card].name}</span>
                  </div>
                  <div style={{fontFamily:'var(--font-mono)', fontSize:'11px', color:'var(--fg-3)', lineHeight:1.55}}>
                    {window.GAME_DATA.MYTHIC_CARDS[champion.reward.card].desc}
                  </div>
                </div>
              </div>
            </div>
          )}

          <RoundLog history={history} championName={champion.name}/>

          <div style={{display:'flex', gap:'12px', justifyContent:'center', marginTop:'24px'}}>
            <button className="btn ghost" onClick={() => actions.go('hub')}>HUB</button>
            <button className="btn ghost" onClick={() => actions.go('collection')}>VER COLECCIÓN</button>
            {won && <button className="btn primary" onClick={() => {
              actions.championDefeated(champion.id, champion.reward);
              actions.go('champions');
            }}>▸ RECLAMAR Y CONTINUAR</button>}
            {!won && <button className="btn orange" onClick={() => actions.battle(champion.id)}>▸ REINTENTAR</button>}
          </div>
        </div>
      </div>
    );
  }

  // ─── PLAYING / DUEL ARENA ─────────────────────────────────────────────
  return (
    <div className="battle-shell">
      {/* Result banner overlay */}
      {roundResult && (
        <div className={`battle-result-banner show ${roundResult==='win'?'win':roundResult==='lose'?'lose':'draw'}`}>
          {roundResult === 'win' ? '+1' : roundResult === 'lose' ? '−1' : '='}
        </div>
      )}
      <div className="battle-hud">
        <div className="battle-side">
          <div className="battle-portrait you">▣</div>
          <div>
            <div className="battle-name">TÚ</div>
            <div className="battle-sub">RETADOR</div>
          </div>
        </div>
        <div style={{textAlign:'center'}}>
          <div className="battle-score">
            <span className="you-score">{yourScore}</span>
            <span className="sep">/</span>
            <span className="opp-score">{oppScore}</span>
          </div>
          <div className="battle-round-info">RONDA {round+1} / 5 · BEST OF 5</div>
        </div>
        <div className="battle-side right">
          <div className="battle-portrait">◆</div>
          <div style={{textAlign:'right'}}>
            <div className="battle-name">{champion.name}</div>
            <div className="battle-sub">{champion.title}</div>
          </div>
        </div>
      </div>

      <div className="battle-arena">
        {/* YOUR CARD */}
        <div className="battle-card-slot">
          <div className={`reveal-card-flip ${yourCardRevealed?'revealed':''}`}>
            <div className="reveal-back">
              <span className="corner-mark tl"></span>
              <span className="corner-mark tr"></span>
              <span className="corner-mark bl"></span>
              <span className="corner-mark br"></span>
            </div>
            <div className="reveal-front">
              {yourCard && <TopTrumpsCard card={yourCard} highlightStat={selectedStat}/>}
            </div>
          </div>
        </div>

        <div className="battle-vs">VS</div>

        {/* OPP CARD */}
        <div className="battle-card-slot">
          <div className={`reveal-card-flip ${oppCardRevealed?'revealed':''}`}>
            <div className="reveal-back">
              <span className="corner-mark tl" style={{borderColor:'var(--accent-orange)'}}></span>
              <span className="corner-mark tr" style={{borderColor:'var(--accent-orange)'}}></span>
              <span className="corner-mark bl" style={{borderColor:'var(--accent-orange)'}}></span>
              <span className="corner-mark br" style={{borderColor:'var(--accent-orange)'}}></span>
            </div>
            <div className="reveal-front">
              {oppCard && <TopTrumpsCard card={oppCard} highlightStat={selectedStat}/>}
            </div>
          </div>
        </div>
      </div>

      {/* Stat picker */}
      {!selectedStat && (
        <React.Fragment>
          <div className="battle-prompt">
            <strong>ELIGE UN STAT.</strong> El mayor valor gana la ronda.
          </div>
          <div className="battle-stat-picker">
            {Object.values(BS).map(stat => (
              <button key={stat.key} className="stat-pick-btn" onClick={() => pickStat(stat.key)}>
                <span className="stat-pick-label">{stat.label}</span>
                <span className="stat-pick-val">
                  {window.fmtStat(stat.key, yourCard.stats[stat.key])}
                </span>
              </button>
            ))}
          </div>
        </React.Fragment>
      )}

      {selectedStat && roundResult && (
        <div style={{display:'grid', placeItems:'center', padding:'16px'}}>
          <div style={{fontFamily:'var(--font-mono)', fontSize:'13px', color:'var(--fg-2)', textTransform:'uppercase', letterSpacing:'0.12em', marginBottom:'12px', textAlign:'center'}}>
            {BS[selectedStat].label}: <strong style={{color:'var(--accent-cyan)'}}>{window.fmtStat(selectedStat, yourCard.stats[selectedStat])}</strong>
            {' '}vs{' '}
            <strong style={{color:'var(--accent-orange)'}}>{window.fmtStat(selectedStat, oppCard.stats[selectedStat])}</strong>
          </div>
          <button className="btn primary" onClick={nextRound}>
            ▸ {round === 4 ? 'VER RESULTADO' : 'SIGUIENTE RONDA'}
          </button>
        </div>
      )}

      {selectedStat && !roundResult && (
        <div style={{textAlign:'center', padding:'16px', fontFamily:'var(--font-mono)', fontSize:'13px', color:'var(--accent-cyan)', textTransform:'uppercase', letterSpacing:'0.12em'}}>
          ◈ COMPARANDO {BS[selectedStat].label}...
        </div>
      )}
    </div>
  );
}

function RoundLog({ history, championName }) {
  if (!history.length) return null;
  return (
    <div style={{background:'var(--bg-inset)', border:'1px solid var(--border-hairline)', padding:'16px'}}>
      <div style={{fontFamily:'var(--font-mono)', fontSize:'10px', color:'var(--fg-3)', textTransform:'uppercase', letterSpacing:'0.12em', marginBottom:'12px'}}>
        ◈ REPLAY · 5 RONDAS
      </div>
      <div style={{display:'grid', gap:'6px'}}>
        {history.map((r, i) => (
          <div key={i} style={{display:'grid', gridTemplateColumns:'40px 90px 1fr 80px', gap:'12px', fontFamily:'var(--font-mono)', fontSize:'11px', color:'var(--fg-2)', alignItems:'center'}}>
            <span style={{color:'var(--fg-3)'}}>R{i+1}</span>
            <span style={{textTransform:'uppercase', color:'var(--fg-3)'}}>{window.GAME_DATA.STATS[r.stat].label}</span>
            <span>
              <span style={{color:'var(--accent-cyan)'}}>{window.fmtStat(r.stat, r.your)}</span>
              <span style={{color:'var(--fg-4)', margin:'0 8px'}}>vs</span>
              <span style={{color:'var(--accent-orange)'}}>{window.fmtStat(r.stat, r.opp)}</span>
            </span>
            <span style={{
              color: r.res==='win'?'var(--accent-lime)':r.res==='lose'?'var(--accent-orange)':'var(--fg-3)',
              fontWeight: 700, textAlign:'right'
            }}>{r.res==='win'?'GANADA':r.res==='lose'?'PERDIDA':'EMPATE'}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

window.BattleScreen = BattleScreen;
