// wci26/command-center.jsx - contract-aware dashboard surfaces for the live prototype.

const wciCmdAdapter = () => (
  typeof WCI_LIVE_ADAPTER !== 'undefined'
    ? WCI_LIVE_ADAPTER
    : (typeof WCI_CONTRACT_ADAPTER !== 'undefined' ? WCI_CONTRACT_ADAPTER : null)
);
const wciCmdConstants = () => (typeof WCI_CONTRACT_CONSTANTS !== 'undefined' ? WCI_CONTRACT_CONSTANTS : {
  buybackThresholdWETH: 0.1,
  championRewardBps: 0,
  allocationCaps: { reserve: 200000000, airdrop: 150000000, treasury: 100000000, rewards: 50000000 },
});

const wciCmdFmtWeth = (value, digits = 3) => `${Number(value || 0).toFixed(digits)} WETH`;
const wciCmdFmtPct = (value) => `${Math.max(0, Math.min(100, Number(value || 0))).toFixed(0)}%`;
const wciCmdFmtTokens = (value) => {
  const n = Number(value || 0);
  if (n >= 1000000) return `${(n / 1000000).toFixed(1)}M`;
  if (n >= 1000) return `${(n / 1000).toFixed(0)}K`;
  return `${Math.round(n)}`;
};
const wciCmdFmtMarketCap = (country) => (
  typeof wciFormatCountryMarketCap === 'function'
    ? wciFormatCountryMarketCap(country)
    : (typeof fmtMcap === 'function' ? fmtMcap(country?.mcap || 0) : '$--')
);
const wciCmdFmtVolume = (country) => (
  typeof wciFormatCountryVolume === 'function'
    ? wciFormatCountryVolume(country)
    : (typeof fmtVol === 'function' ? fmtVol(country?.volume24h || 0) : '$0')
);
const wciCmdMarketCapUsd = (country) => (
  typeof wciCountryMarketCapUsd === 'function'
    ? wciCountryMarketCapUsd(country)
    : Number(country?.mcap || 0)
);
const wciCmdVolumeUsd = (country) => (
  typeof wciCountryVolumeUsd === 'function'
    ? wciCountryVolumeUsd(country)
    : Number(country?.volume24h || 0)
);
const wciCmdRecentBuyCount = (country) => Number(country?.recentBuyCount || 0);
const wciCmdBuyPressureWeth = (country) => (
  Number(country?.recentBuyVolumeWETH || 0)
  || Number(country?.recentSwapVolumeWETH || 0)
  || Number(country?.volume24h || 0)
);
const wciCmdBuyPressureUsd = (country) => {
  const weth = wciCmdBuyPressureWeth(country);
  if (typeof wciWethToUsd === 'function') return wciWethToUsd(weth);
  return wciCmdVolumeUsd(country);
};
const wciCmdFmtBuyPressure = (country) => wciCmdFmtAggregateUsd(wciCmdBuyPressureUsd(country), '$0');
const wciCmdFmtAggregateUsd = (value, fallback = '$0') => (
  typeof wciFormatCompactUsd === 'function' ? wciFormatCompactUsd(value, fallback) : fallback
);
const wciCmdFmtCountryChange = (country) => {
  const value = Number(country?.change24h || 0);
  return `${value >= 0 ? '+' : ''}${value.toFixed(1)}%`;
};
const wciCmdFmtRaceGap = (value) => (
  Number(value || 0) > 0 ? wciCmdFmtAggregateUsd(value, '$0') : 'TIED'
);
const wciCmdFmtAggregateMarketCap = (countries) => (
  typeof wciFormatAggregateCountryMarketCap === 'function'
    ? wciFormatAggregateCountryMarketCap(countries, { fallback: '$--' })
    : wciCmdFmtAggregateUsd((countries || []).reduce((sum, country) => sum + Number(country.mcap || 0), 0), '$--')
);

const wciCmdGetPressure = (countries) => {
  const adapter = wciCmdAdapter();
  if (adapter?.getGlobalBuybackPressure) return adapter.getGlobalBuybackPressure();
  return {
    pendingWETH: countries.reduce((sum, country) => sum + (country.pendingWETH || 0), 0),
    buybackReadyCount: countries.filter((country) => country.buybackReady).length,
    activeCountries: countries.filter((country) => country.active !== false).length,
    eliminatedCountries: countries.filter((country) => country.active === false).length,
    thresholdWETH: wciCmdConstants().buybackThresholdWETH,
  };
};

const wciCmdGetActivity = (countries) => {
  const adapter = wciCmdAdapter();
  if (adapter?.getLiveActivitySummary) return adapter.getLiveActivitySummary();
  return {
    buysPerMinute: (countries || []).reduce((sum, country) => sum + Number(country.buysPerMinute || country.buys1m || 0), 0),
    recentBuyCount: (countries || []).reduce((sum, country) => sum + Number(country.recentBuyCount || 0), 0),
    recentBuyVolumeWETH: (countries || []).reduce((sum, country) => sum + Number(country.recentBuyVolumeWETH || 0), 0),
  };
};

const WciMetricTile = ({ label, value, meta, tone = 'cyan' }) => (
  <div className={`wci-metric-tile tone-${tone}`}>
    <div className="label">{label}</div>
    <div className="wci-metric-value mono">{value}</div>
    {meta && <div className="wci-metric-meta">{meta}</div>}
  </div>
);

const BattleObjectivesPanel = ({ battleIndex }) => {
  const index = battleIndex || {};
  const season = index.season || { label: 'Live 24h Battle', sprintLabel: '60m sprint' };
  const objectives = (index.objectives || []).slice(0, 4);
  const totalBuys = Number(index.rolling24h?.totalBuyCount || 0);
  const totalVolume = Number(index.rolling24h?.totalBuyVolumeWETH || 0);
  return (
    <section className="command-panel battle-objectives-panel" aria-label="Battle objectives">
      <div className="battle-window-summary">
        <div>
          <div className="label">STATIC INDEX WINDOW</div>
          <h2>{season.label}</h2>
        </div>
        <div className="battle-window-pills">
          <span>{season.sprintLabel || '60m sprint'}</span>
          <span>{totalBuys} buys</span>
          <span>{wciCmdFmtWeth(totalVolume, totalVolume >= 1 ? 3 : 4)}</span>
        </div>
      </div>
      <div className="battle-objective-grid">
        {objectives.map((objective) => (
          <button
            type="button"
            key={objective.type}
            className="battle-objective-card"
            style={{ '--objective-color': objective.accent || 'var(--fifa-cyan)', '--objective-pct': wciCmdFmtPct(objective.progress) }}
          >
            <span className="battle-objective-label">{objective.label}</span>
            <strong>{objective.title}</strong>
            <em>{objective.body}</em>
            <i aria-hidden="true"><b /></i>
          </button>
        ))}
      </div>
    </section>
  );
};

const wciCmdEventTitle = (event = {}) => {
  if (event.isCountryBuy) return 'Country Buy';
  if (event.type === 'BuybackReady') return 'Buy Flow Ready';
  if (event.type === 'BuybackExecuted') return 'Manual Ops';
  if (event.type === 'BuybackDeferred') return 'Ops Deferred';
  return event.type || 'Live Event';
};

const WciAllocationRow = ({ label, bucket, color = 'var(--fifa-cyan)' }) => {
  const used = bucket?.usedPct || 0;
  return (
    <div className="wci-allocation-row">
      <div className="wci-allocation-head">
        <div>
          <div className="wci-allocation-name">{label}</div>
          <div className="wci-allocation-purpose">{bucket?.purpose || 'Owner allocation only'}</div>
        </div>
        <div className="mono wci-allocation-number">{wciCmdFmtTokens(bucket?.remainingTokens)} remaining</div>
      </div>
      <div className="wci-allocation-track" aria-hidden="true">
        <div className="wci-allocation-fill" style={{ width: `${Math.max(0, Math.min(100, used))}%`, background: color }} />
      </div>
      <div className="wci-allocation-foot mono">
        <span>{wciCmdFmtTokens(bucket?.distributedTokens)} distributed</span>
        <span>{wciCmdFmtTokens(bucket?.totalTokens)} cap</span>
      </div>
    </div>
  );
};

const WciCountryPickerStrip = ({ countries, selectedCountry, onSelectCountry }) => (
  <div className="wci-country-picker-strip" aria-label="Country selector">
    {countries.slice(0, 16).map((country) => (
      <button
        key={country.code}
        type="button"
        className={`wci-country-chip ${selectedCountry?.code === country.code ? 'is-selected' : ''}`}
        onClick={() => onSelectCountry(country)}
        style={{ '--chip-color': country.color }}
      >
        <FlagRect code={country.code} w={18} h={12} />
        <span className="mono">{country.code}</span>
      </button>
    ))}
  </div>
);

const FederationLoopPanel = ({ countries, globalBuybackPressure, selectedCountry, hidden }) => {
  const activity = wciCmdGetActivity(countries);
  const totalVolumeUsd = typeof wciCountryVolumeUsd === 'function'
    ? countries.reduce((sum, country) => sum + wciCountryVolumeUsd(country), 0)
    : 0;
  const totalBuyPressureUsd = countries.reduce((sum, country) => sum + wciCmdBuyPressureUsd(country), 0);
  const totalMarketCapLabel = wciCmdFmtAggregateMarketCap(countries);
  const totalVolumeLabel = typeof wciFormatAggregateCountryVolume === 'function'
    ? wciFormatAggregateCountryVolume(countries, { fallback: '$0' })
    : wciCmdFmtAggregateUsd(totalVolumeUsd);
  const buyActivityLabel = wciCmdFmtAggregateUsd(totalBuyPressureUsd, '$0');
  return (
    <aside className={`federation-loop-panel ${hidden ? 'is-hidden' : ''}`} aria-label="Federation value loop">
      <div className="label">FEDERATION COMMAND CENTER</div>
      <div className="federation-loop-title">Country activity funds WCI26 strength</div>
      <div className="federation-loop-chain">
        <span>{countries.length}/48 country pools</span>
        <span>{activity.recentBuyCount || 0} recent buys</span>
        <span>{totalVolumeLabel} total country volume</span>
        <span>{buyActivityLabel} total buy activity</span>
      </div>
      <div className="federation-loop-grid">
        <WciMetricTile label="TOTAL COUNTRY MCAP" value={totalMarketCapLabel} meta={`${countries.length}/48 live country tokens`} tone="lime" />
        <WciMetricTile label="RECENT BUYS" value={`${activity.recentBuyCount || 0}`} meta="Indexed country buy events" tone="cyan" />
        <WciMetricTile label="TOTAL COUNTRY VOLUME" value={totalVolumeLabel} meta="Live Mainnet pool swaps" tone="gold" />
        <WciMetricTile label="TOTAL BUY ACTIVITY" value={buyActivityLabel} meta={`${activity.recentBuyCount || 0} recent buys`} tone="magenta" />
      </div>
    </aside>
  );
};

const WciEventFeed = ({ events }) => (
  <div className="wci-event-feed">
    {(events || []).slice(0, 7).map((event) => (
      <div className="wci-event-row" key={event.id}>
        <div className="wci-event-dot" />
        <div>
          <div className="wci-event-title">{wciCmdEventTitle(event)}</div>
          <div className="wci-event-meta">
            {event.countryName} {event.wethAmount ? `+${wciCmdFmtWeth(event.wethAmount, 4)}` : ''}
            {event.wethOwed ? ` ${wciCmdFmtWeth(event.wethOwed)} activity` : ''}
            {event.message ? ` ${event.message}` : ''}
          </div>
        </div>
      </div>
    ))}
  </div>
);

const wciBattleScore = (country) => (
  wciCmdMarketCapUsd(country)
  + wciCmdVolumeUsd(country) * 0.35
  + wciCmdBuyPressureUsd(country) * 0.5
  + wciCmdRecentBuyCount(country) * 750
);

const wciBuildBattleFeedRows = (events = [], countries = []) => {
  const countryByCode = Object.fromEntries((countries || []).map((country) => [country.code, country]));
  const fromEvents = (events || [])
    .filter((event) => event?.isoCode || event?.code)
    .filter((event) => (
      event.type === 'Swap'
      || event.isCountryBuy
      || Number(event.wethAmount || 0) > 0
      || Number(event.wethOwed || 0) > 0
    ))
    .map((event) => {
      const code = event.isoCode || event.code;
      const country = countryByCode[code] || {};
      const weth = Number(event.wethAmount || event.wethOwed || 0);
      return {
        id: event.id || `${event.txHash || code}-${event.logIndex || weth}`,
        code,
        country: country.name || event.countryName || code,
        label: event.isCountryBuy ? 'COUNTRY BUY' : Number(event.wethOwed || 0) > 0 ? 'BUY FLOW READY' : 'BATTLE MOVE',
        title: event.isCountryBuy ? `${code} buy flow landed` : `${code} activity changed`,
        metric: weth ? `+${wciCmdFmtWeth(weth, 4)}` : wciCmdFmtMarketCap(country),
        meta: event.isCountryBuy ? 'Live Uniswap V3 buy' : 'Live battle signal',
        color: country.color || 'var(--fifa-cyan)',
      };
    });
  const fallback = [...(countries || [])]
    .sort((a, b) => wciBattleScore(b) - wciBattleScore(a))
    .map((country, index) => ({
      id: `battle-feed-${country.code}`,
      code: country.code,
      country: country.name,
      label: index === 0 ? 'LEADER HOLD' : index < 3 ? 'CHASER HEAT' : 'BUY WATCH',
      title: index === 0 ? `${country.code} defending the top lane` : `${country.code} chasing market cap`,
      metric: `${wciCmdFmtMarketCap(country)} mcap`,
      meta: `${wciCmdFmtVolume(country)} volume - ${wciCmdRecentBuyCount(country)} buys`,
      color: country.color,
    }));
  const rows = [...fromEvents, ...fallback];
  const seen = new Set();
  return rows.filter((row) => {
    const key = row.id || `${row.code}-${row.label}`;
    if (seen.has(key)) return false;
    seen.add(key);
    return true;
  }).slice(0, 6);
};

const BattleDuelTeam = ({ country, side, maxScore }) => {
  const score = Math.max(0.01, wciBattleScore(country));
  const pct = Math.max(4, Math.min(100, (score / Math.max(1, maxScore)) * 100));
  return (
    <div className={`battle-duel-team side-${side}`} style={{ '--team-color': country?.color || 'var(--gold)', '--duel-pct': `${pct}%` }}>
      <div className="battle-duel-team-head">
        <FlagRect code={country?.code || 'BRA'} w={38} h={26} />
        <div>
          <span className="mono">{country?.code}</span>
          <strong>{country?.name}</strong>
        </div>
      </div>
      <div className="battle-duel-score mono">{wciCmdFmtMarketCap(country)}</div>
      <div className="battle-duel-track" aria-hidden="true"><span /></div>
      <div className="battle-duel-stats">
        <span>VOL <strong className="mono">{wciCmdFmtVolume(country)}</strong></span>
        <span>BUYS <strong className="mono">{wciCmdRecentBuyCount(country)}</strong></span>
      </div>
    </div>
  );
};

const BattleComparisonGraph = ({ leader, rival }) => {
  const rows = [
    ['Market cap', wciCmdMarketCapUsd(leader), wciCmdMarketCapUsd(rival), wciCmdFmtMarketCap],
    ['Total volume', wciCmdVolumeUsd(leader), wciCmdVolumeUsd(rival), wciCmdFmtVolume],
    ['Buy pressure', wciCmdBuyPressureUsd(leader), wciCmdBuyPressureUsd(rival), wciCmdFmtBuyPressure],
  ];
  return (
    <div className="battle-comparison-graph" aria-label="Country comparison graph">
      <div className="battle-comparison-head">
        <span className="label">Comparison Graph</span>
        <strong>{leader?.code || '--'} vs {rival?.code || '--'}</strong>
      </div>
      {rows.map(([label, leaderValue, rivalValue, formatter]) => {
        const max = Math.max(leaderValue, rivalValue, 1);
        const leaderPct = Math.max(4, Math.min(100, (leaderValue / max) * 100));
        const rivalPct = Math.max(4, Math.min(100, (rivalValue / max) * 100));
        return (
          <div
            key={label}
            className="battle-compare-row"
            style={{
              '--leader-color': leader?.color || 'var(--gold)',
              '--rival-color': rival?.color || 'var(--fifa-cyan)',
              '--leader-pct': `${leaderPct}%`,
              '--rival-pct': `${rivalPct}%`,
            }}
          >
            <div className="battle-compare-label">
              <span>{label}</span>
              <strong className="mono">{formatter(leader)} / {formatter(rival)}</strong>
            </div>
            <div className="battle-compare-bars" aria-hidden="true">
              <span className="leader-line" />
              <span className="rival-line" />
            </div>
          </div>
        );
      })}
    </div>
  );
};

const BattleRivalryPanel = ({ leader, rival, rivals, selectedCode, onPickRival, onSelectCountry }) => {
  const maxScore = Math.max(wciBattleScore(leader), wciBattleScore(rival), 1);
  const raceGap = Math.abs(wciBattleScore(leader) - wciBattleScore(rival));
  return (
    <div className="command-panel battle-rivalry-panel">
      <div className="command-panel-head">
        <div>
          <div className="label">LIVE RIVALRY ENGINE</div>
          <h2>Buy Flow Duel</h2>
        </div>
        <span className="command-state-pill mono">{wciCmdFmtRaceGap(raceGap)} race gap</span>
      </div>
      <div className="battle-duel-stage">
        <BattleDuelTeam country={leader} side="leader" maxScore={maxScore} />
        <button type="button" className="battle-duel-vs" onClick={() => onSelectCountry(rival)} aria-label={`Select ${rival?.name}`}>
          <span>VS</span>
        </button>
        <BattleDuelTeam country={rival} side="rival" maxScore={maxScore} />
      </div>
      <BattleComparisonGraph leader={leader} rival={rival} />
      <div className="battle-rival-chips" aria-label="Choose challenger">
        {rivals.slice(0, 6).map((country) => (
          <button
            key={country.code}
            type="button"
            className={`battle-rival-chip ${country.code === selectedCode ? 'is-active' : ''}`}
            onClick={() => onPickRival(country)}
            style={{ '--team-color': country.color }}
          >
            <FlagRect code={country.code} w={18} h={12} />
            <span className="mono">{country.code}</span>
            <strong>{wciCmdFmtMarketCap(country)}</strong>
          </button>
        ))}
      </div>
    </div>
  );
};

const BattleActivityPanel = ({ countries, events, onSelectCountry }) => {
  const activity = wciCmdGetActivity(countries);
  const sortedByScore = [...countries].sort((a, b) => wciBattleScore(b) - wciBattleScore(a));
  const leader = sortedByScore[0] || countries[0];
  const runner = sortedByScore[1] || leader;
  const hottest = [...countries].sort((a, b) => (
    Number(b.recentBuyVolumeWETH || 0) - Number(a.recentBuyVolumeWETH || 0)
    || wciCmdVolumeUsd(b) - wciCmdVolumeUsd(a)
  ))[0] || leader;
  const feedRows = wciBuildBattleFeedRows(events, countries);
  const leaderGap = Math.max(0, wciBattleScore(leader) - wciBattleScore(runner));
  const totalBuyPressureUsd = countries.reduce((sum, country) => sum + wciCmdBuyPressureUsd(country), 0);
  const metricRows = [
    ['RECENT BUYS', `${activity.recentBuyCount || 0}`, 'Indexed buy events', 'cyan'],
    ['LEADER GAP', wciCmdFmtRaceGap(leaderGap), `${leader?.code || '--'} vs ${runner?.code || '--'}`, 'gold'],
    ['HOTTEST BUY FLOW', hottest?.code || '--', wciCmdFmtVolume(hottest), 'lime'],
    ['TOTAL BUY PRESSURE', wciCmdFmtAggregateUsd(totalBuyPressureUsd, '$0'), `${activity.recentBuyCount || 0} recent buys`, 'magenta'],
  ];
  return (
    <div className="command-panel battle-activity-panel">
      <div className="command-panel-head">
        <div>
          <div className="label">VS BATTLE FEED</div>
          <h2>Live battle pulse</h2>
        </div>
        <span className="command-state-pill">Mainnet live</span>
      </div>
      <div className="battle-battle-metrics">
        {metricRows.map(([label, value, meta, tone]) => (
          <div className={`battle-battle-metric tone-${tone}`} key={label}>
            <span>{label}</span>
            <strong className="mono">{value}</strong>
            <small>{meta}</small>
          </div>
        ))}
      </div>
      <div className="battle-feed-list">
        {feedRows.map((row) => (
          <button
            key={row.id}
            type="button"
            className="battle-feed-row"
            onClick={() => {
              const country = countries.find((candidate) => candidate.code === row.code);
              if (country) onSelectCountry(country);
            }}
            style={{ '--feed-color': row.color || 'var(--fifa-cyan)' }}
          >
            <span className="battle-feed-pulse" />
            <span>
              <small>{row.label}</small>
              <strong>{row.title}</strong>
              <em>{row.meta}</em>
            </span>
            <span className="mono">{row.metric}</span>
          </button>
        ))}
      </div>
    </div>
  );
};

const BattleSeasonView = ({ countries, selectedCountry, onSelectCountry }) => {
  const adapter = wciCmdAdapter();
  const tournament = adapter?.getTournamentState ? adapter.getTournamentState() : null;
  const events = adapter?.getRecentEvents ? adapter.getRecentEvents() : [];
  const battleIndex = adapter?.getBattleIndex ? adapter.getBattleIndex() : (
    typeof WCI_STATIC_INDEXER !== 'undefined'
      ? WCI_STATIC_INDEXER.buildSnapshot({ countries, events })
      : null
  );
  const [mode, setMode] = React.useState('marketCap');
  const [rivalCode, setRivalCode] = React.useState(null);
  const modes = [
    ['marketCap', 'Market Cap'],
    ['volume', 'Volume'],
    ['buyPressure', 'Buy Pressure'],
  ];
  const maxMarketCap = Math.max(1, ...countries.map(wciCmdMarketCapUsd));
  const maxVolume = Math.max(1, ...countries.map(wciCmdVolumeUsd));
  const maxBuyPressureUsd = Math.max(1, ...countries.map(wciCmdBuyPressureUsd));
  const scoreFor = (country) => {
    if (mode === 'volume') return wciCmdVolumeUsd(country);
    if (mode === 'buyPressure') return wciCmdBuyPressureUsd(country);
    return wciCmdMarketCapUsd(country);
  };
  const leaderboard = [...countries]
    .sort((a, b) => scoreFor(b) - scoreFor(a) || wciCmdMarketCapUsd(b) - wciCmdMarketCapUsd(a) || (a.rank || 999) - (b.rank || 999))
    .map((country, index) => ({ ...country, raceRank: index + 1 }));
  const champion = leaderboard[0] || countries[0];
  const totalMarketCap = countries.reduce((sum, country) => sum + wciCmdMarketCapUsd(country), 0);
  const totalVolume = countries.reduce((sum, country) => sum + wciCmdVolumeUsd(country), 0);
  const totalBuyPressureUsd = countries.reduce((sum, country) => sum + wciCmdBuyPressureUsd(country), 0);
  const totalRecentBuys = countries.reduce((sum, country) => sum + wciCmdRecentBuyCount(country), 0);
  const battleLeaders = [...countries]
    .sort((a, b) => wciBattleScore(b) - wciBattleScore(a) || (a.rank || 999) - (b.rank || 999));
  const duelLeader = selectedCountry || battleLeaders[0] || champion;
  const rivalOptions = battleLeaders.filter((country) => country.code !== duelLeader?.code);
  const duelRival = rivalOptions.find((country) => country.code === rivalCode) || rivalOptions[0] || duelLeader;
  React.useEffect(() => {
    if (!rivalOptions.length) return;
    if (!rivalOptions.some((country) => country.code === rivalCode)) {
      setRivalCode(rivalOptions[0].code);
    }
  }, [duelLeader?.code, countries.length]);
  const handlePickRival = (country) => {
    setRivalCode(country.code);
    onSelectCountry(country);
  };

  return (
    <div className="command-page main-scroll" data-screen-label="02 Battle">
      <div className="command-page-inner">
        <section className="command-hero-band battle-race-hero">
          <div>
            <div className="label">BATTLE VIEW</div>
            <h1>National Power Race</h1>
            <p>Live market cap, country pool volume, and buy flow determine the race board. Every bar is pulled from the Ethereum mainnet country contracts and Uniswap V3 pool reads.</p>
            <div className="battle-hero-mode-strip" aria-label="Battle metric focus">
              {modes.map(([key, label]) => (
                <button key={key} type="button" className={mode === key ? 'is-active' : ''} onClick={() => setMode(key)}>
                  {label}
                </button>
              ))}
            </div>
          </div>
          <div className="command-hero-stats">
            <WciMetricTile label="TOTAL COUNTRY MCAP" value={wciCmdFmtAggregateUsd(totalMarketCap, '$--')} meta="48 country-token caps" tone="lime" />
            <WciMetricTile label="TOTAL COUNTRY VOLUME" value={wciCmdFmtAggregateUsd(totalVolume)} meta={`${tournament?.activeCount || countries.length}/48 active`} tone="cyan" />
            <WciMetricTile label="TOTAL BUY PRESSURE" value={wciCmdFmtAggregateUsd(totalBuyPressureUsd)} meta={`${totalRecentBuys} recent buys`} tone="gold" />
          </div>
        </section>

        <BattleObjectivesPanel battleIndex={battleIndex} />

        <section className="battle-grid">
          <BattleRivalryPanel
            leader={duelLeader}
            rival={duelRival}
            rivals={rivalOptions}
            selectedCode={duelRival?.code}
            onPickRival={handlePickRival}
            onSelectCountry={onSelectCountry}
          />
          <BattleActivityPanel countries={countries} events={events} onSelectCountry={onSelectCountry} />
        </section>

        <section className="command-panel leaderboard-command battle-race-command">
          <div className="command-panel-head">
            <div>
              <div className="label">COUNTRY LEADERBOARDS</div>
              <h2>{modes.find(([key]) => key === mode)?.[1]} Ladder</h2>
            </div>
            <div className="command-segmented">
              {modes.map(([key, label]) => (
                <button key={key} type="button" className={mode === key ? 'is-active' : ''} onClick={() => setMode(key)}>
                  {label}
                </button>
              ))}
            </div>
          </div>
          <div className="battle-race-board">
            {leaderboard.map((country) => {
              const mcapUsd = wciCmdMarketCapUsd(country);
              const volumeUsd = wciCmdVolumeUsd(country);
              const buyPressureUsd = wciCmdBuyPressureUsd(country);
              const leaderScore = Math.max(1, scoreFor(champion));
              const primaryPct = Math.max(6, Math.min(28, (scoreFor(country) / (leaderScore * 5)) * 100));
              const marketPct = Math.max(6, Math.min(28, (mcapUsd / (maxMarketCap * 5)) * 100));
              const volumePct = Math.max(6, Math.min(28, (volumeUsd / (maxVolume * 5)) * 100));
              const pressurePct = Math.max(6, Math.min(28, (buyPressureUsd / (maxBuyPressureUsd * 5)) * 100));
              const isSelected = selectedCountry?.code === country.code;
              return (
                <button
                  key={country.code}
                  type="button"
                  className={`battle-race-row ${isSelected ? 'is-selected' : ''}`}
                  onClick={() => onSelectCountry(country)}
                  style={{
                    '--row-color': country.color,
                    '--row-secondary': country.secondary || country.color,
                    '--primary-pct': `${primaryPct}%`,
                    '--mcap-pct': `${marketPct}%`,
                    '--volume-pct': `${volumePct}%`,
                    '--pressure-pct': `${pressurePct}%`,
                  }}
                >
                  <span className="battle-race-rank mono">P{country.raceRank}</span>
                  <FlagRect code={country.code} w={30} h={20} />
                  <span className="battle-race-code mono">{country.code}</span>
                  <span className="battle-race-track" aria-hidden="true">
                    <span className="battle-race-fill" />
                    <span className="battle-race-orb mono">{country.code.slice(0, 1)}</span>
                  </span>
                  <span className="battle-race-values mono">
                    <strong>MCAP {wciCmdFmtMarketCap(country)}</strong>
                    <small>VOL {wciCmdFmtVolume(country)} · BUYS {wciCmdRecentBuyCount(country)}</small>
                  </span>
                </button>
              );
            })}
          </div>
        </section>

        <section className="command-panel group-results-panel">
          <div className="command-panel-head">
            <div>
              <div className="label">TOURNAMENT MODULE</div>
              <h2>Group-stage results</h2>
            </div>
            <div className="mono command-state-pill">Country eliminations/reinstatements tracked</div>
          </div>
          <div className="group-result-grid">
            {(tournament?.groupStageResults || []).slice(0, 8).map((result) => (
              <div className="group-result-row" key={result.matchId}>
                <span className="mono">M{result.matchId}</span>
                <strong>{result.winner}</strong>
                <span>over</span>
                <span>{result.loser || 'TBD'}</span>
              </div>
            ))}
          </div>
        </section>
      </div>
    </div>
  );
};

const RewardsCenterView = ({ countries, selectedCountry, onSelectCountry }) => {
  return (
    <div className="command-page main-scroll" data-screen-label="03 Rewards">
      <div className="command-page-inner rewards-locked-shell">
        <section className="rewards-coming-soon-modal" aria-label="Rewards coming soon">
          <div className="rewards-token-art-wrap" aria-hidden="true">
            <img className="rewards-token-art" src="assets/tokens.png" alt="" loading="eager" />
          </div>
          <div className="label">REWARD VAULT PREVIEW</div>
          <h1>Rewards vault opening soon</h1>
          <p>Season missions, supporter badges, and country prize lanes are being shaped around real indexed activity. Claims stay locked until the rules, balances, and payout paths are ready to open cleanly.</p>
          <div className="rewards-soon-stats">
            <span>Season quests</span>
            <span>Supporter badges</span>
            <span>Country prize lanes</span>
            <span>Live claim rules</span>
          </div>
        </section>
      </div>
    </div>
  );
};

const wciCmdShortAddress = (value) => {
  const text = String(value || '');
  return text.length > 12 ? `${text.slice(0, 6)}...${text.slice(-4)}` : (text || 'Pending');
};

const wciCmdCountryTicker = (country) => (
  country.tokenSymbol || (typeof wciCountryDollarTicker === 'function' ? wciCountryDollarTicker(country) : `$${country.code}`)
);

const wciCmdFmtHolders = (value) => {
  const n = Number(value || 0);
  if (typeof fmtNum === 'function') return fmtNum(n);
  if (n >= 1000000) return `${(n / 1000000).toFixed(1)}M`;
  if (n >= 1000) return `${(n / 1000).toFixed(1)}K`;
  return `${Math.max(0, Math.round(n))}`;
};

const wciCmdFmtPrice = (country) => (
  typeof wciFormatCountryPrice === 'function'
    ? wciFormatCountryPrice(country, { fallback: '$--' })
    : '$--'
);

const wciCmdTeamMetrics = (country) => [
  ['VOLUME', wciCmdFmtVolume(country), 'Country pool volume'],
  ['MARKET CAP', wciCmdFmtMarketCap(country), 'Dextools-style live cap'],
  ['HOLDERS', wciCmdFmtHolders(country.holders), country.holderDataState === 'transfer-log-indexed' ? 'Transfer-log indexed' : 'Live token holders'],
  ['BUY PRESSURE', wciCmdFmtBuyPressure(country), `${wciCmdRecentBuyCount(country)} recent buys`],
];

const WciTeamCardMetric = ({ label, value, meta }) => (
  <div className="team-card-metric">
    <span>{label}</span>
    <strong className="mono">{value}</strong>
    <small>{meta}</small>
  </div>
);

const WciTeamMetricBar = ({ label, value, pct, tone = 'gold' }) => (
  <div className={`team-metric-bar tone-${tone}`} style={{ '--bar-pct': `${Math.max(2, Math.min(100, Number(pct || 0)))}%` }}>
    <div>
      <span>{label}</span>
      <strong className="mono">{value}</strong>
    </div>
    <div className="team-metric-track" aria-hidden="true"><span /></div>
  </div>
);

const WciTeamWatchChart = ({
  country,
  countries = [],
  maxMarketCapUsd = 1,
  maxVolumeUsd = 1,
  maxBuyPressureUsd = 1,
}) => {
  const focused = country || countries[0];
  const lineup = (countries.length ? countries : [focused]).filter(Boolean);
  if (!focused) {
    return (
      <div className="team-watch-chart is-empty">
        <div className="label">WATCHLIST ARENA</div>
        <strong>Pick teams below to activate the board.</strong>
      </div>
    );
  }
  const focusedMarketPct = Math.max(2, Math.min(44, (wciCmdMarketCapUsd(focused) / Math.max(1, maxMarketCapUsd * 2.35)) * 100));
  const focusedVolumePct = Math.max(2, Math.min(44, (wciCmdVolumeUsd(focused) / Math.max(1, maxVolumeUsd * 2.35)) * 100));
  const focusedPressurePct = Math.max(2, Math.min(44, (wciCmdBuyPressureUsd(focused) / Math.max(1, maxBuyPressureUsd * 2.35)) * 100));
  return (
    <div className="team-watch-chart" style={{
      '--team-color': focused.color || 'var(--gold)',
      '--team-secondary': focused.secondary || focused.color || 'var(--fifa-cyan)',
      '--focus-mcap': `${focusedMarketPct}%`,
      '--focus-volume': `${focusedVolumePct}%`,
      '--focus-pressure': `${focusedPressurePct}%`,
    }}>
      <div className="team-chart-head">
        <div>
          <div className="label">WATCHLIST ARENA</div>
          <strong>{focused.name}</strong>
        </div>
        <span className="mono">{wciCmdFmtMarketCap(focused)} MCAP</span>
      </div>
      <div className="team-chart-track-stack" aria-hidden="true">
        <span className="mcap-line" />
        <span className="volume-line" />
        <span className="pressure-line" />
      </div>
      <div className="team-chart-grid">
        {lineup.map((team) => {
          const capPct = Math.max(2, Math.min(44, (wciCmdMarketCapUsd(team) / Math.max(1, maxMarketCapUsd * 2.35)) * 100));
          const pressurePct = Math.max(2, Math.min(44, (wciCmdBuyPressureUsd(team) / Math.max(1, maxBuyPressureUsd * 2.35)) * 100));
          return (
            <div className={`team-chart-row ${team.code === focused.code ? 'is-focused' : ''}`} key={team.code} style={{
              '--team-color': team.color,
              '--cap-pct': `${capPct}%`,
              '--pressure-pct': `${pressurePct}%`,
            }}>
              <FlagRect code={team.code} w={22} h={15} />
              <span className="mono">{team.code}</span>
              <div className="team-chart-mini-bars">
                <span className="team-chart-cap" />
                <span className="team-chart-pressure" />
              </div>
              <strong className="mono">{wciCmdFmtMarketCap(team)}</strong>
            </div>
          );
        })}
      </div>
      <div className="team-chart-legend">
        <span>Market cap</span>
        <span>Volume</span>
        <span>Buy pressure</span>
      </div>
    </div>
  );
};

const CountryInspectModal = ({ country, onClose, onBuy }) => {
  if (!country) return null;
  const rows = [
    ['Market cap', wciCmdFmtMarketCap(country), 'Live country token cap'],
    ['Volume', wciCmdFmtVolume(country), 'Country pool volume'],
    ['Buy pressure', wciCmdFmtBuyPressure(country), `${wciCmdRecentBuyCount(country)} recent buys`],
    ['Recent buys', `${Number(country.recentBuyCount || 0)}`, `${wciCmdFmtBuyPressure(country)} tracked buy activity`],
  ];
  return (
    <div className="country-inspect-backdrop" role="presentation">
      <section className="country-inspect-modal" role="dialog" aria-modal="true" aria-label={`${country.name} live metrics`} style={{ '--country-color': country.color }}>
        <button type="button" className="country-inspect-close" onClick={onClose}>Close</button>
        <div className="country-inspect-hero">
          <FlagRect code={country.code} w={74} h={50} />
          <div>
            <div className="label">LIVE COUNTRY SCOUTING REPORT</div>
            <h2>{country.name}</h2>
            <p className="mono">{wciCmdCountryTicker(country)} - Rank #{country.rank || '-'}</p>
          </div>
        </div>
        <div className="country-inspect-metrics">
          {rows.map(([label, value, meta]) => (
            <div className="country-inspect-metric" key={label}>
              <span>{label}</span>
              <strong className="mono">{value}</strong>
              <small>{meta}</small>
            </div>
          ))}
        </div>
        <div className="country-inspect-contracts">
          <div>
            <span>Token contract</span>
            <strong className="mono">{country.tokenAddress || 'Pending'}</strong>
          </div>
          <div>
            <span>Uniswap pool</span>
            <strong className="mono">{country.poolAddress || country.pool || 'Pending'}</strong>
          </div>
        </div>
        <div className="country-inspect-actions">
          <button type="button" className="team-buy-action is-large" onClick={() => onBuy?.(country)}>Buy this country</button>
        </div>
      </section>
    </div>
  );
};

const WciTeamMonitorCard = ({
  country,
  monitored,
  compact = false,
  uncheckWhenMonitored = false,
  onInspect,
  onToggle,
  onBackCountry,
  maxMarketCapUsd = 1,
  maxBuyPressureUsd = 1,
}) => {
  const ticker = wciCmdCountryTicker(country);
  const marketCapUsd = wciCmdMarketCapUsd(country);
  const buyPressureUsd = wciCmdBuyPressureUsd(country);
  const marketPct = Math.max(2, Math.min(44, (marketCapUsd / Math.max(1, maxMarketCapUsd * 2.35)) * 100));
  const pressurePct = Math.max(2, Math.min(44, (buyPressureUsd / Math.max(1, maxBuyPressureUsd * 2.35)) * 100));
  const segmentCount = 7;
  const activeSegments = Math.max(1, Math.min(segmentCount, Math.ceil((marketPct / 100) * segmentCount)));
  return (
    <article
      className={`team-picker-card team-watch-card ${monitored ? 'is-monitored' : ''} ${compact ? 'is-compact' : ''}`}
      data-watch-card="rich"
      style={{ '--team-color': country.color, '--team-progress': `${marketPct}%` }}
    >
      <span className="team-card-edge-line" aria-hidden="true" />
      <div className="team-card-top">
        <div className="team-flag-frame">
          <FlagRect code={country.code} w={compact ? 42 : 48} h={compact ? 28 : 32} />
        </div>
        <div className="team-picker-identity">
          <div className="team-picker-code mono">{country.code}</div>
          <div className="team-picker-name">{country.name}</div>
          <div className="team-picker-meta mono">
            <span>{ticker}</span>
            <span>{wciCmdShortAddress(country.tokenAddress)} token</span>
          </div>
        </div>
        <div className="team-status-stack">
          <span className="team-rank-badge mono">#{country.rank || '-'}</span>
          <span className={`team-live-badge ${country.active === false ? 'is-off' : ''}`}>{country.active === false ? 'Out' : 'Live'}</span>
        </div>
      </div>

      <div className="team-card-price-line">
        <strong className="mono">{wciCmdFmtPrice(country)}</strong>
        <span className="mono">{wciCmdFmtCountryChange(country)}</span>
      </div>

      <div className="team-card-segment-bars" aria-hidden="true">
        {Array.from({ length: segmentCount }).map((_, index) => (
          <span key={index} className={index < activeSegments ? 'is-lit' : ''} />
        ))}
      </div>

      <div className="team-card-metrics">
        {wciCmdTeamMetrics(country).map(([label, value, meta]) => (
          <WciTeamCardMetric key={label} label={label} value={value} meta={meta} />
        ))}
      </div>

      <div className="team-card-power team-live-bars">
        <WciTeamMetricBar label="Market cap bar" value={wciCmdFmtMarketCap(country)} pct={marketPct} tone="gold" />
        <WciTeamMetricBar label="Buy pressure bar" value={wciCmdFmtBuyPressure(country)} pct={pressurePct} tone="lime" />
      </div>

      <div className="team-picker-actions">
        <button type="button" className="team-secondary-action" onClick={() => onInspect?.(country)}>
          Inspect
        </button>
        {onBackCountry && (
          <button type="button" className="team-buy-action" onClick={() => onBackCountry(country)}>
            Buy
          </button>
        )}
        <button
          type="button"
          className={`team-pick-action ${monitored ? 'is-active' : ''} ${monitored && uncheckWhenMonitored ? 'is-danger' : ''}`}
          onClick={() => onToggle(country)}
        >
          {monitored && uncheckWhenMonitored ? 'Uncheck team' : monitored ? 'Monitoring' : 'Pick this team'}
        </button>
      </div>
    </article>
  );
};

const CountryDetailView = ({
  countries,
  country,
  monitoredTeamCodes = [],
  onSelectCountry,
  onToggleTeamMonitor,
  onBackCountry,
  supporterPanel = null,
  supporterNotice = '',
  onDismissSupporterNotice,
}) => {
  const adapter = wciCmdAdapter();
  const liveReadiness = typeof WCI_LIVE_ADAPTER !== 'undefined' && WCI_LIVE_ADAPTER.getReadiness
    ? WCI_LIVE_ADAPTER.getReadiness()
    : null;
  const liveModeLabel = typeof WCI_LIVE_ADAPTER !== 'undefined' && WCI_LIVE_ADAPTER.getModeLabel
    ? WCI_LIVE_ADAPTER.getModeLabel()
    : 'Addresses pending';
  const tournament = adapter?.getTournamentState ? adapter.getTournamentState() : null;
  const monitoredSet = new Set(monitoredTeamCodes);
  const monitoredCountries = monitoredTeamCodes
    .map((code) => countries.find((team) => team.code === code))
    .filter(Boolean);
  const [inspectCountry, setInspectCountry] = React.useState(null);
  const [focusedMonitorCode, setFocusedMonitorCode] = React.useState(null);
  React.useEffect(() => {
    const codes = monitoredCountries.map((team) => team.code);
    if (!codes.length) {
      setFocusedMonitorCode(null);
      return;
    }
    setFocusedMonitorCode((current) => (codes.includes(current) ? current : codes[0]));
  }, [monitoredTeamCodes.join('|')]);
  const selectedCount = monitoredCountries.length;
  const readyCount = liveReadiness?.readyCountryCount || countries.filter((team) => team.liveDeployment?.ready).length;
  const activeCount = tournament?.activeCount || countries.filter((team) => team.active !== false).length;
  const maxMarketCapUsd = Math.max(1, ...countries.map(wciCmdMarketCapUsd));
  const maxVolumeUsd = Math.max(1, ...countries.map(wciCmdVolumeUsd));
  const maxBuyPressureUsd = Math.max(1, ...countries.map(wciCmdBuyPressureUsd));
  const monitoredVolumeUsd = typeof wciCountryVolumeUsd === 'function'
    ? monitoredCountries.reduce((sum, team) => sum + wciCountryVolumeUsd(team), 0)
    : 0;
  const monitoredMarketCapUsd = typeof wciCountryMarketCapUsd === 'function'
    ? monitoredCountries.reduce((sum, team) => sum + wciCountryMarketCapUsd(team), 0)
    : 0;
  const monitoredBuyPressureUsd = monitoredCountries.reduce((sum, team) => sum + wciCmdBuyPressureUsd(team), 0);
  const selectedCopy = selectedCount === 1 ? '1 team monitored' : `${selectedCount} teams monitored`;
  const focusedMonitorCountry = monitoredCountries.find((team) => team.code === focusedMonitorCode) || monitoredCountries[0] || country || countries[0];
  const spotlightCountry = focusedMonitorCountry;
  const topRanked = monitoredCountries.length
    ? [...monitoredCountries].sort((a, b) => (a.rank || 999) - (b.rank || 999))[0]
    : countries[0];
  const handleModalBuy = (team) => {
    setInspectCountry(null);
    onBackCountry?.(team);
  };

  return (
    <div className="command-page main-scroll" data-screen-label="04 My Team">
      <div className="command-page-inner team-monitor-inner">
        <section className="team-monitor-hero">
          <div className="team-monitor-copy">
            <div className="label">TEAMS COMMAND</div>
            <h1>Pick teams to monitor</h1>
            <p>Choose one or multiple countries to pin here. This is your live Mainnet watchlist for country market cap, volume, rank, and buy activity.</p>
            <div className="team-monitor-spotlight" style={{ '--team-color': spotlightCountry?.color || 'var(--gold)' }}>
              <FlagRect code={spotlightCountry?.code || 'BRA'} w={58} h={39} />
              <div>
                <span className="label">SPOTLIGHT</span>
                <strong>{spotlightCountry?.name || 'No team selected'}</strong>
                <small className="mono">{wciCmdCountryTicker(spotlightCountry || {})} · Rank #{spotlightCountry?.rank || '-'}</small>
              </div>
            </div>
            {selectedCount > 0 && (
              <div className="team-focus-tabs" role="tablist" aria-label="Monitored team focus">
                {monitoredCountries.map((team) => (
                  <button
                    key={team.code}
                    type="button"
                    className={`team-focus-tab ${team.code === spotlightCountry?.code ? 'is-active' : ''}`}
                    onClick={() => setFocusedMonitorCode(team.code)}
                    style={{ '--team-color': team.color }}
                  >
                    <FlagRect code={team.code} w={18} h={12} />
                    <span className="mono">{team.code}</span>
                  </button>
                ))}
              </div>
            )}
            <WciTeamWatchChart
              country={spotlightCountry}
              countries={monitoredCountries}
              maxMarketCapUsd={maxMarketCapUsd}
              maxVolumeUsd={maxVolumeUsd}
              maxBuyPressureUsd={maxBuyPressureUsd}
            />
          </div>
          <div className="team-monitor-summary">
            {supporterNotice && (
              <div className="wallet-connected-routing" role="status">
                <span>Read-only wallet connected</span>
                <strong>{supporterNotice}</strong>
                {onDismissSupporterNotice && (
                  <button type="button" onClick={onDismissSupporterNotice} aria-label="Dismiss wallet notice">Dismiss</button>
                )}
              </div>
            )}
            {supporterPanel && (
              <div className="team-supporter-slot">
                {supporterPanel}
              </div>
            )}
            <div className={`team-monitor-kpi ${selectedCount ? 'tone-lime' : 'tone-gold'}`}>
              <span>Selected teams</span>
              <strong>{selectedCopy}</strong>
              <small>{readyCount}/48 Mainnet pools ready</small>
            </div>
            <div className="team-monitor-kpi tone-cyan">
              <span>Watchlist cap</span>
              <strong className="mono">{wciCmdFmtAggregateUsd(monitoredMarketCapUsd, '$--')}</strong>
              <small>{topRanked?.name || 'Pick a country'} leads the board</small>
            </div>
            <div className="team-monitor-kpi tone-magenta">
              <span>Total buy pressure</span>
              <strong className="mono">{wciCmdFmtAggregateUsd(monitoredBuyPressureUsd)}</strong>
              <small>{wciCmdFmtAggregateUsd(monitoredVolumeUsd)} tracked volume · {activeCount}/48 active</small>
            </div>
          </div>
        </section>

        <section className="command-panel monitored-team-panel">
          <div className="command-panel-head">
            <div>
              <div className="label">MONITORED TEAMS</div>
              <h2>{selectedCopy}</h2>
            </div>
            {selectedCount > 0 && <div className="command-state-pill">Live watchlist</div>}
          </div>
          {selectedCount === 0 ? (
            <div className="team-monitor-empty">
              <div className="label">NO TEAMS PICKED</div>
              <div>Pick teams below to build your monitoring board.</div>
            </div>
          ) : (
            <div className="monitored-team-grid">
              {monitoredCountries.map((team) => (
                <div className="monitored-team-card" key={team.code} style={{ '--team-color': team.color }}>
                  <WciTeamMonitorCard
                    country={team}
                    monitored
                    compact
                    uncheckWhenMonitored
                    onInspect={setInspectCountry}
                    onToggle={onToggleTeamMonitor}
                    onBackCountry={onBackCountry}
                    maxMarketCapUsd={maxMarketCapUsd}
                    maxBuyPressureUsd={maxBuyPressureUsd}
                  />
                </div>
              ))}
            </div>
          )}
        </section>

        <section className="command-panel team-picker-panel">
          <div className="command-panel-head">
            <div>
              <div className="label">ALL COUNTRIES</div>
              <h2>Choose new teams to monitor</h2>
            </div>
            <div className="command-state-pill">{countries.length}/48 available</div>
          </div>
          <div className="team-picker-grid">
            {countries.map((team) => (
              <WciTeamMonitorCard
                key={team.code}
                country={team}
                monitored={monitoredSet.has(team.code)}
                onInspect={setInspectCountry}
                onToggle={onToggleTeamMonitor}
                onBackCountry={onBackCountry}
                maxMarketCapUsd={maxMarketCapUsd}
                maxBuyPressureUsd={maxBuyPressureUsd}
              />
            ))}
          </div>
        </section>
      </div>
      <CountryInspectModal
        country={inspectCountry}
        onClose={() => setInspectCountry(null)}
        onBuy={handleModalBuy}
      />
    </div>
  );
};

Object.assign(window, {
  FederationLoopPanel,
  BattleSeasonView,
  RewardsCenterView,
  CountryDetailView,
});
