// =============================================================
// PACK OPENING — dramatic reveal sequence
// 1. Pack on table → click → tear animation
// 2. Cards fly out one by one, flip from back to front
// 3. Reveal summary with NEW badges
// =============================================================
const { useState: usePackState, useEffect: usePackEffect, useMemo: usePackMemo } = React;

function PackOpening({ state, setState, onDone }) {
  // phase: idle → tearing → reveal (one card at a time) → summary
  const [phase, setPhase] = usePackState("idle");
  const [pack, setPack] = usePackState(null);          // generated cards
  const [results, setResults] = usePackState([]);      // [{pokemon, isNew}]
  const [revealIdx, setRevealIdx] = usePackState(0);

  function startOpen() {
    if (state.packsAvailable <= 0) return;
    const cards = GameEngine.generatePack();
    setPack(cards);
    setPhase("tearing");
    // After tear animation, commit to state and begin reveal
    setTimeout(() => {
      setState(prev => {
        const next = { ...prev, packsAvailable: prev.packsAvailable - 1, packsOpenedTotal: prev.packsOpenedTotal + 1 };
        const res = GameEngine.addCardsToCollection(next, cards);
        // Give coins for new dex entries
        const newCount = res.filter(r => r.isNew).length;
        next.coins = (next.coins || 0) + newCount * 5 + cards.length;
        setResults(res);
        return next;
      });
      setPhase("reveal");
      setRevealIdx(0);
    }, 900);
  }

  function nextCard() {
    if (revealIdx < (results.length - 1)) {
      setRevealIdx(revealIdx + 1);
    } else {
      setPhase("summary");
    }
  }

  function openAnother() {
    setPack(null); setResults([]); setRevealIdx(0); setPhase("idle");
  }

  return (
    <div style={{
      minHeight:"100vh",
      background: `
        radial-gradient(ellipse at 50% 30%, rgba(0,240,255,0.12), transparent 60%),
        radial-gradient(ellipse at 50% 80%, rgba(249,85,135,0.08), transparent 60%),
        var(--bg-base)
      `,
      color:"var(--fg-2)",
      display:"flex", flexDirection:"column",
    }}>
      {/* Top bar */}
      <div data-r="pack-topbar" style={{display:"flex", justifyContent:"space-between", alignItems:"center", padding:"24px 40px", borderBottom:"1px solid var(--border-hairline)"}}>
        <button onClick={onDone} style={btnGhost()}>← VOLVER</button>
        <div style={{textAlign:"center"}}>
          <div className="eyebrow" style={{color:"var(--accent-cyan)"}}>SECUENCIA DE APERTURA</div>
          <div style={{fontFamily:"var(--font-sans)", fontWeight:700, fontSize:18, color:"#fff", letterSpacing:"0.05em"}}>SOBRE BÁSICO · 5 CARTAS</div>
        </div>
        <div style={{fontFamily:"var(--font-mono)", fontSize:12, color:"var(--fg-3)"}}>
          SOBRES RESTANTES: <span style={{color:"var(--accent-cyan)", fontWeight:700}}>{state.packsAvailable}</span>
        </div>
      </div>

      <div data-r="pack-stage" style={{flex:1, display:"flex", alignItems:"center", justifyContent:"center", padding:40, position:"relative", overflow:"hidden"}}>
        {/* Background grid */}
        <div style={{position:"absolute", inset:0, backgroundImage:"radial-gradient(circle, var(--grid-dot) 1px, transparent 1px)", backgroundSize:"24px 24px", opacity:0.4, pointerEvents:"none"}}/>

        {phase === "idle" && <IdlePack onOpen={startOpen} canOpen={state.packsAvailable > 0}/>}
        {phase === "tearing" && <TearingPack/>}
        {phase === "reveal" && results[revealIdx] && (
          <RevealCard
            key={revealIdx}
            result={results[revealIdx]}
            idx={revealIdx}
            total={results.length}
            onNext={nextCard}
          />
        )}
        {phase === "summary" && (
          <Summary results={results} onAnother={openAnother} onDone={onDone} canOpenAnother={state.packsAvailable > 0}/>
        )}
      </div>
    </div>
  );
}

// ---------- Idle pack ready to be opened ----------
function IdlePack({ onOpen, canOpen }) {
  const [hover, setHover] = usePackState(false);
  return (
    <div style={{display:"flex", flexDirection:"column", alignItems:"center", gap:32}}>
      <div style={{fontFamily:"var(--font-sans)", fontWeight:300, fontSize:24, color:"var(--fg-3)", letterSpacing:"0.05em", textAlign:"center"}}>
        Toca el sobre para abrirlo
      </div>
      <div
        onClick={canOpen ? onOpen : undefined}
        onMouseEnter={()=>setHover(true)}
        onMouseLeave={()=>setHover(false)}
        style={{
          position:"relative", width:240, height:340,
          cursor: canOpen ? "pointer" : "not-allowed",
          transform: `perspective(1200px) rotateY(${hover ? -12 : -4}deg) rotateX(${hover ? 6 : 2}deg) translateY(${hover ? -8 : 0}px)`,
          transition: "transform 400ms cubic-bezier(0.16,1,0.3,1)",
          filter: canOpen ? "none" : "grayscale(1) brightness(0.5)",
        }}>
        <BigPack hover={hover}/>
      </div>
      <div style={{fontFamily:"var(--font-mono)", fontSize:11, color:"var(--fg-4)", letterSpacing:"0.15em", textAlign:"center"}}>
        3 COMUNES · 1 INUSUAL · 1 RARA<br/>
        <span style={{color:"var(--accent-cyan)"}}>★ CHANCE DE LEGENDARIA ★</span>
      </div>
    </div>
  );
}

function BigPack({ hover }) {
  return (
    <div style={{
      position:"absolute", inset:0,
      borderRadius: 6,
      overflow:"hidden",
      boxShadow: `
        0 0 ${hover ? 80 : 40}px rgba(0,240,255,0.55),
        0 0 ${hover ? 120 : 60}px rgba(249,85,135,0.3),
        12px 12px 0 0 rgba(0,0,0,0.5)
      `,
    }}>
      <img
        src="assets/pack.png"
        alt="Sobre Pokémon"
        style={{
          width:"100%", height:"100%", objectFit:"cover",
          display:"block",
        }}
      />
      {/* Holo shine sweep */}
      <div style={{
        position:"absolute", inset:0,
        backgroundImage:"linear-gradient(115deg, transparent 30%, rgba(255,255,255,0.5) 50%, transparent 70%)",
        animation:"holoShift 3s linear infinite",
        backgroundSize:"200% 200%",
        mixBlendMode:"overlay",
        pointerEvents:"none",
      }}/>
      {/* Subtle scanlines */}
      <div style={{
        position:"absolute", inset:0,
        backgroundImage:"repeating-linear-gradient(0deg, transparent 0px, transparent 3px, rgba(0,0,0,0.06) 3px, rgba(0,0,0,0.06) 4px)",
        pointerEvents:"none",
      }}/>
    </div>
  );
}

// ---------- Tearing animation ----------
function TearingPack() {
  return (
    <div style={{position:"relative", width:240, height:340}}>
      <style>{`
        @keyframes tearLeft  { 0%{transform:translate(0,0) rotate(0)} 100%{transform:translate(-100px, 30px) rotate(-12deg); opacity:0;} }
        @keyframes tearRight { 0%{transform:translate(0,0) rotate(0)} 100%{transform:translate(100px, 30px) rotate(12deg); opacity:0;} }
        @keyframes flashBurst { 0%{transform:scale(0); opacity:1;} 80%{transform:scale(3); opacity:0.6;} 100%{transform:scale(4); opacity:0;} }
      `}</style>
      <div style={{position:"absolute", top:0, left:0, width:120, height:340, overflow:"hidden", animation:"tearLeft 800ms cubic-bezier(0.4,0,0.2,1) forwards"}}>
        <div style={{position:"absolute", width:240, height:340}}><BigPack hover={false}/></div>
      </div>
      <div style={{position:"absolute", top:0, left:120, width:120, height:340, overflow:"hidden", animation:"tearRight 800ms cubic-bezier(0.4,0,0.2,1) forwards"}}>
        <div style={{position:"absolute", left:-120, width:240, height:340}}><BigPack hover={false}/></div>
      </div>
      <div style={{position:"absolute", top:"50%", left:"50%", transform:"translate(-50%,-50%)", width:200, height:200, borderRadius:"50%", background:"radial-gradient(circle, rgba(255,255,255,0.9), rgba(0,240,255,0.6), transparent 70%)", animation:"flashBurst 900ms ease-out forwards"}}/>
    </div>
  );
}

// ---------- Reveal one card ----------
function RevealCard({ result, idx, total, onNext }) {
  const [flipped, setFlipped] = usePackState(false);
  const { pokemon, isNew } = result;
  const isShiny = pokemon.rarity === "holo" || pokemon.rarity === "legendary";

  usePackEffect(() => {
    const t = setTimeout(() => setFlipped(true), 380);
    return () => clearTimeout(t);
  }, []);

  return (
    <div data-r="reveal-card" style={{display:"flex", flexDirection:"column", alignItems:"center", gap:24}}>
      <style>{`
        @keyframes cardSlideIn { 0%{transform: translateY(40px) scale(0.85); opacity:0;} 100%{transform: translateY(0) scale(1); opacity:1;} }
        @keyframes rareGlow { 0%,100%{filter: drop-shadow(0 0 20px rgba(0,240,255,0.5))} 50%{filter: drop-shadow(0 0 50px rgba(0,240,255,0.9))} }
        @keyframes legendBurst { 0%{transform:rotate(0)} 100%{transform:rotate(360deg)} }
      `}</style>

      <div style={{fontFamily:"var(--font-mono)", fontSize:13, color:"var(--fg-3)", letterSpacing:"0.2em"}}>
        CARTA {idx + 1} / {total}
      </div>

      <div style={{
        position:"relative",
        animation: "cardSlideIn 420ms cubic-bezier(0.16,1,0.3,1)",
      }}>
        {/* Legendary radial burst */}
        {pokemon.rarity === "legendary" && flipped && (
          <div style={{
            position:"absolute", top:"50%", left:"50%", transform:"translate(-50%,-50%)",
            width: 500, height: 500,
            background: `conic-gradient(from 0deg, transparent, rgba(255,212,0,0.4), transparent, rgba(255,94,0,0.4), transparent, rgba(255,212,0,0.4), transparent)`,
            animation: "legendBurst 8s linear infinite",
            pointerEvents:"none",
            borderRadius: "50%",
            filter:"blur(20px)",
          }}/>
        )}

        {/* Flip card */}
        <div style={{
          width: 280, height: 392,
          perspective: 1500,
          animation: isShiny && flipped ? "rareGlow 2s ease-in-out infinite" : "none",
        }}>
          <div style={{
            width:"100%", height:"100%",
            position:"relative",
            transformStyle:"preserve-3d",
            transform: flipped ? "rotateY(0deg)" : "rotateY(180deg)",
            transition: "transform 700ms cubic-bezier(0.4, 0.0, 0.2, 1)",
          }}>
            <div style={{position:"absolute", inset:0, backfaceVisibility:"hidden", transform:"rotateY(180deg)"}}>
              <PokemonCard pokemon={pokemon} size="lg" showBack/>
            </div>
            <div style={{position:"absolute", inset:0, backfaceVisibility:"hidden"}}>
              <PokemonCard pokemon={pokemon} size="lg" glow={isShiny}/>
            </div>
          </div>
        </div>
      </div>

      {/* Status under card */}
      <div style={{display:"flex", flexDirection:"column", alignItems:"center", gap:8, minHeight:60}}>
        {flipped && (
          <>
            <div style={{display:"flex", gap:8, alignItems:"center"}}>
              {isNew && (
                <span style={{
                  fontFamily:"var(--font-mono)", fontSize:11, fontWeight:700,
                  padding:"4px 10px", letterSpacing:"0.2em",
                  background:"var(--accent-lime)", color:"#0a0d12",
                  borderRadius:2,
                  boxShadow:"0 0 12px var(--accent-lime-glow)",
                }}>★ NUEVA ★</span>
              )}
              <span style={{
                fontFamily:"var(--font-mono)", fontSize:11, fontWeight:700,
                padding:"4px 10px", letterSpacing:"0.2em",
                background:"transparent", color: RARITY[pokemon.rarity].color,
                border: `1px solid ${RARITY[pokemon.rarity].color}`,
                borderRadius:2,
              }}>{RARITY[pokemon.rarity].symbol} {RARITY[pokemon.rarity].name.toUpperCase()}</span>
            </div>
            <button onClick={onNext} style={btnGhostCyan()}>
              {idx < total - 1 ? "SIGUIENTE ▸" : "VER RESUMEN ▸"}
            </button>
            <div style={{fontFamily:"var(--font-mono)", fontSize:10, color:"var(--fg-4)", letterSpacing:"0.1em"}}>o presiona ESPACIO</div>
          </>
        )}
      </div>

      <KeyHandler onSpace={() => flipped && onNext()}/>
    </div>
  );
}

function KeyHandler({ onSpace }) {
  usePackEffect(() => {
    const h = (e) => { if (e.code === "Space" || e.code === "Enter") { e.preventDefault(); onSpace(); } };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, [onSpace]);
  return null;
}

// ---------- Summary ----------
function Summary({ results, onAnother, onDone, canOpenAnother }) {
  const newCount = results.filter(r => r.isNew).length;
  return (
    <div style={{display:"flex", flexDirection:"column", alignItems:"center", gap:32, maxWidth: 1100}}>
      <div style={{textAlign:"center"}}>
        <div className="eyebrow" style={{color:"var(--accent-cyan)"}}>RESULTADO DEL SOBRE</div>
        <h2 style={{fontFamily:"var(--font-sans)", fontWeight:800, fontSize:48, color:"#fff", margin:"8px 0", letterSpacing:"-0.02em"}}>
          {newCount === 0 ? "Sin nuevas, pero sumas duplicados" :
            newCount === 5 ? "¡SOBRE PERFECTO! Todas nuevas." :
            `${newCount} ${newCount === 1 ? "carta nueva" : "cartas nuevas"} a la Pokédex`}
        </h2>
        <div style={{color:"var(--fg-3)", fontSize:14}}>
          +{results.length} cartas obtenidas · +{newCount * 5 + results.length} Pokécoins
        </div>
      </div>

      <div style={{display:"flex", gap:16, flexWrap:"wrap", justifyContent:"center"}}>
        {results.map((r, i) => (
          <div key={i} style={{position:"relative"}}>
            <PokemonCard pokemon={r.pokemon} size="sm"/>
            {r.isNew && (
              <div style={{
                position:"absolute", top:-8, left:-8,
                padding:"3px 8px",
                background:"var(--accent-lime)", color:"#0a0d12",
                fontFamily:"var(--font-mono)", fontSize:9, fontWeight:800,
                letterSpacing:"0.15em", borderRadius:2,
                boxShadow:"0 0 10px var(--accent-lime-glow)",
                zIndex: 6,
              }}>NUEVA</div>
            )}
          </div>
        ))}
      </div>

      <div style={{display:"flex", gap:12}}>
        {canOpenAnother && (
          <button onClick={onAnother} style={btnPrimary(false)}>
            ▶ ABRIR OTRO SOBRE
          </button>
        )}
        <button onClick={onDone} style={btnGhost()}>VOLVER AL HUB</button>
      </div>
    </div>
  );
}

// ---------- Button helpers ----------
function btnGhost() {
  return {
    fontFamily:"var(--font-sans)", fontWeight:600,
    fontSize:13, letterSpacing:"0.15em", textTransform:"uppercase",
    color:"var(--fg-2)",
    background:"transparent",
    border:"1px solid var(--border-solid)",
    borderRadius: 2,
    padding:"12px 22px",
    cursor:"pointer",
    transition:"all 180ms",
  };
}
function btnGhostCyan() {
  return {
    ...btnGhost(),
    color:"var(--accent-cyan)",
    border:"1px solid var(--accent-cyan)",
    boxShadow:"0 0 12px var(--accent-cyan-glow)",
  };
}

window.PackOpening = PackOpening;
window.btnGhost = btnGhost;
window.btnGhostCyan = btnGhostCyan;
