// wci26/leaderboard-rail.jsx — Live buy pressure battle (left rail)

const MissionCard = ({ mission }) => (
  <div style={{
    padding: 10, borderRadius: 10,
    background: 'rgba(255,255,255,0.035)',
    border: `1px solid ${mission.accent}44`,
    boxShadow: `0 10px 24px -18px ${mission.accent}`,
  }}>
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'center' }}>
      <span className="label" style={{ fontSize: 8, color: mission.accent }}>{mission.label}</span>
      <span className="mono" style={{ fontSize: 9, color: 'var(--t4)', fontWeight: 700 }}>{mission.reward}</span>
    </div>
    <div style={{ marginTop: 5, display: 'flex', justifyContent: 'space-between', gap: 10, alignItems: 'baseline' }}>
      <span className="display" style={{ fontSize: 13, color: '#fff', lineHeight: 1.05 }}>{mission.title}</span>
      <span className="mono" style={{ fontSize: 10, color: 'var(--t2)', fontWeight: 700, whiteSpace: 'nowrap' }}>{mission.body}</span>
    </div>
    <div style={{
      marginTop: 8, height: 5, borderRadius: 999,
      background: 'rgba(255,255,255,0.06)', overflow: 'hidden',
    }}>
      <div style={{
        height: '100%', width: `${Math.max(0, Math.min(100, mission.progress || 0))}%`,
        background: `linear-gradient(90deg, ${mission.accent}, rgba(255,255,255,0.78))`,
        boxShadow: `0 0 10px ${mission.accent}`,
      }} />
    </div>
  </div>
);

const isRecentBuyTickerEvent = (event = {}) => {
  const type = String(event.eventType || event.type || '').toLowerCase();
  const side = String(event.tradeSide || '').toLowerCase();
  const amount = Number(event.amount ?? event.wethAmount ?? event.wethVolume ?? 0);
  if (event.isCountryBuy === true) return amount > 0;
  if (type === 'swap') return side === 'buy' && amount > 0;
  return ['buy', 'countrybuy', 'countrytokenbuy', 'tokenbuy'].includes(type) && amount > 0;
};

const buildRecentBuyFeed = (ticker = []) => {
  const seen = new Set();
  const buys = (Array.isArray(ticker) ? ticker : [])
    .filter(isRecentBuyTickerEvent)
    .filter((buy) => {
      const code = String(buy.code || buy.isoCode || '').toUpperCase();
      const txKey = buy.txHash ? String(buy.txHash).toLowerCase() : '';
      const fallbackKey = `${buy.id || ''}-${code}-${buy.blockNumber || ''}-${buy.amountLabel || buy.amount || buy.wethAmount || ''}`;
      const key = txKey || fallbackKey;
      if (seen.has(key)) return false;
      seen.add(key);
      return true;
    })
    .slice(0, 8)
    .map((buy, index) => {
      const amount = Number(buy.amount ?? buy.wethAmount ?? buy.wethVolume ?? 0);
      const accent = buy.color || buy.accent || 'var(--fifa-teal)';
      return {
        ...buy,
        amountWETH: Number.isFinite(amount) ? amount : 0,
        accent,
        txUrl: buy.txHash ? `https://etherscan.io/tx/${buy.txHash}` : '',
        motionDelayMs: index * 90,
        isHot: index === 0,
      };
    });
  if (buys.length) return buys;
  return [{
    id: 'recent-buys-empty',
    code: 'BUYS',
    color: 'var(--fifa-teal)',
    amount: 0,
    amountLabel: 'No indexed buys yet',
    eventType: 'RecentBuyPending',
    emptyState: true,
  }];
};

const shortTx = (hash) => {
  const text = String(hash || '');
  return text.length > 12 ? `${text.slice(0, 6)}...${text.slice(-4)}` : '';
};

const formatRailVolume = (country) => (
  typeof wciFormatCountryVolume === 'function'
    ? wciFormatCountryVolume(country)
    : fmtVol(country?.volume24h || 0)
);

const formatRailAggregateVolume = (countries) => (
  typeof wciFormatAggregateCountryVolume === 'function'
    ? wciFormatAggregateCountryVolume(countries)
    : fmtVol(countries.reduce((sum, country) => sum + (country.volume24h || 0), 0))
);

const LeaderboardRail = ({ countries, onPick, selectedCountry, marketState, ticker = [], buybackPool = 0 }) => {
  const rankedCountries = countries;
  const maxVol = Math.max(1, ...rankedCountries.map(c => c.volume24h || 0));
  const missions = buildDailyMissions(countries, buybackPool);
  const recentBuyFeed = buildRecentBuyFeed(ticker);

  return (
    <div className="leaderboard-rail" style={{
      width: 320, padding: 16, height: '100%',
      display: 'flex', flexDirection: 'column', minHeight: 0,
      borderRight: '1px solid var(--hair)',
      background: 'linear-gradient(180deg, rgba(20,16,40,0.55), rgba(10,6,21,0.85))',
      backdropFilter: 'blur(12px)',
    }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
        <div>
          <div className="label" style={{ color: 'var(--gold)' }}>LIVE BUY PRESSURE</div>
          <div className="display" style={{ fontSize: 19, lineHeight: 1.1, marginTop: 2 }}>Country Battle</div>
        </div>
        <Chip kind="live">LIVE</Chip>
      </div>

      {/* Mini summary */}
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginBottom: 12,
      }}>
        <div style={{
          padding: 10, borderRadius: 10, border: '1px solid var(--hair)',
          background: 'rgba(245,208,32,0.06)',
        }}>
          <div className="label" style={{ fontSize: 8, color: 'var(--gold)' }}>24h VOL</div>
          <div className="mono" style={{ fontSize: 14, fontWeight: 700, color: '#fff', marginTop: 2 }}>
            {formatRailAggregateVolume(countries)}
          </div>
        </div>
        <div style={{
          padding: 10, borderRadius: 10, border: '1px solid var(--hair)',
          background: 'rgba(159,214,52,0.06)',
        }}>
          <div className="label" style={{ fontSize: 8, color: 'var(--lime)' }}>HOLDERS</div>
          <div className="mono" style={{ fontSize: 14, fontWeight: 700, color: '#fff', marginTop: 2 }}>
            {fmtNum(countries.reduce((s, c) => s + c.holders, 0))}
          </div>
        </div>
      </div>

      {/* Daily missions */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 12 }}>
        {missions.map((mission) => <MissionCard key={mission.id} mission={mission} />)}
      </div>

      {/* Bars */}
      <div className="main-scroll" style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden', marginRight: -8, paddingRight: 8, minHeight: 0 }}>
        {rankedCountries.map((c, i) => {
          const pct = (c.volume24h / maxVol) * 100;
          const isSelected = selectedCountry?.code === c.code;
          const baseBg = i < 3 ? 'rgba(245,208,32,0.04)' : 'transparent';
          const selectedBg = `linear-gradient(90deg, ${c.color}1f, rgba(245,208,32,0.055))`;
          const baseBorder = i < 3 ? 'rgba(245,208,32,0.18)' : 'var(--hair)';
          return (
            <button key={c.code} onClick={() => onPick(c)}
              className={`leaderboard-rail-row ${isSelected ? 'is-selected' : ''}`}
              style={{
                width: '100%', textAlign: 'left', marginBottom: 6,
                padding: '8px 10px', borderRadius: 10,
                background: isSelected ? selectedBg : baseBg,
                border: '1px solid ' + (isSelected ? c.color + '88' : baseBorder),
                boxShadow: isSelected ? `0 0 22px -13px ${c.color}, inset 3px 0 0 ${c.color}` : 'none',
                cursor: 'pointer', transition: 'all 160ms var(--ease)',
                position: 'relative', overflow: 'hidden',
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.transform = 'translateX(2px)';
                e.currentTarget.style.background = `rgba(${parseInt(c.color.slice(1,3),16)}, ${parseInt(c.color.slice(3,5),16)}, ${parseInt(c.color.slice(5,7),16)}, 0.08)`;
                e.currentTarget.style.borderColor = c.color + '66';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.transform = 'translateX(0)';
                e.currentTarget.style.background = isSelected ? selectedBg : baseBg;
                e.currentTarget.style.borderColor = isSelected ? c.color + '88' : baseBorder;
              }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                <span className="mono" style={{
                  fontSize: 10, fontWeight: 700,
                  color: i === 0 ? 'var(--gold)' : i < 3 ? 'var(--fifa-yellow)' : 'var(--t3)',
                  width: 16, textAlign: 'right',
                }}>#{c.rank}</span>
                <FlagRect code={c.code} w={18} h={12} />
                <span className="display" style={{ fontSize: 12, fontWeight: 700, color: '#fff', letterSpacing: '0.04em' }}>{c.code}</span>
                <span style={{ fontSize: 11, color: 'var(--t3)', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.name}</span>
                <span className="mono" style={{
                  fontSize: 10, fontWeight: 700,
                  color: c.change24h >= 0 ? 'var(--lime)' : 'var(--coral)',
                }}>{c.change24h >= 0 ? '+' : ''}{c.change24h.toFixed(1)}%</span>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{
                  flex: 1, height: 6, borderRadius: 3,
                  background: 'rgba(255,255,255,0.05)',
                  overflow: 'hidden', position: 'relative',
                  boxShadow: 'inset 0 1px 2px rgba(0,0,0,0.5)',
                }}>
                  <div style={{
                    position: 'absolute', top: 0, left: 0, bottom: 0,
                    width: pct + '%',
                    background: `linear-gradient(90deg, ${c.color}, ${c.secondary})`,
                    borderRadius: 3,
                    boxShadow: `0 0 12px ${c.color}, inset 0 1px 0 rgba(255,255,255,0.4)`,
                    transition: 'width 600ms var(--ease)',
                  }} />
                  {/* Shimmer */}
                  <div style={{
                    position: 'absolute', top: 0, left: 0, bottom: 0,
                    width: pct + '%', overflow: 'hidden', borderRadius: 3,
                  }}>
                    <div style={{
                      position: 'absolute', inset: 0,
                      background: 'linear-gradient(90deg, transparent, rgba(255,255,255,0.5), transparent)',
                      animation: 'shimmer 2.4s linear infinite',
                    }} />
                  </div>
                </div>
                <span className="mono" style={{ fontSize: 10, color: 'var(--t2)', fontWeight: 700, minWidth: 50, textAlign: 'right' }}>
                  {formatRailVolume(c)}
                </span>
              </div>
            </button>
          );
        })}
      </div>

      {/* Recent buys ticker tape at bottom */}
      <div className="leaderboard-rail-buy-feed" style={{
        marginTop: 10, padding: 10, borderRadius: 10,
        border: '1px solid var(--hair)',
        background: 'rgba(10,6,21,0.65)',
        overflow: 'hidden', position: 'relative',
      }}>
        <div className="recent-buy-feed-header">
          <div className="label" style={{ fontSize: 8, color: 'var(--fifa-teal)' }}>RECENT BUYS</div>
          <span className="recent-buy-stream-meta mono">{recentBuyFeed[0]?.emptyState ? 'waiting' : 'live tape'}</span>
        </div>
        <div className="recent-buy-list">
          {recentBuyFeed.slice(0, 3).map((t, i) => (
            <a
              key={t.id || `${t.code}-${i}`}
              href={t.txUrl || undefined}
              target={t.txUrl ? '_blank' : undefined}
              rel={t.txUrl ? 'noopener noreferrer' : undefined}
              aria-label={t.emptyState ? 'Recent buys waiting for indexed transactions' : `View ${t.code} buy transaction`}
              data-tx-hash={t.txHash || undefined}
              className={`recent-buy-row ${t.emptyState ? 'is-empty' : 'is-live-buy'} ${t.isHot ? 'is-hot' : ''}`}
              style={{
                '--buy-accent': t.accent || t.color || 'var(--fifa-teal)',
                '--buy-delay': `${Number(t.motionDelayMs || 0)}ms`,
                gridTemplateColumns: t.emptyState ? '1fr' : '18px 1fr auto',
              }}
            >
              {!t.emptyState && <span className="recent-buy-trail" aria-hidden="true" />}
              {t.emptyState ? (
                <span className="mono" style={{ fontSize: 11, color: 'var(--t3)' }}>{t.amountLabel}</span>
              ) : (
                <>
                  <span className="recent-buy-flag-wrap">
                    <span className="recent-buy-spark" aria-hidden="true" />
                    <FlagRect code={t.code} w={18} h={12} />
                  </span>
                  <span className="recent-buy-copy mono">
                    {t.amountLabel || `${Number(t.amount || 0).toFixed(4)} WETH`} -> <strong>{t.tokenSymbol || t.code}</strong>
                  </span>
                  <span className="recent-buy-side">
                    <span className="recent-buy-action">View tx</span>
                    <span className="mono recent-buy-hash">{shortTx(t.txHash)}</span>
                  </span>
                </>
              )}
            </a>
          ))}
        </div>
      </div>
    </div>
  );
};

window.LeaderboardRail = LeaderboardRail;
window.WCI_RECENT_BUY_TESTING = {
  buildRecentBuyFeed,
  isRecentBuyTickerEvent,
};
