// wci26/country-cards.jsx — 3D tilt cards grid with neon volume bars

const CountryCard = ({ c, onPick }) => {
  const cardRef = React.useRef(null);
  const [tilt, setTilt] = React.useState({ x: 0, y: 0, h: false });
  const tokenLabel = typeof wciCountryDollarTicker === 'function' ? wciCountryDollarTicker(c) : `$${c.code}26`;

  const handleMove = (e) => {
    if (!cardRef.current) return;
    const r = cardRef.current.getBoundingClientRect();
    const cx = (e.clientX - r.left) / r.width - 0.5;
    const cy = (e.clientY - r.top) / r.height - 0.5;
    setTilt({ x: cy * -12, y: cx * 18, h: true });
  };
  const handleLeave = () => setTilt({ x: 0, y: 0, h: false });

  return (
    <button
      ref={cardRef}
      onMouseMove={handleMove}
      onMouseLeave={handleLeave}
      onClick={() => onPick(c)}
      style={{
        position: 'relative', cursor: 'pointer', appearance: 'none', textAlign: 'left',
        background: 'transparent', border: 0, padding: 0,
        perspective: 1200, perspectiveOrigin: '50% 50%',
      }}
    >
      <div style={{
        position: 'relative', borderRadius: 18, padding: 16,
        background: `linear-gradient(155deg,
          rgba(${parseInt(c.color.slice(1,3),16)}, ${parseInt(c.color.slice(3,5),16)}, ${parseInt(c.color.slice(5,7),16)}, 0.18) 0%,
          rgba(29, 23, 64, 0.95) 55%,
          rgba(15, 9, 35, 0.98) 100%)`,
        border: `1px solid ${c.color}33`,
        boxShadow: `
          inset 0 1.5px 0 rgba(255,255,255,0.10),
          inset 0 -1px 0 rgba(0,0,0,0.5),
          0 1px 2px rgba(0,0,0,0.6),
          0 ${tilt.h ? 16 : 8}px ${tilt.h ? 36 : 18}px -6px rgba(0,0,0,0.7),
          0 ${tilt.h ? 24 : 18}px ${tilt.h ? 56 : 40}px -16px rgba(0,0,0,0.85),
          0 0 ${tilt.h ? 60 : 40}px -16px ${c.color}
        `,
        transform: `rotateX(${tilt.x}deg) rotateY(${tilt.y}deg) translateZ(0)`,
        transition: tilt.h ? 'transform 80ms linear, box-shadow 220ms var(--ease)' : 'transform 320ms var(--ease), box-shadow 320ms var(--ease)',
        transformStyle: 'preserve-3d',
        overflow: 'hidden',
      }}>
        {/* Glow blob */}
        <div style={{
          position: 'absolute', top: -40, right: -40, width: 160, height: 160,
          borderRadius: '50%',
          background: `radial-gradient(circle at center, ${c.color}55 0%, ${c.color}00 70%)`,
          pointerEvents: 'none', filter: 'blur(8px)',
          transform: 'translateZ(20px)',
        }} />
        {/* Accent bar */}
        <div style={{
          position: 'absolute', top: 0, left: 20, right: 20, height: 2,
          background: c.color,
          boxShadow: `0 0 16px ${c.color}`,
          borderRadius: '0 0 2px 2px',
        }} />

        {/* Top row */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14,
          transform: 'translateZ(30px)',
        }}>
          <FlagRect code={c.code} w={36} h={24} />
          <div style={{ flex: 1 }}>
            <div className="display" style={{ fontSize: 22, fontWeight: 800, color: '#fff', lineHeight: 1, letterSpacing: '-0.02em' }}>
              {c.code}
            </div>
            <div style={{ fontSize: 10, color: 'var(--t3)', textTransform: 'uppercase', letterSpacing: '0.08em', marginTop: 2 }}>
              {c.name}
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="mono" style={{ fontSize: 9, color: 'var(--t3)', fontWeight: 700, letterSpacing: '0.1em' }}>
              RANK
            </div>
            <div className="display" style={{
              fontSize: 22, lineHeight: 1, marginTop: 2,
              color: c.rank <= 3 ? 'var(--gold)' : c.rank <= 8 ? 'var(--fifa-yellow)' : 'var(--t1)',
            }}>
              #{c.rank}
            </div>
          </div>
        </div>

        {/* Price */}
        <div style={{
          display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 12,
          transform: 'translateZ(20px)',
        }}>
          <div className="mono" style={{ fontSize: 18, fontWeight: 700, color: '#fff' }}>
            {typeof wciFormatCountryPrice === 'function' ? wciFormatCountryPrice(c) : fmtPrice(c.price)}
          </div>
          <div className="mono" style={{
            fontSize: 12, fontWeight: 700,
            color: c.change24h >= 0 ? 'var(--lime)' : 'var(--coral)',
          }}>
            {c.change24h >= 0 ? '▲' : '▼'} {Math.abs(c.change24h).toFixed(1)}%
          </div>
        </div>

        {/* 3D Neon volume bars (5 segments) */}
        <NeonVolumeBar value={c.volume24h} maxValue={3_500_000} color={c.color} momentum={c.momentum} />

        {/* Stats footer */}
        <div style={{
          marginTop: 12, paddingTop: 10, borderTop: '1px solid rgba(255,255,255,0.06)',
          display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8,
          transform: 'translateZ(10px)',
        }}>
          <Stat label="24h VOL" value={typeof wciFormatCountryVolume === 'function' ? wciFormatCountryVolume(c) : fmtVol(c.volume24h)} />
          <Stat label="MCAP" value={typeof wciFormatCountryMarketCap === 'function' ? wciFormatCountryMarketCap(c) : fmtMcap(c.mcap)} />
          <Stat label="HOLDERS" value={fmtNum(c.holders)} />
        </div>

        {/* Buy CTA */}
        <div style={{
          marginTop: 12, padding: '10px 14px', borderRadius: 10,
          background: `linear-gradient(180deg, ${c.color}, ${c.secondary})`,
          textAlign: 'center', fontWeight: 800, fontSize: 12, letterSpacing: '0.08em',
          textTransform: 'uppercase', color: '#0A0615',
          boxShadow: `
            inset 0 1.5px 0 rgba(255,255,255,0.4),
            inset 0 -1.5px 0 rgba(0,0,0,0.2),
            0 3px 0 rgba(0,0,0,0.4),
            0 6px 14px -2px rgba(0,0,0,0.5)
          `,
          textShadow: '0 1px 0 rgba(255,255,255,0.3)',
          fontFamily: 'Bricolage Grotesque, sans-serif',
          transform: 'translateZ(40px)',
        }}>
          BUY {tokenLabel}
        </div>
      </div>
    </button>
  );
};

const Stat = ({ label, value }) => (
  <div>
    <div className="label" style={{ fontSize: 8, color: 'var(--t3)' }}>{label}</div>
    <div className="mono" style={{ fontSize: 11, fontWeight: 700, color: 'var(--t1)', marginTop: 2 }}>{value}</div>
  </div>
);

// 3D Neon segmented volume bars (5 chunky neon segments stacked)
const NeonVolumeBar = ({ value, maxValue, color, momentum }) => {
  const segments = 7;
  const filled = Math.min(segments, Math.round((value / maxValue) * segments));
  const [pulseT, setPulseT] = React.useState(0);
  React.useEffect(() => {
    let raf;
    const loop = () => {
      setPulseT(performance.now() / 1000);
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);

  return (
    <div style={{ display: 'flex', gap: 4, height: 14 }}>
      {Array.from({ length: segments }).map((_, i) => {
        const isFilled = i < filled;
        const wave = Math.sin(pulseT * (1.5 + momentum) - i * 0.5);
        const intensity = isFilled ? 0.7 + 0.3 * wave : 0;
        return (
          <div key={i} style={{
            flex: 1, height: '100%', borderRadius: 3,
            background: isFilled
              ? `linear-gradient(180deg, ${color}, ${color}99)`
              : 'rgba(255,255,255,0.05)',
            border: `1px solid ${isFilled ? color : 'rgba(255,255,255,0.08)'}`,
            boxShadow: isFilled
              ? `inset 0 1px 0 rgba(255,255,255,0.5),
                 inset 0 -1px 0 rgba(0,0,0,0.3),
                 0 0 ${10 + intensity * 16}px ${color}`
              : 'inset 0 1px 2px rgba(0,0,0,0.5)',
            transition: 'box-shadow 240ms',
          }} />
        );
      })}
    </div>
  );
};

// Grid of all 48 cards
const CountryCardsGrid = ({ countries, onPick }) => {
  const [filter, setFilter] = React.useState('all');
  const filters = [
    { k: 'all', label: 'All 48' },
    { k: 'top', label: 'Top 10' },
    { k: 'gainers', label: 'Gainers' },
    { k: 'losers', label: 'Losers' },
  ];
  const filtered = React.useMemo(() => {
    if (filter === 'top') return countries.slice(0, 10);
    if (filter === 'gainers') return [...countries].sort((a, b) => b.change24h - a.change24h).slice(0, 12);
    if (filter === 'losers') return [...countries].sort((a, b) => a.change24h - b.change24h).slice(0, 12);
    return countries;
  }, [countries, filter]);

  return (
    <div style={{ padding: '32px 40px 80px', maxWidth: 1600, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 24 }}>
        <div>
          <div className="label" style={{ color: 'var(--gold)' }}>COUNTRY TOKENS</div>
          <div className="display" style={{ fontSize: 44, lineHeight: 1, letterSpacing: '-0.03em' }}>
            All 48 contenders.
          </div>
          <div style={{ color: 'var(--t2)', marginTop: 6, maxWidth: 600 }}>
            One ETH token per country. Pick your colors. Back your nation. Every live buy moves the board.
          </div>
        </div>
        <div style={{ display: 'flex', gap: 6 }}>
          {filters.map(f => (
            <button key={f.k} onClick={() => setFilter(f.k)}
              style={{
                padding: '8px 14px', borderRadius: 10,
                background: filter === f.k ? 'rgba(245,208,32,0.15)' : 'rgba(255,255,255,0.04)',
                border: '1px solid ' + (filter === f.k ? 'var(--gold)' : 'var(--hair)'),
                color: filter === f.k ? 'var(--gold)' : 'var(--t2)',
                fontSize: 12, fontWeight: 700, cursor: 'pointer',
                fontFamily: 'Bricolage Grotesque, sans-serif',
                letterSpacing: '0.04em', textTransform: 'uppercase',
              }}>{f.label}</button>
          ))}
        </div>
      </div>
      <div style={{
        display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16,
      }}>
        {filtered.map(c => <CountryCard key={c.code} c={c} onPick={onPick} />)}
      </div>
    </div>
  );
};

window.CountryCard = CountryCard;
window.CountryCardsGrid = CountryCardsGrid;
