// Card component - the star of the app
// Reads from window.WC_DATA

const { useRef, useEffect } = React;

// Back-compat: existing Firestore docs may store legacy rarity strings.
const RARITY_ALIAS = { shiny: 'rare', holo: 'epic', legend: 'legendary' };
function normalizeRarity(r) { return RARITY_ALIAS[r] || r; }

function teamGradient(team, rarity) {
  if (!team) return 'linear-gradient(160deg, #1a2244, #0f1530)';
  const primary = team.primary;
  const accent = team.accent;

  if (rarity === 'legendary') {
    return `linear-gradient(160deg, ${accent} 0%, ${primary} 50%, #2b1a00 100%)`;
  }
  if (rarity === 'epic') {
    return `linear-gradient(160deg, ${primary} 0%, ${accent} 70%, #111 100%)`;
  }
  return `linear-gradient(160deg, ${primary} 0%, ${accent} 100%)`;
}

function getTeamFlag(team) {
  return team?.displayFlag || team?.flag || '';
}

// SVG silhouette of a player - simple iconic shape
function PlayerSilhouette({ pos, rarity }) {
  const color = rarity === 'legendary' ? 'rgba(255,255,255,0.95)'
    : rarity === 'epic' ? 'rgba(255,255,255,0.9)'
    : rarity === 'rare' ? 'rgba(255,255,255,0.85)'
    : 'rgba(255,255,255,0.82)';
  const shadow = 'rgba(0,0,0,0.55)';

  if (pos === 'GK') {
    return (
      <svg viewBox="0 0 100 130" style={{ width: '100%', height: '100%', filter: `drop-shadow(0 6px 12px ${shadow})` }}>
        <circle cx="50" cy="22" r="12" fill={color} />
        <path d="M 28 42 L 22 72 L 18 56 L 10 62 L 14 82 L 26 78 L 26 118 L 74 118 L 74 78 L 86 82 L 90 62 L 82 56 L 78 72 L 72 42 L 62 38 L 50 42 L 38 38 Z" fill={color} />
      </svg>
    );
  }

  return (
    <svg viewBox="0 0 100 130" style={{ width: '100%', height: '100%', filter: `drop-shadow(0 6px 12px ${shadow})` }}>
      <circle cx="50" cy="22" r="12" fill={color} />
      <path d="M 30 40 L 22 72 L 26 88 L 34 118 L 46 118 L 48 80 L 52 80 L 54 118 L 66 118 L 74 88 L 78 72 L 70 40 L 62 38 L 50 42 L 38 38 Z" fill={color} />
    </svg>
  );
}

// Shirt number with team colors behind - bigger more graphic
function PlayerShirt({ num, team }) {
  return (
    <div
      style={{
        position: 'absolute',
        top: '18%',
        right: '8%',
        fontFamily: 'var(--font-display)',
        fontSize: '42px',
        lineHeight: 1,
        color: team?.secondary || '#fff',
        textShadow: `2px 2px 0 ${team?.accent || '#000'}, 0 4px 10px rgba(0,0,0,0.5)`,
        opacity: 0.5,
        zIndex: 1,
      }}
    >
      {num}
    </div>
  );
}

function StickerCard({ sticker, rarity, isNew, onClick, interactive = true, mini = false, compact = false, tilt = true }) {
  const data = window.WC_DATA;
  const team = data.TEAMS.find(item => item.id === sticker.team);
  const normalizedRarity = normalizeRarity(rarity || sticker.baseRarity || 'common');
  const cardRef = useRef(null);
  const rafRef = useRef(0);
  const pendingRef = useRef(null);

  function handleMove(event) {
    if (!interactive || !tilt || !cardRef.current) return;
    const rect = cardRef.current.getBoundingClientRect();
    pendingRef.current = {
      px: (event.clientX - rect.left) / rect.width,
      py: (event.clientY - rect.top) / rect.height,
    };

    if (rafRef.current) return;

    rafRef.current = requestAnimationFrame(() => {
      rafRef.current = 0;
      const element = cardRef.current;
      const next = pendingRef.current;
      if (!element || !next) return;

      const px = Math.max(0, Math.min(1, next.px));
      const py = Math.max(0, Math.min(1, next.py));
      const fromCenter = Math.hypot(px - 0.5, py - 0.5);

      element.style.setProperty('--pointer-x', `${(px * 100).toFixed(2)}%`);
      element.style.setProperty('--pointer-y', `${(py * 100).toFixed(2)}%`);
      element.style.setProperty('--pointer-from-center', fromCenter.toFixed(3));
      element.style.setProperty('--background-x', `${(px * 200 - 50).toFixed(2)}%`);
      element.style.setProperty('--background-y', `${(py * 200 - 50).toFixed(2)}%`);
      element.style.setProperty('--rotate-x', `${((0.5 - py) * 14).toFixed(2)}deg`);
      element.style.setProperty('--rotate-y', `${((px - 0.5) * 14).toFixed(2)}deg`);
      element.style.setProperty('--card-active', '1');
    });
  }

  function handleLeave() {
    if (rafRef.current) {
      cancelAnimationFrame(rafRef.current);
      rafRef.current = 0;
    }

    const element = cardRef.current;
    if (!element) return;

    element.style.setProperty('--rotate-x', '0deg');
    element.style.setProperty('--rotate-y', '0deg');
    element.style.setProperty('--card-active', '0');
    element.style.setProperty('--pointer-x', '50%');
    element.style.setProperty('--pointer-y', '50%');
  }

  useEffect(() => () => {
    if (rafRef.current) cancelAnimationFrame(rafRef.current);
  }, []);

  return (
    <div
      ref={cardRef}
      className={`sticker-card ${interactive ? 'interactive' : ''} ${tilt ? 'tilt' : ''} ${compact ? 'is-compact' : ''}`}
      data-rarity={normalizedRarity}
      style={{ '--card-bg': teamGradient(team, normalizedRarity) }}
      onPointerMove={handleMove}
      onPointerLeave={handleLeave}
      onClick={onClick}
    >
      <div className="sticker-card__inner">
        <div className="sticker-card__header">
          <div className="sticker-card__num">{String(sticker.num).padStart(2, '0')}</div>
          <div className="sticker-card__flag">{compact ? team?.short : getTeamFlag(team)}</div>
        </div>

        {!compact && <PlayerShirt num={sticker.num} team={team} />}

        <div className="sticker-card__portrait">
          <div className="sticker-card__silhouette">
            <PlayerSilhouette pos={sticker.pos} rarity={normalizedRarity} />
          </div>
        </div>

        {!mini && !compact && (
          <div className="sticker-card__nameplate">
            <div className="sticker-card__name">{sticker.name}</div>
            <div className="sticker-card__pos">{sticker.pos} - {team?.short}</div>
          </div>
        )}
      </div>

      <div className="sticker-card__shine" />
      <div className="sticker-card__glare" />
      <div className="sticker-card__frame" />
      {(!mini || compact) && <div className="sticker-card__rarity">{data.RARITY[normalizedRarity]?.label || normalizedRarity}</div>}
      {isNew && <div className="sticker-card__new">NEW</div>}
    </div>
  );
}

function EmptySlot({ num, showNum = true }) {
  return (
    <div className="sticker-slot-empty">
      {showNum && <div className="sticker-slot-empty__num">{String(num).padStart(2, '0')}</div>}
      <svg viewBox="0 0 100 130" style={{ width: '60%', height: '70%', opacity: 0.4 }}>
        <circle cx="50" cy="22" r="12" fill="currentColor" />
        <path d="M 30 40 L 22 72 L 26 88 L 34 118 L 46 118 L 48 80 L 52 80 L 54 118 L 66 118 L 74 88 L 78 72 L 70 40 L 62 38 L 50 42 L 38 38 Z" fill="currentColor" />
      </svg>
    </div>
  );
}

Object.assign(window, { StickerCard, EmptySlot, teamGradient, PlayerSilhouette, normalizeRarity });
