// =============================================================================
// PACK OPENING SCREEN
// =============================================================================
const { useState } = React;

function PackScreen({ state, actions }) {
  const [phase, setPhase] = useState('idle'); // idle | shaking | revealing | summary
  const [pack, setPack] = useState(null); // array of card ids
  const [revealedIdx, setRevealedIdx] = useState([]); // bools

  const openPack = () => {
    if (state.packsToday <= 0) return;
    setPhase('shaking');
    setTimeout(() => {
      const newPack = window.GAME_DATA.generatePack(5);
      setPack(newPack);
      setRevealedIdx(newPack.map(() => false));
      setPhase('revealing');
    }, 700);
  };

  const reveal = (i) => {
    setRevealedIdx(arr => arr.map((v, idx) => idx === i ? true : v));
  };

  const revealAll = () => {
    setRevealedIdx(pack.map(() => true));
  };

  const finishPack = () => {
    // Persist new cards
    actions.openedPack(pack);
    setPhase('idle');
    setPack(null);
    setRevealedIdx([]);
  };

  if (state.packsToday <= 0 && phase === 'idle') {
    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'}}>
            ◈ SIN STOCK · DAILY LIMIT
          </div>
          <div style={{fontFamily:'var(--font-sans)', fontWeight:700, fontSize:'36px', color:'var(--fg-1)', marginBottom:'12px', letterSpacing:'-0.02em', lineHeight:1.05}}>
            SOBRES AGOTADOS
          </div>
          <div style={{fontFamily:'var(--font-mono)', fontSize:'13px', color:'var(--fg-3)', marginBottom:'24px', lineHeight:1.55}}>
            Has abierto tus 2 sobres diarios.<br/>Vuelve en 24h o reta a un campeón.
          </div>
          <div style={{display:'flex', gap:'12px', justifyContent:'center'}}>
            <button className="btn ghost" onClick={() => actions.go('hub')}>VOLVER AL HUB</button>
            <button className="btn orange" onClick={() => actions.go('champions')}>◆ IR A DESAFÍOS</button>
          </div>
        </div>
      </div>
    );
  }

  // IDLE — show the big pack
  if (phase === 'idle' || phase === 'shaking') {
    return (
      <div className="pack-screen">
        <div className="pack-bg-radial"></div>
        <div style={{display:'grid', gap:'32px', textAlign:'center', position:'relative', zIndex:1}}>
          <div>
            <div style={{fontFamily:'var(--font-mono)', fontSize:'11px', color:'var(--accent-cyan)', textTransform:'uppercase', letterSpacing:'0.12em', marginBottom:'8px'}}>
              ◈ DAILY · SOBRE {3 - state.packsToday}/2
            </div>
            <div style={{fontFamily:'var(--font-sans)', fontWeight:700, fontSize:'48px', color:'var(--fg-1)', letterSpacing:'-0.03em', lineHeight:1}}>
              ABRIR SOBRE
            </div>
            <div style={{fontFamily:'var(--font-mono)', fontSize:'12px', color:'var(--fg-3)', textTransform:'uppercase', letterSpacing:'0.12em', marginTop:'8px'}}>
              5 CARTAS · 1 GARANTIZADA ≥ RARA
            </div>
          </div>

          <div className={`pack-big ${phase==='shaking'?'opening':''}`} onClick={phase==='idle' ? openPack : undefined}>
            <div className="pack-big-top">
              <span>TT · v1.0</span>
              <span>5 / 5</span>
            </div>
            <div className="pack-big-mid">
              <svg viewBox="0 0 100 100" width="140" height="140" fill="none" stroke="var(--accent-cyan)" strokeWidth="1.5">
                <rect x="22" y="22" width="56" height="56" />
                <rect x="32" y="32" width="36" height="36" strokeDasharray="3 3"/>
                <path d="M 22 22 L 32 32 M 78 22 L 68 32 M 22 78 L 32 68 M 78 78 L 68 68"/>
                <circle cx="50" cy="50" r="6" fill="var(--accent-cyan)"/>
                <text x="50" y="92" textAnchor="middle" fontFamily="monospace" fontSize="6" letterSpacing="2" fill="var(--accent-cyan)" stroke="none">SLOT LEGENDS</text>
              </svg>
              <div className="pack-big-title" style={{position:'absolute', bottom:'-10px', left:0, right:0, fontSize:'14px', color:'var(--accent-cyan)', letterSpacing:'0.12em', fontFamily:'var(--font-mono)'}}>
                · PACK · 5 ·
              </div>
            </div>
            <div className="pack-big-foot">
              {phase==='idle' ? 'TOCA PARA ABRIR' : 'ABRIENDO...'}
            </div>
          </div>

          <div style={{display:'flex', gap:'12px', justifyContent:'center'}}>
            <button className="btn ghost" onClick={() => actions.go('hub')}>VOLVER</button>
            <button className="btn primary" disabled={phase!=='idle'} onClick={openPack}>
              ▸ ABRIR
            </button>
          </div>
        </div>
      </div>
    );
  }

  // REVEALING phase
  const allRevealed = revealedIdx.every(Boolean);
  return (
    <div className="page" style={{paddingTop:'32px'}}>
      <div style={{textAlign:'center', marginBottom:'32px'}}>
        <div style={{fontFamily:'var(--font-mono)', fontSize:'11px', color:'var(--accent-cyan)', textTransform:'uppercase', letterSpacing:'0.12em', marginBottom:'8px'}}>
          ◈ TU SOBRE · {revealedIdx.filter(Boolean).length} / 5 REVELADAS
        </div>
        <div style={{fontFamily:'var(--font-sans)', fontWeight:700, fontSize:'36px', color:'var(--fg-1)', letterSpacing:'-0.02em'}}>
          {allRevealed ? '¡SOBRE COMPLETO!' : 'TOCA CADA CARTA PARA REVELAR'}
        </div>
      </div>

      <div className="pack-reveal">
        {pack.map((cardId, i) => {
          const card = window.GAME_DATA.getCard(cardId);
          const isNew = !state.collection[cardId];
          const dupCount = pack.slice(0, i).filter(id => id === cardId).length;
          // If this same card appeared earlier in pack and was new there, this is a duplicate of this pack
          const newInPackBefore = pack.slice(0, i).some(id => id === cardId && !state.collection[id]);
          const labelNew = isNew && !newInPackBefore;
          return (
            <div key={i} className={`reveal-card-slot ${revealedIdx[i] ? (labelNew ? 'new' : 'duplicate') : ''}`}>
              <div className={`reveal-card-flip ${revealedIdx[i] ? 'revealed' : ''}`}>
                <div className="reveal-back" onClick={() => !revealedIdx[i] && reveal(i)}>
                  <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" style={{'--accent-glow': window.GAME_DATA.RARITIES[card.rarity].glow}}>
                  {revealedIdx[i] && <div className="reveal-flash" style={{'--accent-glow': window.GAME_DATA.RARITIES[card.rarity].glow}}></div>}
                  <TopTrumpsCard card={card} />
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <div style={{display:'flex', gap:'12px', justifyContent:'center', marginTop:'40px'}}>
        {!allRevealed && <button className="btn ghost" onClick={revealAll}>▸ REVELAR TODAS</button>}
        {allRevealed && <button className="btn primary" onClick={finishPack}>▸ AÑADIR A COLECCIÓN</button>}
      </div>
    </div>
  );
}

window.PackScreen = PackScreen;
