// =============================================================
// CARD COMPONENT — beautiful Pokémon TCG card
// Used everywhere: pack reveal, collection grid, battle field
// =============================================================
const { useState, useRef, useEffect } = React;

// Energy chip — small circle showing energy type
function EnergyChip({ type, size = 18 }) {
  const info = TYPE_INFO[type] || TYPE_INFO.normal;
  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        justifyContent: "center",
        width: size, height: size,
        borderRadius: "50%",
        background: `radial-gradient(circle at 30% 30%, ${info.gradient[0]}, ${info.gradient[1]})`,
        boxShadow: `inset 0 0 0 1.5px rgba(0,0,0,0.35), 0 0 6px ${info.glow}`,
        color: "#fff",
        fontFamily: "var(--font-sans)",
        fontWeight: 800,
        fontSize: size * 0.55,
        textShadow: "0 1px 1px rgba(0,0,0,0.5)",
        flexShrink: 0,
      }}
    >{info.icon}</span>
  );
}

// Type ribbon at top of card
function TypeRibbon({ types }) {
  return (
    <div style={{ display:"flex", gap:4 }}>
      {types.map((t,i) => <EnergyChip key={i} type={t} size={22} />)}
    </div>
  );
}

// Rarity badge bottom-right
function RarityMark({ rarity }) {
  const r = RARITY[rarity];
  return (
    <span style={{
      display:"inline-flex", alignItems:"center", gap:4,
      fontFamily:"var(--font-mono)", fontSize:10, color:r.color,
      letterSpacing:"0.08em", textTransform:"uppercase",
    }}>
      <span style={{fontSize:14, lineHeight:1}}>{r.symbol}</span>
      {r.name}
    </span>
  );
}

// Holographic foil overlay for rare cards
function HoloFoil({ rarity, hover }) {
  if (rarity !== "holo" && rarity !== "legendary") return null;
  const isLeg = rarity === "legendary";
  return (
    <div
      className="holo-foil"
      style={{
        position:"absolute", inset:0,
        pointerEvents:"none",
        mixBlendMode:"color-dodge",
        opacity: hover ? 0.85 : 0.45,
        backgroundImage: isLeg
          ? "linear-gradient(115deg, transparent 20%, rgba(255,212,0,0.6) 35%, rgba(255,94,0,0.5) 45%, rgba(255,255,255,0.7) 50%, rgba(0,240,255,0.5) 55%, rgba(57,255,20,0.5) 65%, transparent 80%)"
          : "linear-gradient(115deg, transparent 25%, rgba(0,240,255,0.45) 40%, rgba(176,107,255,0.45) 50%, rgba(249,85,135,0.45) 60%, transparent 75%)",
        backgroundSize: "300% 300%",
        animation: `holoShift ${isLeg ? 3.5 : 5}s linear infinite`,
        transition: "opacity 200ms",
        borderRadius: 6,
      }}
    />
  );
}

// Main PokemonCard
function PokemonCard({ pokemon, size = "md", showBack = false, onClick, glow = false, dim = false, count = 0 }) {
  const [hover, setHover] = useState(false);
  const [tilt, setTilt] = useState({ rx: 0, ry: 0 });
  const ref = useRef(null);

  const dims = {
    xs: { w: 110, h: 154, scale: 0.45 },
    sm: { w: 160, h: 224, scale: 0.65 },
    md: { w: 220, h: 308, scale: 0.9 },
    lg: { w: 280, h: 392, scale: 1.15 },
    xl: { w: 340, h: 476, scale: 1.4 },
  }[size];

  const primaryType = pokemon.types[0];
  const info = TYPE_INFO[primaryType];

  function onMove(e) {
    if (!ref.current) return;
    const rect = ref.current.getBoundingClientRect();
    const x = (e.clientX - rect.left) / rect.width;
    const y = (e.clientY - rect.top) / rect.height;
    setTilt({ ry: (x - 0.5) * 14, rx: -(y - 0.5) * 14 });
  }
  function onLeave() { setHover(false); setTilt({ rx:0, ry:0 }); }

  if (showBack) {
    return (
      <div style={{ width: dims.w, height: dims.h, position:"relative",
        borderRadius: 8, overflow:"hidden",
        boxShadow: "0 0 20px rgba(0,0,0,0.5), 2px 2px 0 0 var(--border-solid)",
      }}>
        <img
          src="assets/card-back.png"
          alt="Reverso"
          style={{
            width:"100%", height:"100%", objectFit:"cover",
            display:"block",
          }}
        />
      </div>
    );
  }

  const isRareGlow = pokemon.rarity === "holo" || pokemon.rarity === "legendary";

  return (
    <div
      ref={ref}
      onMouseMove={onMove}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={onLeave}
      onClick={onClick}
      style={{
        width: dims.w, height: dims.h,
        position:"relative",
        cursor: onClick ? "pointer" : "default",
        transform: `perspective(1000px) rotateX(${tilt.rx}deg) rotateY(${tilt.ry}deg) ${hover ? "translateY(-6px)" : ""}`,
        transformStyle: "preserve-3d",
        transition: "transform 220ms cubic-bezier(0.16,1,0.3,1)",
        filter: dim ? "grayscale(1) brightness(0.5)" : "none",
        opacity: dim ? 0.65 : 1,
      }}
    >
      {/* Outer frame */}
      <div style={{
        position:"absolute", inset:0,
        borderRadius: 8,
        background: `linear-gradient(160deg, ${info.gradient[0]} 0%, ${info.gradient[1]} 100%)`,
        boxShadow: glow
          ? `0 0 30px ${info.glow}, 0 0 60px ${info.glow}, 2px 2px 0 0 var(--border-solid)`
          : (isRareGlow ? `0 0 18px ${info.glow}, 2px 2px 0 0 var(--border-solid)` : "2px 2px 0 0 var(--border-solid)"),
        overflow:"hidden",
      }}>
        {/* Inner card body */}
        <div style={{
          position:"absolute", inset:6,
          background: "linear-gradient(180deg, #1C232C 0%, #0D1117 100%)",
          borderRadius: 5,
          border: "1px solid rgba(255,255,255,0.06)",
          display:"flex", flexDirection:"column",
          padding: dims.scale * 10,
          gap: dims.scale * 6,
        }}>
          {/* Header row: name + HP */}
          <div style={{display:"flex", justifyContent:"space-between", alignItems:"flex-start", gap:6}}>
            <div style={{minWidth:0, flex:1}}>
              <div style={{
                fontFamily:"var(--font-sans)", fontWeight:800,
                fontSize: dims.scale * 16, lineHeight:1.05,
                letterSpacing:"0.04em", textTransform:"uppercase",
                color:"#fff",
                whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis",
                textShadow: `0 1px 0 rgba(0,0,0,0.5)`,
              }}>{pokemon.name}</div>
              <div style={{fontFamily:"var(--font-mono)", fontSize: dims.scale * 9, color:info.color, letterSpacing:"0.08em", marginTop: 2}}>
                #{String(pokemon.id).padStart(3,"0")} · GEN {pokemon.id <= 151 ? "I" : "II"}
              </div>
            </div>
            <div style={{display:"flex", flexDirection:"column", alignItems:"flex-end", gap:4}}>
              <div style={{
                fontFamily:"var(--font-sans)", fontWeight:900,
                fontSize: dims.scale * 18, color:"#fff",
                lineHeight:1,
                textShadow:`0 0 8px ${info.glow}`,
              }}>{pokemon.hp}<span style={{fontSize: dims.scale * 9, fontWeight:600, marginLeft:2}}>PS</span></div>
              <TypeRibbon types={pokemon.types} />
            </div>
          </div>

          {/* Image well */}
          <div style={{
            position:"relative",
            height: dims.scale * 130,
            borderRadius: 3,
            background: `
              radial-gradient(ellipse at 50% 70%, ${info.glow} 0%, transparent 60%),
              linear-gradient(180deg, rgba(255,255,255,0.04), rgba(0,0,0,0.4)),
              repeating-linear-gradient(0deg, transparent 0px, transparent 11px, rgba(255,255,255,0.03) 11px, rgba(255,255,255,0.03) 12px),
              repeating-linear-gradient(90deg, transparent 0px, transparent 11px, rgba(255,255,255,0.03) 11px, rgba(255,255,255,0.03) 12px)
            `,
            border: `1px solid ${info.color}55`,
            overflow:"hidden",
            display:"flex", alignItems:"center", justifyContent:"center",
          }}>
            <HoloFoil rarity={pokemon.rarity} hover={hover} />
            <img
              src={SPRITE(pokemon.id)}
              alt={pokemon.name}
              style={{
                maxWidth:"92%", maxHeight:"96%",
                objectFit:"contain",
                filter: `drop-shadow(0 4px 8px rgba(0,0,0,0.6)) drop-shadow(0 0 12px ${info.glow})`,
                transform: `scale(${hover ? 1.06 : 1})`,
                transition: "transform 280ms cubic-bezier(0.16,1,0.3,1)",
              }}
              onError={(e)=>{ e.target.style.display='none'; }}
            />
            {/* Hologram scanlines */}
            <div style={{
              position:"absolute", inset:0, pointerEvents:"none",
              background: "repeating-linear-gradient(0deg, transparent 0px, transparent 3px, rgba(0,240,255,0.04) 3px, rgba(0,240,255,0.04) 4px)",
              mixBlendMode:"screen",
            }}/>
          </div>

          {/* Attacks */}
          {size !== "xs" && (
            <div style={{display:"flex", flexDirection:"column", gap: dims.scale * 4, flex:1}}>
              {pokemon.attacks.map((atk, i) => (
                <div key={i} style={{
                  display:"flex", justifyContent:"space-between", alignItems:"center",
                  padding: `${dims.scale * 4}px ${dims.scale * 6}px`,
                  background: "rgba(0,0,0,0.35)",
                  borderRadius: 2,
                  border:"1px solid rgba(255,255,255,0.05)",
                  gap: 4,
                }}>
                  <div style={{display:"flex", alignItems:"center", gap:4, minWidth:0, flex:1}}>
                    <div style={{display:"flex", gap:2}}>
                      {atk.cost.map((c,j) => <EnergyChip key={j} type={c} size={dims.scale * 13} />)}
                    </div>
                    <span style={{
                      fontFamily:"var(--font-sans)", fontWeight:600,
                      fontSize: dims.scale * 11, color:"#fff",
                      marginLeft: 4,
                      whiteSpace:"nowrap", overflow:"hidden", textOverflow:"ellipsis",
                    }}>{atk.name}</span>
                  </div>
                  <span style={{
                    fontFamily:"var(--font-sans)", fontWeight:800,
                    fontSize: dims.scale * 14, color: atk.dmg > 0 ? "#fff" : "var(--fg-3)",
                  }}>{atk.dmg > 0 ? atk.dmg : "—"}</span>
                </div>
              ))}
            </div>
          )}

          {/* Footer: weakness / retreat / rarity */}
          {size === "md" || size === "lg" || size === "xl" ? (
            <div style={{
              display:"flex", justifyContent:"space-between", alignItems:"center",
              borderTop: "1px dashed rgba(255,255,255,0.1)",
              paddingTop: 4,
              fontFamily:"var(--font-mono)", fontSize: dims.scale * 9,
              color:"var(--fg-3)", letterSpacing:"0.05em",
            }}>
              <div style={{display:"flex", alignItems:"center", gap:3}}>
                <span style={{color:"var(--fg-4)"}}>DÉBIL</span>
                <EnergyChip type={pokemon.weak} size={dims.scale * 11} />
              </div>
              <div style={{display:"flex", alignItems:"center", gap:3}}>
                <span style={{color:"var(--fg-4)"}}>RETIR</span>
                {Array.from({length: pokemon.retreat}).map((_,i)=>(
                  <EnergyChip key={i} type="normal" size={dims.scale * 9}/>
                ))}
                {pokemon.retreat === 0 && <span style={{color:"var(--fg-4)"}}>—</span>}
              </div>
              <RarityMark rarity={pokemon.rarity} />
            </div>
          ) : null}
        </div>
      </div>

      {/* Count badge */}
      {count > 1 && (
        <div style={{
          position:"absolute", top:-8, right:-8,
          minWidth: 26, height:26, padding:"0 7px",
          borderRadius: 13,
          background: "var(--bg-void)",
          border: `2px solid ${info.color}`,
          color: "#fff",
          fontFamily:"var(--font-mono)", fontSize:11, fontWeight:700,
          display:"flex", alignItems:"center", justifyContent:"center",
          boxShadow: `0 0 8px ${info.glow}`,
          zIndex: 5,
        }}>×{count}</div>
      )}
    </div>
  );
}

window.PokemonCard = PokemonCard;
window.EnergyChip = EnergyChip;
window.TypeRibbon = TypeRibbon;
window.RarityMark = RarityMark;
