// =============================================================================
// SHARED COMPONENTS
// =============================================================================
const { useState, useEffect, useMemo, useRef, useCallback } = React;
const { CardArt } = window;
const { PROVIDERS, RARITIES, STATS, CARDS, MYTHIC_CARDS, CHAMPIONS, COLLECTIONS, getCard } = window.GAME_DATA;

// Format helpers
function fmtStat(key, val) {
  if (key === 'rtp') return val.toFixed(1) + '%';
  if (key === 'maxwin') return val >= 1000 ? (val / 1000).toFixed(val >= 10000 ? 0 : 1) + 'k' : val;
  if (key === 'hits') return val + '%';
  return val;
}

function statForCompare(key, val) {
  // RTP is in 90-99 range — normalize by subtracting 90
  if (key === 'rtp') return (val - 90) * 10;
  if (key === 'maxwin') return Math.log10(val) * 12; // log scale → 0–60
  return val;
}

function normalizedPercent(key, val) {
  if (key === 'rtp') return Math.min(100, (val - 90) * 10);
  if (key === 'maxwin') return Math.min(100, Math.log10(val) * 12);
  if (key === 'volatility') return val;
  if (key === 'hits') return val;
  if (key === 'fame') return val;
  return val;
}

// =============================================================================
// PROVIDER CHIP
// =============================================================================
function ProvChip({ providerId }) {
  const p = PROVIDERS[providerId];
  const accentClass = {
    cyan: 'cyan', lime: 'lime', orange: 'orange', violet: 'violet', red: 'red',
  }[p.accent] || 'cyan';
  return <span className={`prov-chip ${accentClass}`}>{p.code}</span>;
}

// =============================================================================
// TOP TRUMPS CARD
// =============================================================================
function TopTrumpsCard({ card, locked = false, selected = false, inDeck = false, onClick, highlightStat, size = 'md', onStatClick }) {
  if (!card) return null;
  const rarity = RARITIES[card.rarity];
  const provider = PROVIDERS[card.provider];
  const cls = `tt-card rarity-${card.rarity}${locked?' locked':''}${selected?' selected':''}${inDeck?' in-deck':''} size-${size}`;

  return (
    <div className={cls} onClick={onClick}>
      <div className="tt-header">
        <span className="prov-code">{provider.code}</span>
        <span className="tt-rarity-badge">{rarity.label}</span>
      </div>
      <div className="tt-art">
        {!locked && <CardArt artKey={card.art} color="var(--accent)" />}
      </div>
      <div className="tt-card-name">
        {card.name}
        <span className="tt-mech">{card.mech} · {card.year}</span>
      </div>
      <div className="tt-stats">
        {Object.values(STATS).map(stat => {
          const v = card.stats[stat.key];
          const pct = normalizedPercent(stat.key, v);
          const active = highlightStat === stat.key;
          return (
            <div key={stat.key}
                 className={`tt-stat-row ${active?'active flip-stat':''}`}
                 onClick={onStatClick ? (e) => { e.stopPropagation(); onStatClick(stat.key); } : undefined}
                 style={onStatClick ? {cursor:'pointer'} : undefined}>
              <span className="tt-stat-label">{stat.short}</span>
              <span className="tt-stat-bar">
                <span className="tt-stat-bar-fill" style={{'--w': pct + '%'}}></span>
              </span>
              <span className="tt-stat-val">{fmtStat(stat.key, v)}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// =============================================================================
// CHAMPION PORTRAIT — abstract sigil
// =============================================================================
function ChampionSigil({ champion, size = 110 }) {
  const c = champion;
  // Use one of the champion's deck arts as the sigil base
  const baseCard = getCard(c.deck[0]);
  return (
    <svg viewBox="0 0 100 100" width={size} height={size} fill="none"
         stroke="var(--accent-orange)" strokeWidth="1.5">
      <CardArt artKey={baseCard?.art || 'gem'} color="var(--accent-orange)" />
      <circle cx="50" cy="50" r="46" strokeDasharray="4 3" opacity="0.5"/>
    </svg>
  );
}

// =============================================================================
// PACK MINI VISUAL
// =============================================================================
function PackMini() {
  return (
    <div className="pack-mini">
      <span style={{position:'relative', zIndex:1}}>SOBRE<br/>×5</span>
    </div>
  );
}

// =============================================================================
// CORNER PANEL DECORATION
// =============================================================================
function PanelCorners({ color }) {
  const style = color ? { borderColor: color } : {};
  return (
    <React.Fragment>
      <span className="panel-corner tl" style={style}></span>
      <span className="panel-corner tr" style={style}></span>
      <span className="panel-corner bl" style={style}></span>
      <span className="panel-corner br" style={style}></span>
    </React.Fragment>
  );
}

Object.assign(window, {
  TopTrumpsCard, ChampionSigil, PackMini, ProvChip, PanelCorners,
  fmtStat, statForCompare, normalizedPercent,
});
