// wci26_pwa/m-screens.jsx - mobile PWA screens (Live, Globe, Battle, Teams)

const fmtTimeAgo = (ts) => {
  const s = Math.max(1, Math.floor((Date.now() - ts) / 1000));
  if (s < 60) return s + 's';
  if (s < 3600) return Math.floor(s / 60) + 'm';
  return Math.floor(s / 3600) + 'h';
};

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

const mFmtCountryPrice = (country) => (
  typeof wciFormatCountryPrice === 'function' ? wciFormatCountryPrice(country) : fmtPrice(country?.price || 0)
);

const mCountryMcapValue = (country) => Number(country?.marketCapWETH || country?.mcap || 0);
const mCountryVolumeValue = (country) => Number(country?.volume24h || 0);
const mCountryPressureValue = (country) => Number(country?.recentBuyVolumeWETH || country?.pendingWETH || 0);

const mFmtCountryMcap = (country) => (
  country && typeof wciFormatCountryMarketCap === 'function' ? wciFormatCountryMarketCap(country) : '$--'
);

const mFmtBuyPressure = (country) => (
  typeof wciFormatWethUsd === 'function' ? wciFormatWethUsd(mCountryPressureValue(country)) : '$0'
);

const mRacePct = (value, max, min = 6, cap = 62) => {
  const number = Number(value || 0);
  if (!Number.isFinite(number) || number <= 0) return '4%';
  return `${Math.max(min, Math.min(cap, (number / Math.max(1, max * 1.85)) * 100))}%`;
};

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

const mFmtSupporterUsd = (value) => (
  typeof wciFormatCompactUsd === 'function'
    ? wciFormatCompactUsd(value, '$0')
    : `$${Math.round(Number(value || 0)).toLocaleString('en-US')}`
);

const mPlural = (count, singular, plural = `${singular}s`) => `${count} ${Number(count) === 1 ? singular : plural}`;

const MOBILE_WCI26_HOME_URL = 'https://www.wci26.com/';
const MOBILE_WCI26_X_URL = 'https://x.com/WCI_26';
const MOBILE_WCI26_TELEGRAM_URL = 'https://t.me/WCI_26';

const MobileSocialLinks = () => (
  <>
    <NavPill href={MOBILE_WCI26_X_URL} ariaLabel="WCI26 on X" title="WCI26 on X">
      {Icon.xSocial('rgba(255,255,255,0.92)')}
    </NavPill>
    <NavPill href={MOBILE_WCI26_TELEGRAM_URL} ariaLabel="WCI26 Telegram" title="WCI26 Telegram">
      {Icon.telegram('rgba(78,209,230,0.96)')}
    </NavPill>
    <NavPill href={MOBILE_WCI26_HOME_URL} ariaLabel="Visit WCI26.com" title="Visit WCI26.com">
      {Icon.globe(false, 'rgba(245,208,32,0.96)')}
    </NavPill>
  </>
);

// ═════════════════════════════════════════════════════════════
// LIVE — the home / hero screen
// ═════════════════════════════════════════════════════════════
const LiveScreen = ({ countries, buybackPool, ticker, portfolio, watchlist, wciMarket, onPick }) => {
  const champ = countries[0];
  const fillPct = Math.min(100, (champ.volume24h / 2_500_000) * 100);
  const top3 = countries.slice(0, 3);
  const movers = [...countries].sort((a, b) => b.change24h - a.change24h).slice(0, 8);
  const market = wciMarket || (
    typeof WCI_MARKET_DATA !== 'undefined' && WCI_MARKET_DATA.getSnapshot
      ? WCI_MARKET_DATA.getSnapshot()
      : {}
  );
  const marketPriceLabel = typeof wciFormatUsdPrice === 'function'
    ? wciFormatUsdPrice(market.priceUsd ?? market.price)
    : (Number(market.priceUsd ?? market.price) > 0 ? `$${Number(market.priceUsd ?? market.price).toFixed(4)}` : '--');
  const marketChange = Number(market.priceChange24h ?? market.change24h ?? 0);
  const marketChangeLabel = typeof wciFormatPct === 'function'
    ? wciFormatPct(marketChange)
    : `${marketChange >= 0 ? '+' : ''}${marketChange.toFixed(1)}%`;
  const marketVolumeLabel = typeof wciFormatCompactUsd === 'function'
    ? wciFormatCompactUsd(market.volume24hUsd, '$0')
    : (typeof fmtMcap === 'function' ? fmtMcap(Number(market.volume24hUsd || 0)) : '$0');
  const marketCapLabel = typeof wciFormatCompactUsd === 'function'
    ? wciFormatCompactUsd(market.marketCapUsd)
    : (typeof fmtMcap === 'function' ? fmtMcap(Number(market.marketCapUsd || 0)) : '--');

  return (
    <>
      <NavBar
        title="Live"
        eyebrow={<><span style={{ marginRight: 6 }}>●</span>WCI26 · MATCHDAY 14</>}
        leading={<SyncPill online={true} />}
        trailing={<MobileSocialLinks />}
      />

      {/* HERO — Golden Boot */}
      <div style={{ padding: '6px 16px 0' }}>
        <div className="m-card" style={{
          display: 'grid',
          gridTemplateColumns: 'minmax(0, 1.2fr) minmax(0, 0.8fr) minmax(0, 0.8fr)',
          gap: 10,
          alignItems: 'center',
          padding: '12px 14px',
          borderColor: 'rgba(245,208,32,0.28)',
          background: 'linear-gradient(180deg, rgba(41,31,82,0.68), rgba(20,16,40,0.84))',
        }}>
          <div style={{ minWidth: 0 }}>
            <div className="label" style={{ fontSize: 9, color: 'var(--gold)' }}>$WCI26 LIVE</div>
            <div className="mono tnum" style={{ marginTop: 4, fontSize: 20, fontWeight: 800, color: '#fff', whiteSpace: 'nowrap' }}>
              {marketPriceLabel}
            </div>
          </div>
          <div style={{ textAlign: 'right', minWidth: 0 }}>
            <div className="label" style={{ fontSize: 8 }}>24H</div>
            <div className="mono" style={{ marginTop: 5, fontSize: 13, fontWeight: 800, color: marketChange >= 0 ? 'var(--lime)' : 'var(--coral)' }}>
              {marketChangeLabel}
            </div>
          </div>
          <div style={{ textAlign: 'right', minWidth: 0 }}>
            <div className="label" style={{ fontSize: 8 }}>VOL / MCAP</div>
            <div className="mono" style={{ marginTop: 5, fontSize: 11, fontWeight: 700, color: 'rgba(235,235,245,0.78)' }}>
              {marketVolumeLabel} / {marketCapLabel}
            </div>
          </div>
        </div>
      </div>

      <div style={{ padding: '6px 16px 0' }}>
        <button onClick={() => onPick(champ)} className="press" style={{
          width: '100%', textAlign: 'left',
          padding: 18, borderRadius: 22,
          background: `
            radial-gradient(120% 90% at 0% 0%, ${champ.color}3a, transparent 50%),
            radial-gradient(120% 90% at 100% 100%, rgba(245,208,32,0.22), transparent 60%),
            linear-gradient(180deg, rgba(41,31,82,0.78), rgba(20,16,40,0.85))
          `,
          backdropFilter: 'blur(30px) saturate(180%)',
          WebkitBackdropFilter: 'blur(30px) saturate(180%)',
          border: '0.5px solid rgba(245,208,32,0.30)',
          boxShadow:
            'inset 0 1.5px 0 rgba(255,255,255,0.14), ' +
            'inset 0 -1px 0 rgba(0,0,0,0.4), ' +
            '0 1px 2px rgba(0,0,0,0.5), ' +
            '0 14px 36px -8px rgba(0,0,0,0.7), ' +
            '0 0 48px -14px ' + champ.color + ', ' +
            '0 0 64px -20px rgba(245,208,32,0.55)',
          position: 'relative', overflow: 'hidden',
          color: 'inherit',
        }}>
          {/* gold leaf */}
          <div aria-hidden style={{
            position: 'absolute', top: -20, right: -20,
            width: 140, height: 140, borderRadius: '50%',
            background: 'radial-gradient(circle, rgba(245,208,32,0.18), transparent 60%)',
            filter: 'blur(8px)',
          }} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{
              fontSize: 10, fontWeight: 700, color: 'var(--gold)',
              letterSpacing: 0.16 + 'em', textTransform: 'uppercase',
            }}>★ Golden Boot · Today</span>
            <div style={{ flex: 1 }} />
            <span style={{ fontSize: 11, fontWeight: 600, color: 'rgba(245,208,32,0.7)' }}>14h 22m left</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 10 }}>
            <div style={{ position: 'relative' }}>
              <FlagRect code={champ.code} w={56} h={38} style={{ borderRadius: 8, boxShadow: '0 4px 14px rgba(0,0,0,0.5)' }} />
              <div style={{
                position: 'absolute', top: -6, left: -6,
                width: 22, height: 22, borderRadius: '50%',
                background: 'linear-gradient(180deg, #FFE85B, #A88900)',
                display: 'grid', placeItems: 'center',
                fontSize: 11, fontWeight: 800, color: '#6B5500',
                fontFamily: 'Bricolage Grotesque', letterSpacing: 0,
                boxShadow: '0 2px 8px rgba(0,0,0,0.5)',
              }}>1</div>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="bgd" style={{ fontSize: 26, lineHeight: 1, color: '#fff' }}>{champ.name}</div>
              <div className="mono" style={{ fontSize: 12, color: 'rgba(235,235,245,0.55)', marginTop: 4 }}>
                {champ.code}·USD · Group {champ.group}
              </div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div className="bgd tnum" style={{ fontSize: 22, color: '#F5D020' }}>{mFmtCountryVolume(champ)}</div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--lime)', fontWeight: 700 }}>
                +{champ.change24h.toFixed(1)}%
              </div>
            </div>
          </div>
          {/* progress */}
          <div style={{ marginTop: 14 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
              <span style={{ fontSize: 10, fontWeight: 700, color: 'rgba(235,235,245,0.6)', letterSpacing: 0.12 + 'em', textTransform: 'uppercase' }}>Boot fill</span>
              <span className="mono" style={{ fontSize: 10, color: 'rgba(245,208,32,0.8)', fontWeight: 700 }}>{fillPct.toFixed(0)}%</span>
            </div>
            <div style={{
              height: 8, borderRadius: 4, background: 'rgba(255,255,255,0.06)',
              overflow: 'hidden', position: 'relative',
              boxShadow: 'inset 0 1px 2px rgba(0,0,0,0.5)',
            }}>
              <div style={{
                position: 'absolute', inset: 0, width: fillPct + '%',
                background: 'linear-gradient(90deg, #FFE85B, #F5D020, #A88900)',
                boxShadow: '0 0 10px rgba(245,208,32,0.7), inset 0 1px 0 rgba(255,255,255,0.4)',
              }} />
            </div>
          </div>
        </button>
      </div>

      {/* TOP MOVERS — Stories-style horizontal scroller */}
      <div className="m-section-hdr">Top movers · 24h</div>
      <div style={{
        display: 'flex', gap: 12, padding: '0 16px 4px',
        overflowX: 'auto', scrollbarWidth: 'none',
      }}>
        {movers.map(c => (
          <button key={c.code} onClick={() => onPick(c)} className="press" style={{
            background: 'transparent', border: 0, color: 'inherit',
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6,
            flexShrink: 0, cursor: 'pointer', padding: 0, width: 64,
          }}>
            <div style={{
              width: 60, height: 60, borderRadius: '50%',
              padding: 2,
              background: `conic-gradient(${c.color} 0%, ${c.color} ${50 + c.change24h * 1.2}%, rgba(255,255,255,0.08) ${50 + c.change24h * 1.2}%)`,
              display: 'grid', placeItems: 'center',
              boxShadow: `0 0 14px -4px ${c.color}`,
            }}>
              <div style={{
                width: 56, height: 56, borderRadius: '50%',
                background: 'linear-gradient(180deg, #1a1230, #0a0615)',
                display: 'grid', placeItems: 'center',
                boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.08), inset 0 -1px 0 rgba(0,0,0,0.4)',
              }}>
                <FlagRect code={c.code} w={40} h={28} style={{ borderRadius: 5 }} />
              </div>
            </div>
            <div className="mono" style={{ fontSize: 10, fontWeight: 700, color: c.change24h >= 0 ? 'var(--lime)' : 'var(--coral)' }}>
              {c.change24h >= 0 ? '+' : ''}{c.change24h.toFixed(1)}%
            </div>
            <div style={{ fontSize: 11, fontWeight: 500, color: 'rgba(235,235,245,0.7)' }}>{c.code}</div>
          </button>
        ))}
      </div>

      {/* PORTFOLIO MINI */}
      {portfolio.holdings.length > 0 && (
        <>
          <div className="m-section-hdr" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <span>Your portfolio</span>
            <span style={{ fontSize: 12, color: 'var(--gold)', fontWeight: 500, textTransform: 'none', letterSpacing: 0 }}>See all</span>
          </div>
          <div style={{ padding: '0 16px' }}>
            <div className="m-card">
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
                <span className="bgd tnum" style={{ fontSize: 32, lineHeight: 1 }}>
                  ${portfolio.totalValue.toFixed(2)}
                </span>
                <span className="mono tnum" style={{ fontSize: 13, color: portfolio.pnlPct >= 0 ? 'var(--lime)' : 'var(--coral)', fontWeight: 700 }}>
                  {portfolio.pnlPct >= 0 ? '+' : ''}${portfolio.pnl.toFixed(2)} · {portfolio.pnlPct >= 0 ? '+' : ''}{portfolio.pnlPct.toFixed(1)}%
                </span>
              </div>
              <div style={{ fontSize: 11, color: 'rgba(235,235,245,0.45)', marginTop: 3 }}>Today · synced from desktop</div>
              <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
                {portfolio.holdings.slice(0, 4).map(h => {
                  const c = countries.find(x => x.code === h.code);
                  if (!c) return null;
                  return (
                    <button key={h.code} className="press" onClick={() => onPick(c)} style={{
                      flex: 1, padding: 10, borderRadius: 12,
                      background: 'rgba(255,255,255,0.04)',
                      border: '0.5px solid rgba(255,255,255,0.06)',
                      display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 6,
                      cursor: 'pointer', color: 'inherit',
                    }}>
                      <FlagRect code={h.code} w={22} h={15} style={{ borderRadius: 3 }} />
                      <div className="mono tnum" style={{ fontSize: 11, fontWeight: 700, color: '#fff' }}>${(h.value).toFixed(0)}</div>
                      <div className="mono" style={{ fontSize: 9, color: c.change24h >= 0 ? 'var(--lime)' : 'var(--coral)' }}>
                        {c.change24h >= 0 ? '+' : ''}{c.change24h.toFixed(1)}%
                      </div>
                    </button>
                  );
                })}
              </div>
            </div>
          </div>
        </>
      )}

      {/* LIVE FEED */}
      <div className="m-section-hdr" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
        <span className="live-dot" />
        <span>Sepolia feed</span>
      </div>
      <div className="m-list" style={{ marginBottom: 100 }}>
        {(ticker.length ? ticker : [{ id: 'pending', code: null, name: 'WCI26', color: 'var(--fifa-teal)', amount: 0, amountLabel: 'Sync pending', ts: Date.now() }]).slice(0, 12).map((t, i) => {
          const c = countries.find(x => x.code === t.code);
          return (
            <button key={t.id} className="m-list-row press" style={{ background: 'transparent', border: 0, color: 'inherit', width: '100%', textAlign: 'left', cursor: 'pointer' }}
              onClick={() => c && onPick(c)}>
              {t.code ? <FlagRect code={t.code} w={28} h={19} style={{ marginRight: 12, borderRadius: 3 }} /> : <span className="live-dot" style={{ marginRight: 20 }} />}
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 15, fontWeight: 500, color: '#fff', letterSpacing: -0.3 }}>
                  {t.name}
                </div>
                <div style={{ fontSize: 12, color: 'rgba(235,235,245,0.55)', marginTop: 1, letterSpacing: -0.1 }}>
                  {t.eventType || 'Sync'} · {fmtTimeAgo(t.ts)} ago
                </div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div className="mono tnum" style={{ fontSize: 14, fontWeight: 600, color: '#fff', maxWidth: 116, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {t.amountLabel || `${Number(t.amount || 0).toFixed(4)} WETH`}
                </div>
                <div className="mono" style={{ fontSize: 10, color: t.color, fontWeight: 700 }}>
                  {t.code || 'SYNC'}
                </div>
              </div>
            </button>
          );
        })}
      </div>
    </>
  );
};

// ═════════════════════════════════════════════════════════════
// GLOBE — 2D dotted world with country pins (mobile-perf-friendly)
// ═════════════════════════════════════════════════════════════
const GlobeScreen = ({ countries, onPick }) => {
  const [selectedCode, setSelectedCode] = React.useState('BRA');
  const selected = countries.find(c => c.code === selectedCode)
    || countries.find(c => c.code === 'BRA')
    || countries[0];
  const selectedTicker = typeof wciCountryDollarTicker === 'function'
    ? wciCountryDollarTicker(selected)
    : (selected?.tokenSymbol || `$${selected?.code || ''}26`);
  React.useEffect(() => {
    if (countries.length && !countries.some(c => c.code === selectedCode)) {
      setSelectedCode(countries.find(c => c.code === 'BRA')?.code || countries[0].code);
    }
  }, [countries, selectedCode]);
  // Convert lat/lng to a flat equirectangular projection within the viewport
  const W = 386, H = 280;
  const project = (lat, lng) => [
    ((lng + 180) / 360) * W,
    ((90 - lat) / 180) * H,
  ];
  // Generate a dotted base "earth" — fixed seed deterministic dots
  const dots = React.useMemo(() => {
    const arr = [];
    let s = 12345;
    const next = () => { s = (s * 9301 + 49297) % 233280; return s / 233280; };
    // Dense band around equator, sparse poles. We'll fake continent silhouettes
    // by sampling from country lat/lng with jitter
    const sources = Object.values(COUNTRY_GEO);
    for (let i = 0; i < 700; i++) {
      const src = sources[Math.floor(next() * sources.length)];
      const lat = src[0] + (next() - 0.5) * 30;
      const lng = src[1] + (next() - 0.5) * 40;
      const [x, y] = project(lat, lng);
      arr.push([x, y]);
    }
    return arr;
  }, []);

  const topRanked = React.useMemo(() => countries.slice(0, 3), [countries]);
  const realtimeLeaders = React.useMemo(() => [...countries]
    .sort((a, b) => (
      mCountryPressureValue(b) - mCountryPressureValue(a)
      || mCountryVolumeValue(b) - mCountryVolumeValue(a)
      || mCountryMcapValue(b) - mCountryMcapValue(a)
      || String(a.code).localeCompare(String(b.code))
    ))
    .slice(0, 5), [countries]);
  const maxLeaderVolume = Math.max(1, ...realtimeLeaders.map(mCountryVolumeValue));
  const maxLeaderPressure = Math.max(1, ...realtimeLeaders.map(mCountryPressureValue));
  const maxLeaderMcap = Math.max(1, ...realtimeLeaders.map(mCountryMcapValue));
  const selectedLanes = [
    {
      label: 'Market cap',
      value: mFmtCountryMcap(selected),
      pct: mRacePct(mCountryMcapValue(selected), maxLeaderMcap),
      tone: 'cyan',
    },
    {
      label: 'Total country volume',
      value: mFmtCountryVolume(selected),
      pct: mRacePct(mCountryVolumeValue(selected), maxLeaderVolume),
      tone: 'gold',
    },
    {
      label: 'Total buy pressure',
      value: mFmtBuyPressure(selected),
      pct: mRacePct(mCountryPressureValue(selected), maxLeaderPressure),
      tone: 'lime',
    },
  ];
  const handleCountryCode = React.useCallback((code) => {
    const country = countries.find(c => c.code === code);
    if (country) setSelectedCode(country.code);
  }, [countries]);

  return (
    <>
      <NavBar
        title="Globe"
        eyebrow={<>48 NATIONS · LIVE</>}
        leading={<SyncPill online={true} />}
        trailing={<MobileSocialLinks />}
      />

      <div style={{ padding: '4px 16px' }}>
        {/* Desktop globe engine, fitted to the PWA viewport */}
        <div className="m-desktop-globe-frame">
          <div className="m-globe-hud m-globe-hud-left">
            <div>3D GLOBE · 48 / 48 LIVE</div>
          </div>
          <div className="m-globe-hud m-globe-hud-right">
            <div>SYS · {new Date().toISOString().slice(11, 19)}</div>
          </div>
          <div className="m-desktop-globe-stage">
            <Globe
              countries={countries}
              topRanked={topRanked}
              unfolded={false}
              setUnfolded={() => {}}
              onCountryHover={() => {}}
              onCountryClick={handleCountryCode}
              rotationSpeed={0.035}
              scale={0.72}
              focusCodes={[]}
              selectedCountryCode={selected.code}
            />
          </div>
        </div>

        {/* Legacy projection fallback, hidden after desktop globe integration */}
        <div style={{
          display: 'none',
          position: 'relative',
          borderRadius: 22,
          overflow: 'hidden',
          background: `
            radial-gradient(140% 90% at 50% 20%, rgba(78,209,230,0.16), transparent 55%),
            radial-gradient(80% 60% at 100% 100%, rgba(139,71,214,0.18), transparent 60%),
            linear-gradient(180deg, rgba(20,16,40,0.92), rgba(10,6,21,0.96))
          `,
          backdropFilter: 'blur(28px) saturate(180%)',
          WebkitBackdropFilter: 'blur(28px) saturate(180%)',
          border: '0.5px solid rgba(78,209,230,0.28)',
          height: H + 40,
          boxShadow:
            'inset 0 1.5px 0 rgba(255,255,255,0.08), ' +
            'inset 0 -1px 0 rgba(0,0,0,0.4), ' +
            '0 14px 36px -10px rgba(0,0,0,0.7), ' +
            '0 0 40px -14px rgba(78,209,230,0.35)',
        }}>
          {/* HUD coords */}
          <div style={{
            position: 'absolute', top: 10, left: 12, zIndex: 3,
            fontFamily: 'JetBrains Mono', fontSize: 8, color: 'rgba(78,209,230,0.6)',
            letterSpacing: 0.1 + 'em', pointerEvents: 'none',
          }}>
            <div>EQUIRECTANGULAR · 48 / 48 LIVE</div>
          </div>
          <div style={{
            position: 'absolute', top: 10, right: 12, zIndex: 3,
            fontFamily: 'JetBrains Mono', fontSize: 8, color: 'rgba(78,209,230,0.6)',
            letterSpacing: 0.1 + 'em', pointerEvents: 'none', textAlign: 'right',
          }}>
            <div>SYS · {new Date().toISOString().slice(11, 19)}</div>
          </div>

          <svg width="100%" height={H + 20} viewBox={`0 0 ${W} ${H + 20}`} style={{ display: 'block', marginTop: 20 }}>
            {/* base dots */}
            {dots.map(([x, y], i) => (
              <circle key={i} cx={x} cy={y} r="0.7" fill="rgba(78,209,230,0.32)" />
            ))}
            {/* equator + meridian lines */}
            <line x1="0" y1={H/2} x2={W} y2={H/2} stroke="rgba(78,209,230,0.12)" strokeDasharray="2 4" />
            <line x1={W/2} y1="0" x2={W/2} y2={H} stroke="rgba(78,209,230,0.12)" strokeDasharray="2 4" />

            {/* country pins — size = rank inverse */}
            {countries.map(c => {
              const [x, y] = project(c.lat, c.lng);
              const r = Math.max(3, 10 - c.rank * 0.18);
              const isSel = c.code === selected.code;
              return (
                <g key={c.code} style={{ cursor: 'pointer' }} onClick={() => setSelectedCode(c.code)}>
                  {isSel && (
                    <circle cx={x} cy={y} r={r + 8} fill={c.color} opacity="0.2">
                      <animate attributeName="r" values={`${r};${r+10};${r}`} dur="2s" repeatCount="indefinite" />
                      <animate attributeName="opacity" values="0.4;0;0.4" dur="2s" repeatCount="indefinite" />
                    </circle>
                  )}
                  <circle cx={x} cy={y} r={r} fill={c.color} stroke={isSel ? '#fff' : 'rgba(255,255,255,0.5)'} strokeWidth={isSel ? 2 : 0.8}
                          style={{ filter: `drop-shadow(0 0 ${r/2}px ${c.color})` }} />
                  {c.rank <= 3 && (
                    <text x={x} y={y + r + 11} textAnchor="middle" fontSize="8" fontWeight="800"
                      fill={c.color} fontFamily="Bricolage Grotesque" style={{ filter: 'drop-shadow(0 1px 2px rgba(0,0,0,0.8))' }}>
                      {c.code}
                    </text>
                  )}
                </g>
              );
            })}
          </svg>
        </div>

        {/* Selected country detail card */}
        <button onClick={() => onPick(selected)} className="m-selected-country-card press" data-code={selected.code} style={{
          width: '100%', textAlign: 'left',
          marginTop: 12, padding: 14, borderRadius: 16,
          background: `
            linear-gradient(135deg, ${selected.color}30, transparent 55%),
            linear-gradient(180deg, rgba(41,31,82,0.7), rgba(20,16,40,0.85))
          `,
          backdropFilter: 'blur(26px) saturate(180%)',
          WebkitBackdropFilter: 'blur(26px) saturate(180%)',
          border: '0.5px solid ' + selected.color + '88',
          boxShadow:
            'inset 0 1.5px 0 rgba(255,255,255,0.10), ' +
            'inset 0 -1px 0 rgba(0,0,0,0.4), ' +
            `0 12px 32px -10px ${selected.color}, ` +
            '0 8px 24px -10px rgba(0,0,0,0.6)',
          color: 'inherit',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <FlagRect code={selected.code} w={46} h={31} style={{ borderRadius: 5 }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="sfd" style={{ fontSize: 19, fontWeight: 700 }}>{selected.name}</div>
              <div className="mono" style={{ fontSize: 11, color: 'rgba(235,235,245,0.55)' }}>
                {selectedTicker} · #{selected.rank} · GROUP {selected.group} · {fmtNum(selected.holders)} holders
              </div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div className="mono tnum" style={{ fontSize: 15, fontWeight: 700, color: '#fff' }}>{mFmtCountryPrice(selected)}</div>
              <div className="mono" style={{ fontSize: 11, color: selected.change24h >= 0 ? 'var(--lime)' : 'var(--coral)', fontWeight: 700 }}>
                {selected.change24h >= 0 ? '+' : ''}{selected.change24h.toFixed(2)}%
              </div>
            </div>
          </div>
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            marginTop: 12, padding: '10px 12px', borderRadius: 10,
            background: 'rgba(255,255,255,0.04)',
          }}>
            <div>
              <div style={{ fontSize: 9, fontWeight: 700, color: 'rgba(235,235,245,0.5)', letterSpacing: 0.1 + 'em', textTransform: 'uppercase' }}>24h Vol</div>
              <div className="mono tnum" style={{ fontSize: 13, fontWeight: 700, color: '#fff' }}>{mFmtCountryVolume(selected)}</div>
            </div>
            <MobileSparkline data={makeSpark(selected.code, selected.change24h)} color={selected.color} w={80} h={28} />
            <div style={{
              padding: '10px 14px', borderRadius: 999,
              background: 'linear-gradient(180deg, #FFE85B, #F5D020 60%, #A88900)',
              fontSize: 13, fontWeight: 700, color: '#1a1300',
              boxShadow: '0 4px 14px -4px var(--gold), inset 0 1px 0 rgba(255,255,255,0.5)',
              letterSpacing: -0.1,
            }}>
              Buy
            </div>
          </div>
        </button>

        <div className="m-section-hdr">Realtime Leaders</div>
        <section className="m-realtime-panel">
          <div className="m-realtime-chip-row">
            {realtimeLeaders.map((leader, index) => (
              <button
                type="button"
                key={leader.code}
                data-code={leader.code}
                className={`m-realtime-chip press ${leader.code === selected.code ? 'is-active' : ''}`}
                onClick={() => setSelectedCode(leader.code)}
              >
                <span className="m-rank-badge">#{index + 1}</span>
                <FlagRect code={leader.code} w={28} h={19} style={{ borderRadius: 4 }} />
                <strong>{leader.code}</strong>
                <em>{mFmtBuyPressure(leader)}</em>
              </button>
            ))}
          </div>
          <div className="m-live-lanes">
            {selectedLanes.map((lane) => (
              <div className={`m-live-lane ${lane.tone}`} key={lane.label} style={{ '--lane-pct': lane.pct }}>
                <div>
                  <span>{lane.label}</span>
                  <strong className="mono">{lane.value}</strong>
                </div>
                <b><i /></b>
              </div>
            ))}
          </div>
        </section>
      </div>
    </>
  );
};

// ═════════════════════════════════════════════════════════════
// BATTLE — full leaderboard with segmented control + sparklines
// ═════════════════════════════════════════════════════════════
const BattleScreen = ({ countries, onPick, watchlist, toggleWatch }) => {
  const [sortBy, setSortBy] = React.useState('vol');
  const [rivalCode, setRivalCode] = React.useState(null);
  const sorted = React.useMemo(() => {
    const copy = [...countries];
    if (sortBy === 'vol') copy.sort((a,b) => b.volume24h - a.volume24h);
    if (sortBy === 'pct') copy.sort((a,b) => b.change24h - a.change24h);
    if (sortBy === 'holders') copy.sort((a,b) => b.holders - a.holders);
    return copy;
  }, [countries, sortBy]);
  const podium = sorted.slice(0, 3);
  const leader = sorted[0];
  const rival = sorted.find((country) => country.code === rivalCode && country.code !== leader?.code)
    || sorted.find((country) => country.code !== leader?.code)
    || sorted[1]
    || leader;
  const duelMax = {
    mcap: Math.max(1, mCountryMcapValue(leader), mCountryMcapValue(rival)),
    volume: Math.max(1, mCountryVolumeValue(leader), mCountryVolumeValue(rival)),
    pressure: Math.max(1, mCountryPressureValue(leader), mCountryPressureValue(rival)),
  };
  const duelLanes = [
    {
      label: 'Market cap',
      leader: mFmtCountryMcap(leader),
      rival: mFmtCountryMcap(rival),
      leaderPct: mRacePct(mCountryMcapValue(leader), duelMax.mcap, 10, 68),
      rivalPct: mRacePct(mCountryMcapValue(rival), duelMax.mcap, 10, 68),
    },
    {
      label: 'Total country volume',
      leader: mFmtCountryVolume(leader),
      rival: mFmtCountryVolume(rival),
      leaderPct: mRacePct(mCountryVolumeValue(leader), duelMax.volume, 10, 68),
      rivalPct: mRacePct(mCountryVolumeValue(rival), duelMax.volume, 10, 68),
    },
    {
      label: 'Total buy pressure',
      leader: mFmtBuyPressure(leader),
      rival: mFmtBuyPressure(rival),
      leaderPct: mRacePct(mCountryPressureValue(leader), duelMax.pressure, 10, 68),
      rivalPct: mRacePct(mCountryPressureValue(rival), duelMax.pressure, 10, 68),
    },
  ];

  return (
    <>
      <NavBar
        title="Battle"
        eyebrow={<>48 NATIONS · BUY PRESSURE</>}
        leading={<SyncPill online={true} />}
        trailing={<MobileSocialLinks />}
      />

      {/* Podium */}
      <div style={{ padding: '4px 16px 12px' }}>
        <div style={{
          padding: 16, borderRadius: 22,
          background: `
            radial-gradient(80% 80% at 50% 0%, rgba(245,208,32,0.20), transparent 60%),
            linear-gradient(180deg, rgba(41,31,82,0.72), rgba(20,16,40,0.86))
          `,
          backdropFilter: 'blur(28px) saturate(180%)',
          WebkitBackdropFilter: 'blur(28px) saturate(180%)',
          border: '0.5px solid rgba(245,208,32,0.30)',
          boxShadow:
            'inset 0 1.5px 0 rgba(255,255,255,0.12), ' +
            'inset 0 -1px 0 rgba(0,0,0,0.4), ' +
            '0 14px 36px -10px rgba(0,0,0,0.7), ' +
            '0 0 36px -14px rgba(245,208,32,0.5)',
          display: 'flex', alignItems: 'flex-end', justifyContent: 'space-around', gap: 8,
        }}>
          {[1, 0, 2].map((rIdx, i) => {
            const c = podium[rIdx];
            if (!c) return null;
            const h = rIdx === 0 ? 96 : rIdx === 1 ? 72 : 58;
            const mc = rIdx === 0 ? '#F5D020' : rIdx === 1 ? '#C0C5CE' : '#CD7F32';
            return (
              <button key={c.code} className="press" onClick={() => onPick(c)} style={{
                background: 'transparent', border: 0, color: 'inherit', cursor: 'pointer',
                flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
              }}>
                <FlagRect code={c.code} w={36} h={24} style={{ borderRadius: 4 }} />
                <div className="sfd" style={{ fontSize: 13, fontWeight: 700, marginTop: 4 }}>{c.code}</div>
                <div className="mono tnum" style={{ fontSize: 10, color: mc, fontWeight: 700 }}>{mFmtCountryVolume(c)}</div>
                <div style={{
                  width: '90%', height: h, marginTop: 4,
                  borderRadius: '10px 10px 0 0',
                  background: `linear-gradient(180deg, ${mc} 0%, ${mc}aa 50%, ${mc}33 100%)`,
                  display: 'grid', placeItems: 'center', position: 'relative',
                  boxShadow:
                    'inset 0 2px 0 rgba(255,255,255,0.45), ' +
                    'inset 0 -2px 0 rgba(0,0,0,0.25), ' +
                    `0 4px 14px -2px ${mc}88, ` +
                    '0 1px 2px rgba(0,0,0,0.4)',
                }}>
                  <span className="bgd" style={{ fontSize: 28, color: 'rgba(0,0,0,0.5)' }}>{rIdx + 1}</span>
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {leader && rival && (
        <section className="m-battle-duel">
          <div className="m-duel-head">
            <span>Duel Mode</span>
            <strong>{leader.code} vs {rival.code}</strong>
          </div>
          <div className="m-duel-card-row">
            {[leader, rival].map((country, index) => (
              <button
                type="button"
                key={country.code}
                className={`m-duel-card press ${index === 0 ? 'is-leader' : 'is-rival'}`}
                onClick={() => onPick(country)}
              >
                <FlagRect code={country.code} w={32} h={22} style={{ borderRadius: 4 }} />
                <span>
                  <b>{index === 0 ? 'Leader' : 'Rival'}</b>
                  <strong>{country.name}</strong>
                </span>
                <em>{country.change24h >= 0 ? '+' : ''}{Number(country.change24h || 0).toFixed(1)}%</em>
              </button>
            ))}
          </div>
          <div className="m-duel-lanes">
            {duelLanes.map((lane) => (
              <div
                className="m-duel-lane"
                key={lane.label}
                style={{ '--leader-pct': lane.leaderPct, '--rival-pct': lane.rivalPct }}
              >
                <div className="m-duel-lane-top">
                  <span>{lane.label}</span>
                  <strong className="mono">{lane.leader} / {lane.rival}</strong>
                </div>
                <div className="m-duel-meter leader"><i /></div>
                <div className="m-duel-meter rival"><i /></div>
              </div>
            ))}
          </div>
        </section>
      )}

      {/* Segmented control */}
      <div style={{ padding: '4px 16px' }}>
        <div style={{
          display: 'flex', padding: 3, gap: 0,
          background: 'linear-gradient(180deg, rgba(20,16,40,0.6), rgba(41,31,82,0.55))',
          backdropFilter: 'blur(22px) saturate(180%)',
          WebkitBackdropFilter: 'blur(22px) saturate(180%)',
          border: '0.5px solid rgba(255,255,255,0.10)',
          borderRadius: 12,
          boxShadow:
            'inset 0 1px 0 rgba(255,255,255,0.06), ' +
            'inset 0 -1px 0 rgba(0,0,0,0.4), ' +
            '0 6px 18px -8px rgba(0,0,0,0.5)',
        }}>
          {[
            { k: 'vol', label: 'Volume' },
            { k: 'pct', label: '24h %' },
            { k: 'holders', label: 'Holders' },
          ].map(s => (
            <button key={s.k} onClick={() => setSortBy(s.k)} style={{
              flex: 1, padding: '7px 10px', borderRadius: 9,
              background: sortBy === s.k
                ? 'linear-gradient(180deg, rgba(245,208,32,0.35), rgba(245,208,32,0.12))'
                : 'transparent',
              border: '0.5px solid ' + (sortBy === s.k ? 'rgba(245,208,32,0.45)' : 'transparent'),
              color: sortBy === s.k ? '#fff' : 'rgba(235,235,245,0.7)',
              fontSize: 13, fontWeight: 600, cursor: 'pointer',
              fontFamily: 'inherit', letterSpacing: -0.2,
              boxShadow: sortBy === s.k
                ? 'inset 0 1px 0 rgba(255,255,255,0.25), inset 0 -1px 0 rgba(0,0,0,0.15), 0 2px 6px rgba(245,208,32,0.35)'
                : 'none',
            }}>
              {s.label}
            </button>
          ))}
        </div>
      </div>

      {/* List */}
      <div className="m-list" style={{ marginTop: 16, marginBottom: 100 }}>
        {sorted.map((c, i) => {
          const watched = watchlist.includes(c.code);
          const isLast = i === sorted.length - 1;
          return (
            <div key={c.code} className={`m-list-row ${rival?.code === c.code ? 'm-rival-selected' : ''}`} style={{ padding: '10px 14px' }}>
              <span className="bgd tnum" style={{
                width: 30, textAlign: 'center', fontSize: 16,
                color: i === 0 ? 'var(--gold)' : i < 3 ? 'var(--fifa-yellow)' : 'rgba(235,235,245,0.45)',
              }}>{i + 1}</span>
              <FlagRect code={c.code} w={30} h={20} style={{ marginRight: 12, marginLeft: 4, borderRadius: 3 }} />
              <button className="press" onClick={() => setRivalCode(c.code)} style={{
                flex: 1, background: 'transparent', border: 0, color: 'inherit', textAlign: 'left',
                display: 'flex', flexDirection: 'column', minWidth: 0, cursor: 'pointer',
              }}>
                <span style={{ fontSize: 15, fontWeight: 500, letterSpacing: -0.3 }}>{c.name}</span>
                <span className="mono" style={{ fontSize: 11, color: 'rgba(235,235,245,0.5)' }}>
                  {mFmtCountryVolume(c)} · {fmtNum(c.holders)}
                </span>
              </button>
              <MobileSparkline data={makeSpark(c.code, c.change24h)} color={c.change24h >= 0 ? '#34C759' : '#E8392C'} w={48} h={22} fill={false} />
              <div style={{ marginLeft: 10, textAlign: 'right', minWidth: 64 }}>
                <div className="mono tnum" style={{ fontSize: 13, fontWeight: 600 }}>{mFmtCountryPrice(c)}</div>
                <div className="mono" style={{ fontSize: 11, color: c.change24h >= 0 ? 'var(--lime)' : 'var(--coral)', fontWeight: 700 }}>
                  {c.change24h >= 0 ? '+' : ''}{c.change24h.toFixed(1)}%
                </div>
              </div>
              <button onClick={() => toggleWatch(c.code)} className="press" style={{
                marginLeft: 8, background: 'transparent', border: 0, cursor: 'pointer', padding: 6,
              }}>
                {Icon.star(watched, watched ? '#F5D020' : 'rgba(235,235,245,0.4)')}
              </button>
            </div>
          );
        })}
      </div>
    </>
  );
};

// ═════════════════════════════════════════════════════════════
// WALLET — portfolio with tier, streak, holdings
// ═════════════════════════════════════════════════════════════
const TeamScreen = ({
  countries,
  watchlist = [],
  toggleWatch,
  onPick,
  walletAddress = '',
  walletNickname = '',
  walletNicknameDraft = '',
  walletError = '',
  walletProfile = null,
  walletRows = [],
  onWalletConnect,
  onWalletNicknameChange,
}) => {
  const [mobileProfileOpen, setMobileProfileOpen] = React.useState(true);
  React.useEffect(() => {
    setMobileProfileOpen(true);
  }, [walletAddress]);
  const watchedCountries = watchlist
    .map((code) => countries.find((country) => country.code === code))
    .filter(Boolean);
  const sortedCandidates = [...countries].sort((a, b) => (
    (b.volume24h - a.volume24h)
    || (b.marketCapWETH || b.mcap || 0) - (a.marketCapWETH || a.mcap || 0)
    || String(a.code).localeCompare(String(b.code))
  ));
  const focus = watchedCountries[0] || sortedCandidates[0];
  const totalVolume = watchedCountries.reduce((sum, country) => sum + Number(country.volume24h || 0), 0);
  const totalPressure = watchedCountries.reduce((sum, country) => sum + Number(country.recentBuyVolumeWETH || country.pendingWETH || 0), 0);
  const maxVolume = Math.max(1, ...sortedCandidates.map((country) => Number(country.volume24h || 0)));
  const maxMcap = Math.max(1, ...sortedCandidates.map((country) => Number(country.marketCapWETH || country.mcap || 0)));
  const maxPressure = Math.max(1, ...sortedCandidates.map((country) => Number(country.recentBuyVolumeWETH || country.pendingWETH || 0)));
  const barPct = (value, max) => `${Math.max(5, Math.min(52, (Number(value || 0) / Math.max(1, max * 2.2)) * 100))}%`;
  const buyPressureLabel = (country) => {
    const pressureWETH = Number(country?.recentBuyVolumeWETH || country?.pendingWETH || 0);
    return typeof wciFormatWethUsd === 'function' ? wciFormatWethUsd(pressureWETH) : '$0';
  };
  const connectedWallet = Boolean(walletAddress);
  const supporterProfile = walletProfile || {
    totalBuys: 0,
    countriesBacked: 0,
    totalSupportUsd: 0,
    score: 0,
    tier: 'Ready supporter',
    badges: ['Ready to back'],
    topEntry: null,
    nextMission: 'Connect read-only, then back countries to build your supporter profile.',
  };
  const displayNickname = String(walletNickname || '').trim();
  const nicknameValue = connectedWallet ? displayNickname : (walletNicknameDraft || '');
  const topSupportCountry = supporterProfile.topEntry
    ? (supporterProfile.topEntry.country || countries.find((country) => country.code === supporterProfile.topEntry.code))
    : null;
  const recentWalletRows = Array.isArray(walletRows) ? walletRows.slice(0, 3) : [];
  const walletBuyCount = Number(supporterProfile.totalBuys || 0);
  const backedCount = Number(supporterProfile.countriesBacked || 0);

  return (
    <>
      <NavBar
        title="Teams"
        eyebrow={<>WATCHLIST COMMAND - GAME MODE</>}
        leading={<SyncPill online={true} />}
        trailing={<NavPill>{Icon.star(true, 'rgba(245,208,32,0.95)')}</NavPill>}
      />

      <div className="m-team-wrap">
        <section className="m-team-hero">
          <div className="m-team-hero-copy">
            <div className="m-team-kicker">Team monitor - {watchlist.length}</div>
            <h2>{watchlist.length} {watchlist.length === 1 ? 'team' : 'teams'} monitored</h2>
            <p>{watchlist.length ? 'Track your pinned countries like a live match squad.' : 'Pick countries below or star them from Battle to build your squad.'}</p>
          </div>
          <div className="m-team-hero-grid">
            <div>
              <span>Watchlist volume</span>
              <strong className="mono">{typeof wciFormatCompactUsd === 'function' ? wciFormatCompactUsd(totalVolume, '$0') : '$0'}</strong>
            </div>
            <div>
              <span>Buy pressure</span>
              <strong className="mono">{typeof wciFormatWethUsd === 'function' ? wciFormatWethUsd(totalPressure) : '$0'}</strong>
            </div>
          </div>
          {focus && (
            <button type="button" className="m-team-focus press" onClick={() => onPick?.(focus)}>
              <FlagRect code={focus.code} w={34} h={23} style={{ borderRadius: 4 }} />
              <span>
                <strong>{focus.name}</strong>
                <em>{watchlist.includes(focus.code) ? 'Squad captain' : 'Suggested captain'}</em>
              </span>
              <b>{mFmtCountryVolume(focus)}</b>
            </button>
          )}
        </section>

        <section className={`m-mobile-wallet-panel ${connectedWallet ? 'is-connected' : 'is-ready'}`} aria-label="Mobile read-only wallet">
          <div className="m-mobile-wallet-frame" aria-hidden="true">
            <i />
            <i />
          </div>
          <div className="m-mobile-wallet-head">
            <div>
              <div className="m-team-kicker">Read-only wallet</div>
              <h3>{connectedWallet ? (displayNickname || 'Supporter profile') : 'Supporter profile'}</h3>
              <span className="mono">{connectedWallet ? mShortWallet(walletAddress) : 'Public address only'}</span>
            </div>
            {connectedWallet ? (
              <button
                type="button"
                className="m-supporter-profile-toggle press"
                aria-label={mobileProfileOpen ? 'Collapse supporter profile' : 'Expand supporter profile'}
                aria-expanded={mobileProfileOpen ? 'true' : 'false'}
                onClick={() => setMobileProfileOpen(open => !open)}
              >
                <span />
              </button>
            ) : (
              <span className="m-mobile-wallet-lock">View-only</span>
            )}
          </div>

          <label className="m-mobile-wallet-field">
            <span>Mobile supporter nickname</span>
            <input
              type="text"
              aria-label="Mobile supporter nickname"
              value={nicknameValue}
              maxLength={32}
              placeholder="Cup Captain"
              onChange={(event) => onWalletNicknameChange?.(event.target.value)}
            />
          </label>

          {!connectedWallet && (
            <div className="m-mobile-wallet-connect">
              <div className="m-mobile-wallet-proof">
                <span>No approvals</span>
                <span>No transactions</span>
              </div>
              {walletError && <div className="m-mobile-wallet-error">{walletError}</div>}
              <button type="button" className="press" onClick={() => onWalletConnect?.()}>
                Connect read-only wallet
              </button>
            </div>
          )}

          {connectedWallet && (
            <div className="m-supporter-profile-body" hidden={!mobileProfileOpen}>
              <div className="m-mobile-supporter-grid">
                <div>
                  <span>Total support</span>
                  <strong className="mono">{mFmtSupporterUsd(supporterProfile.totalSupportUsd)}</strong>
                </div>
                <div>
                  <span>Wallet buys</span>
                  <strong className="mono">{mPlural(walletBuyCount, 'buy')}</strong>
                </div>
                <div>
                  <span>Countries backed</span>
                  <strong className="mono">{mPlural(backedCount, 'country', 'countries')}</strong>
                </div>
                <div>
                  <span>Score</span>
                  <strong className="mono">{supporterProfile.score}</strong>
                </div>
              </div>
              <div className="m-mobile-supporter-focus">
                <span>Top country</span>
                <strong>
                  {topSupportCountry && <FlagRect code={topSupportCountry.code} w={23} h={16} style={{ borderRadius: 3 }} />}
                  {topSupportCountry?.name || 'None yet'}
                </strong>
              </div>
              <div className="m-mobile-supporter-badges">
                {(supporterProfile.badges || []).map((badge) => <span key={badge}>{badge}</span>)}
              </div>
              <div className="m-mobile-supporter-next">
                <span>Next mission</span>
                <strong>{supporterProfile.nextMission}</strong>
              </div>
              {recentWalletRows.length > 0 && (
                <div className="m-mobile-wallet-buys">
                  {recentWalletRows.map((row) => (
                    <div key={row.id}>
                      {row.country && <FlagRect code={row.country.code} w={22} h={15} style={{ borderRadius: 3 }} />}
                      <span className="mono">{row.code}</span>
                      <strong>{row.country?.name || row.code}</strong>
                      <em className="mono">{row.label}</em>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
        </section>

        <div className="m-section-hdr">Team monitor - {watchlist.length}</div>
        <div className="m-team-watch-stack">
          {watchedCountries.length === 0 && (
            <div className="m-team-empty">
              <strong>Build your watchlist</strong>
              <span>Add countries to make this page your match-day command center.</span>
            </div>
          )}
          {watchedCountries.map((country) => (
            <article className="m-team-watch-card is-neon" key={country.code}>
              <div className="m-team-card-top">
                <FlagRect code={country.code} w={34} h={23} style={{ borderRadius: 4 }} />
                <button type="button" className="press" onClick={() => onPick?.(country)}>
                  <strong>{country.name}</strong>
                  <span className="mono">{country.tokenSymbol || `$${country.ticker || country.code}`}</span>
                </button>
                <div className="m-team-card-badge">LV 10</div>
                <em>{country.change24h >= 0 ? '+' : ''}{Number(country.change24h || 0).toFixed(1)}%</em>
              </div>
              <div className="m-team-metrics">
                <div><span>Market cap</span><strong className="mono">{typeof wciFormatCountryMarketCap === 'function' ? wciFormatCountryMarketCap(country) : '$--'}</strong></div>
                <div><span>Volume</span><strong className="mono">{mFmtCountryVolume(country)}</strong></div>
                <div><span>Buy pressure</span><strong className="mono">{buyPressureLabel(country)}</strong></div>
              </div>
              <div className="m-team-bars" style={{
                '--mcap-pct': barPct(Number(country.marketCapWETH || country.mcap || 0), maxMcap),
                '--vol-pct': barPct(country.volume24h, maxVolume),
                '--pressure-pct': barPct(Number(country.recentBuyVolumeWETH || country.pendingWETH || 0), maxPressure),
              }}>
                <span className="mcap" />
                <span className="vol" />
                <span className="pressure" />
              </div>
              <div className="m-team-support-rail" style={{
                '--support-pct': barPct(Number(country.recentBuyVolumeWETH || country.pendingWETH || 0), maxPressure),
              }}>
                <span>Support charge</span>
                <b><i /></b>
              </div>
              <div className="m-team-card-actions">
                <button type="button" className="press buy" onClick={() => onPick?.(country)}>Back team</button>
                <button type="button" className="press uncheck" onClick={() => toggleWatch?.(country.code)}>Uncheck</button>
              </div>
            </article>
          ))}
        </div>

        <div className="m-section-hdr">Choose teams - {countries.length}</div>
        <div className="m-team-picker-grid">
          {sortedCandidates.map((country) => {
            const watched = watchlist.includes(country.code);
            return (
              <article className={`m-team-picker-card ${watched ? 'is-picked' : ''}`} key={country.code}>
                <div className="m-team-picker-main">
                  <FlagRect code={country.code} w={30} h={20} style={{ borderRadius: 3 }} />
                  <div>
                    <strong>{country.name}</strong>
                    <span className="mono">{mFmtCountryVolume(country)} - {typeof wciFormatCountryMarketCap === 'function' ? wciFormatCountryMarketCap(country) : '$--'} mcap</span>
                  </div>
                </div>
                <button type="button" className="press" onClick={() => toggleWatch?.(country.code)}>
                  {watched ? 'Added' : 'Add'}
                </button>
              </article>
            );
          })}
        </div>
      </div>
    </>
  );
};

const WalletScreen = ({ countries, portfolio, tier, streak, buybackPool, watchlist = [], toggleWatch, onPick }) => {
  const sparkData = React.useMemo(() => {
    const v = portfolio.totalValue;
    let s = 7;
    const next = () => { s = (s * 9301 + 49297) % 233280; return s / 233280; };
    const out = [];
    let acc = v * 0.85;
    for (let i = 0; i < 30; i++) { acc += (next() - 0.4) * v * 0.04; out.push(acc); }
    out[out.length - 1] = v;
    return out;
  }, [portfolio.totalValue]);

  return (
    <>
      <NavBar
        title="Wallet"
        eyebrow={<>0x4f...8ac3 · METAMASK</>}
        leading={<SyncPill online={true} />}
        trailing={<NavPill>{Icon.share('rgba(255,255,255,0.9)')}</NavPill>}
      />

      {/* Hero balance */}
      <div style={{ padding: '4px 16px 0' }}>
        <div style={{
          padding: 20, borderRadius: 24,
          background: `
            radial-gradient(120% 100% at 0% 0%, rgba(245,208,32,0.20), transparent 55%),
            radial-gradient(80% 60% at 100% 100%, rgba(139,71,214,0.20), transparent 60%),
            linear-gradient(180deg, rgba(41,31,82,0.78), rgba(20,16,40,0.88))
          `,
          backdropFilter: 'blur(30px) saturate(180%)',
          WebkitBackdropFilter: 'blur(30px) saturate(180%)',
          border: '0.5px solid rgba(255,255,255,0.12)',
          boxShadow:
            'inset 0 1.5px 0 rgba(255,255,255,0.14), ' +
            'inset 0 -1px 0 rgba(0,0,0,0.4), ' +
            '0 14px 36px -10px rgba(0,0,0,0.7), ' +
            '0 0 40px -16px rgba(245,208,32,0.4)',
        }}>
          <div style={{ fontSize: 12, color: 'rgba(235,235,245,0.7)', letterSpacing: -0.2 }}>Total balance</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 4 }}>
            <span className="bgd tnum num-grad" style={{ fontSize: 44, lineHeight: 1 }}>
              ${portfolio.totalValue.toFixed(2)}
            </span>
          </div>
          <div className="mono" style={{ fontSize: 13, color: portfolio.pnlPct >= 0 ? 'var(--lime)' : 'var(--coral)', fontWeight: 700, marginTop: 6 }}>
            {portfolio.pnlPct >= 0 ? '+' : ''}${portfolio.pnl.toFixed(2)} · {portfolio.pnlPct >= 0 ? '+' : ''}{portfolio.pnlPct.toFixed(2)}% · 30D
          </div>
          <div style={{ marginTop: 12 }}>
            <MobileSparkline data={sparkData} color={portfolio.pnlPct >= 0 ? '#34C759' : '#E8392C'} w={340} h={56} />
          </div>
          {/* Range chips */}
          <div style={{ display: 'flex', gap: 6, marginTop: 10 }}>
            {['1H','1D','1W','1M','1Y','All'].map((r, i) => (
              <div key={r} style={{
                flex: 1, padding: '6px 0', textAlign: 'center', borderRadius: 7,
                background: i === 3 ? 'rgba(245,208,32,0.16)' : 'transparent',
                color: i === 3 ? 'var(--gold)' : 'rgba(235,235,245,0.6)',
                fontSize: 12, fontWeight: 600, letterSpacing: -0.1,
              }}>{r}</div>
            ))}
          </div>
        </div>
      </div>

      {/* Tier + Streak */}
      <div style={{ padding: '12px 16px 0', display: 'flex', gap: 12 }}>
        <div className="m-card" style={{
          flex: 1,
          background: 'linear-gradient(135deg, rgba(245,208,32,0.16), rgba(245,208,32,0.04))',
          border: '0.5px solid rgba(245,208,32,0.28)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <svg width="16" height="20" viewBox="0 0 22 26">
              <defs><linearGradient id="tier-grad-m" x1="0" y1="0" x2="0" y2="1">
                <stop offset="0%" stopColor="#FFE85B" />
                <stop offset="55%" stopColor="#F5D020" />
                <stop offset="100%" stopColor="#A88900" />
              </linearGradient></defs>
              <circle cx="11" cy="16" r="8" fill="url(#tier-grad-m)" stroke="#6B5500" strokeWidth="0.8" />
              <text x="11" y="19" textAnchor="middle" fontSize="9" fontWeight="800" fontFamily="Bricolage Grotesque" fill="#6B5500">G</text>
            </svg>
            <span style={{ fontSize: 10, fontWeight: 700, color: 'var(--gold)', letterSpacing: 0.1 + 'em', textTransform: 'uppercase' }}>Tier</span>
          </div>
          <div className="bgd" style={{ fontSize: 22, marginTop: 6, color: '#fff' }}>{tier}</div>
          <div style={{ fontSize: 11, color: 'rgba(235,235,245,0.55)', marginTop: 2 }}>Watchlist activity boost</div>
        </div>
        <div className="m-card" style={{
          flex: 1,
          background: 'linear-gradient(135deg, rgba(232,57,44,0.14), rgba(232,57,44,0.04))',
          border: '0.5px solid rgba(232,57,44,0.28)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            {Icon.flame('#FF7A1F')}
            <span style={{ fontSize: 10, fontWeight: 700, color: '#FF7A1F', letterSpacing: 0.1 + 'em', textTransform: 'uppercase' }}>Streak</span>
          </div>
          <div className="bgd tnum" style={{ fontSize: 22, marginTop: 6, color: '#fff' }}>{streak} days</div>
          <div style={{ fontSize: 11, color: 'rgba(235,235,245,0.55)', marginTop: 2 }}>Daily-buy multiplier ×1.3</div>
        </div>
      </div>

      {/* Holdings */}
      <div className="m-section-hdr">Holdings · {portfolio.holdings.length}</div>
      <div className="m-list" style={{ marginBottom: 16 }}>
        {portfolio.holdings.length === 0 && (
          <div className="m-list-row" style={{ padding: '12px 14px' }}>
            <span className="live-dot" style={{ marginRight: 14 }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 15, fontWeight: 600 }}>No indexed holdings yet</div>
              <div className="mono" style={{ fontSize: 11, color: 'rgba(235,235,245,0.55)', marginTop: 2 }}>
                Wallet balances need the onchain portfolio reader.
              </div>
            </div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--gold)', fontWeight: 800 }}>
              SEPOLIA
            </div>
          </div>
        )}
        {portfolio.holdings.map((h, i) => {
          const c = countries.find(x => x.code === h.code);
          if (!c) return null;
          return (
            <button key={h.code} className="m-list-row press" onClick={() => onPick(c)} style={{
              width: '100%', background: 'transparent', border: 0, color: 'inherit', textAlign: 'left', cursor: 'pointer',
              padding: '10px 14px',
            }}>
              <FlagRect code={c.code} w={30} h={20} style={{ marginRight: 12, borderRadius: 3 }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 15, fontWeight: 500 }}>{c.name}</div>
                <div className="mono" style={{ fontSize: 11, color: 'rgba(235,235,245,0.55)' }}>
                  {h.tokens.toLocaleString()} {c.code}
                </div>
              </div>
              <MobileSparkline data={makeSpark(c.code, c.change24h)} color={c.change24h >= 0 ? '#34C759' : '#E8392C'} w={44} h={22} fill={false} />
              <div style={{ marginLeft: 10, textAlign: 'right', minWidth: 64 }}>
                <div className="mono tnum" style={{ fontSize: 13, fontWeight: 600 }}>${h.value.toFixed(0)}</div>
                <div className="mono" style={{ fontSize: 11, color: c.change24h >= 0 ? 'var(--lime)' : 'var(--coral)', fontWeight: 700 }}>
                  {c.change24h >= 0 ? '+' : ''}{c.change24h.toFixed(1)}%
                </div>
              </div>
            </button>
          );
        })}
      </div>

      <div className="m-section-hdr">Team monitor - {watchlist.length}</div>
      <div className="m-card" style={{ margin: '0 16px 18px', padding: 0, overflow: 'hidden' }}>
        {watchlist.length === 0 && (
          <div className="m-list-row" style={{ padding: '12px 14px' }}>
            <span className="live-dot" style={{ marginRight: 14 }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 15, fontWeight: 600 }}>No teams monitored yet</div>
              <div className="mono" style={{ fontSize: 11, color: 'rgba(235,235,245,0.55)', marginTop: 2 }}>
                Pick teams from Battle to pin them here.
              </div>
            </div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--gold)', fontWeight: 800 }}>
              0/48
            </div>
          </div>
        )}
        {watchlist.map((code) => {
          const c = countries.find((team) => team.code === code);
          if (!c) return null;
          return (
            <div key={c.code} className="m-list-row m-monitor-row" style={{ padding: '10px 14px' }}>
              <FlagRect code={c.code} w={30} h={20} style={{ marginRight: 12, borderRadius: 3 }} />
              <button className="press" onClick={() => onPick(c)} style={{
                flex: 1, background: 'transparent', border: 0, color: 'inherit', textAlign: 'left',
                display: 'flex', flexDirection: 'column', minWidth: 0, cursor: 'pointer',
              }}>
                <span style={{ fontSize: 15, fontWeight: 600 }}>{c.name}</span>
                <span className="mono" style={{ fontSize: 11, color: 'rgba(235,235,245,0.55)', marginTop: 2 }}>
                  {typeof wciFormatCountryMarketCap === 'function' ? wciFormatCountryMarketCap(c) : '$--'} mcap - {typeof wciFormatCountryVolume === 'function' ? wciFormatCountryVolume(c) : '$0'} vol
                </span>
              </button>
              <button
                type="button"
                onClick={() => toggleWatch?.(c.code)}
                className="press"
                style={{
                  marginLeft: 10,
                  padding: '7px 10px',
                  borderRadius: 10,
                  border: '0.5px solid rgba(232,57,44,0.32)',
                  background: 'rgba(232,57,44,0.10)',
                  color: 'var(--coral)',
                  fontSize: 12,
                  fontWeight: 700,
                  cursor: 'pointer',
                }}
              >
                Uncheck
              </button>
            </div>
          );
        })}
      </div>

      {/* Rewards readiness card */}
      <div style={{ padding: '0 16px 100px' }}>
        <div className="m-card" style={{
          background:
            'radial-gradient(120% 100% at 100% 0%, rgba(159,214,52,0.22), transparent 55%), ' +
            'linear-gradient(180deg, rgba(41,31,82,0.7), rgba(20,16,40,0.85))',
          border: '0.5px solid rgba(159,214,52,0.32)',
          boxShadow:
            'inset 0 1.5px 0 rgba(255,255,255,0.10), ' +
            'inset 0 -1px 0 rgba(0,0,0,0.4), ' +
            '0 14px 36px -10px rgba(0,0,0,0.6), ' +
            '0 0 40px -16px rgba(159,214,52,0.55)',
        }}>
          <div style={{ fontSize: 10, fontWeight: 700, color: 'var(--lime)', letterSpacing: 0.12 + 'em', textTransform: 'uppercase' }}>
            $WCI26 rewards
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 8 }}>
            <div className="bgd tnum" style={{ fontSize: 28, color: '#fff' }}>Manual</div>
            <div style={{
              padding: '4px 10px', borderRadius: 999,
              background: 'rgba(159,214,52,0.16)',
              fontSize: 11, fontWeight: 700, color: 'var(--lime)',
            }}>
              Pending
            </div>
          </div>
          <div style={{ fontSize: 12, color: 'rgba(235,235,245,0.55)', marginTop: 4 }}>
            Manual rewards and operations are managed outside this dashboard.
          </div>
          <button className="press btn-3d lime" style={{
            marginTop: 16, width: '100%',
          }}>
            View rewards
          </button>
        </div>
      </div>
    </>
  );
};

// ═════════════════════════════════════════════════════════════
// MORE — settings, trophies, sync status, about
// ═════════════════════════════════════════════════════════════
const WCI26_PWA_HOME_URL = 'https://www.wci26.com/';

const MoreScreen = ({ countries, onPick }) => {
  return (
    <>
      <NavBar
        title="More"
        leading={<SyncPill online={true} />}
      />

      <div style={{ padding: '4px 16px 0' }}>
        <a
          href={WCI26_PWA_HOME_URL}
          target="_blank"
          rel="noopener noreferrer"
          className="m-wci26-home-link press"
          style={{
            minHeight: 54,
            borderRadius: 16,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            gap: 12,
            padding: '0 16px',
            color: '#090615',
            background: 'linear-gradient(180deg, #ffe866, var(--gold) 54%, #a87908)',
            border: '1px solid rgba(245,208,32,0.55)',
            boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.45), 0 5px 0 rgba(0,0,0,0.42), 0 18px 34px -18px var(--gold)',
            textDecoration: 'none',
            fontFamily: 'Bricolage Grotesque, sans-serif',
            fontSize: 15,
            fontWeight: 900,
          }}
        >
          <span>Go to WCI26.COM</span>
          <span className="mono" style={{ fontSize: 11, color: 'rgba(9,6,21,0.72)', fontWeight: 900 }}>WEB</span>
        </a>
      </div>

      {/* Profile card */}
      <div style={{ padding: '4px 16px 0' }}>
        <div className="m-card" style={{
          display: 'flex', alignItems: 'center', gap: 14,
        }}>
          <div style={{
            width: 56, height: 56, borderRadius: '50%',
            background: 'linear-gradient(135deg, var(--fifa-violet), var(--fifa-magenta))',
            display: 'grid', placeItems: 'center',
            fontFamily: 'Bricolage Grotesque', fontSize: 22, fontWeight: 800, color: '#fff',
            boxShadow: '0 6px 18px -4px rgba(139,71,214,0.5)',
          }}>P</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="sfd" style={{ fontSize: 19, fontWeight: 700 }}>paul_dev_99</div>
            <div style={{ fontSize: 12, color: 'rgba(235,235,245,0.55)' }}>0x4f29...8ac3 · joined Mar 2026</div>
          </div>
          {Icon.chevR()}
        </div>
      </div>

      {/* Trophies preview */}
      <div className="m-section-hdr">Trophies · 4 / 12</div>
      <div style={{ padding: '0 16px', display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
        {[
          { e: '⚽', n: 'First Buy', got: true },
          { e: '🔥', n: '7-day Streak', got: true },
          { e: '🏆', n: 'Golden Boot', got: true },
          { e: '⭐', n: 'Hat-trick', got: true },
          { e: '🌍', n: 'World Tour', got: false },
          { e: '👑', n: 'Top 100', got: false },
          { e: '🎖', n: 'Diamond', got: false },
          { e: '🏅', n: 'Champion', got: false },
        ].map((t, i) => (
          <div key={i} style={{
            aspectRatio: '1 / 1', borderRadius: 14,
            background: t.got ? 'linear-gradient(180deg, rgba(245,208,32,0.16), rgba(245,208,32,0.04))' : 'rgba(118,118,128,0.16)',
            border: t.got ? '0.5px solid rgba(245,208,32,0.3)' : '0.5px solid rgba(255,255,255,0.06)',
            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 4,
            opacity: t.got ? 1 : 0.5,
          }}>
            <span style={{ fontSize: 26, filter: t.got ? 'none' : 'grayscale(1)' }}>{t.e}</span>
            <span style={{ fontSize: 9, fontWeight: 600, color: t.got ? 'var(--gold)' : 'rgba(235,235,245,0.5)', textAlign: 'center', padding: '0 4px' }}>{t.n}</span>
          </div>
        ))}
      </div>

      {/* Desktop sync */}
      <div className="m-section-hdr">Devices</div>
      <div className="m-list">
        <div className="m-list-row" style={{ padding: '12px 16px' }}>
          <div style={{
            width: 30, height: 30, borderRadius: 8,
            background: 'linear-gradient(135deg, #34C759, #2A9F47)',
            display: 'grid', placeItems: 'center', marginRight: 12,
          }}>
            <svg width="18" height="14" viewBox="0 0 18 14"><rect x="0.5" y="0.5" width="17" height="11" rx="1.5" fill="none" stroke="#fff" strokeWidth="1.4" /><rect x="6" y="12.5" width="6" height="1.2" fill="#fff" /></svg>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 15, fontWeight: 500 }}>MacBook Pro · WCI26 Dash</div>
            <div style={{ fontSize: 12, color: '#34C759' }}>Online · synced 2s ago</div>
          </div>
          <span style={{ fontSize: 13, color: 'rgba(235,235,245,0.5)' }}>This device</span>
        </div>
        <div className="m-list-row" style={{ padding: '12px 16px' }}>
          <div style={{
            width: 30, height: 30, borderRadius: 8,
            background: 'rgba(255,255,255,0.06)',
            display: 'grid', placeItems: 'center', marginRight: 12,
          }}>
            <svg width="14" height="20" viewBox="0 0 14 20"><rect x="0.5" y="0.5" width="13" height="19" rx="2.5" fill="none" stroke="rgba(255,255,255,0.7)" strokeWidth="1.4" /><circle cx="7" cy="16.5" r="1" fill="rgba(255,255,255,0.7)" /></svg>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 15, fontWeight: 500 }}>iPhone 15 Pro</div>
            <div style={{ fontSize: 12, color: 'rgba(235,235,245,0.55)' }}>iOS · this device</div>
          </div>
          {Icon.chevR()}
        </div>
      </div>

      {/* Settings */}
      <div className="m-section-hdr">Settings</div>
      <div className="m-list" style={{ marginBottom: 24 }}>
        {[
          ['Notifications', 'Buys, alerts, drops', '#FF3B30'],
          ['Watchlist', '6 countries', '#34C759'],
          ['Network', 'Sepolia', '#5856D6'],
          ['Privacy & Security', null, '#007AFF'],
          ['Appearance', 'Dark', '#FF9500'],
        ].map(([t, d, col], i) => (
          <div key={i} className="m-list-row" style={{ padding: '10px 16px' }}>
            <div style={{
              width: 30, height: 30, borderRadius: 7, background: col,
              marginRight: 12, flexShrink: 0,
              boxShadow: '0 1px 2px rgba(0,0,0,0.3)',
            }} />
            <div style={{ flex: 1 }}>{t}</div>
            {d && <span style={{ color: 'rgba(235,235,245,0.55)', fontSize: 15, marginRight: 6 }}>{d}</span>}
            {Icon.chevR()}
          </div>
        ))}
      </div>

      {/* Footer */}
      <div style={{ padding: '0 16px 110px', textAlign: 'center' }}>
        <div style={{ fontSize: 11, color: 'rgba(235,235,245,0.4)', marginTop: 8 }}>
          WCI26.com · v2.6.0 (build 142) · MIT-LICENSE
        </div>
        <div style={{ fontSize: 10, color: 'rgba(235,235,245,0.3)', marginTop: 4 }}>
          Not investment advice. Entertainment only.
        </div>
      </div>
    </>
  );
};

Object.assign(window, { LiveScreen, GlobeScreen, BattleScreen, TeamScreen, WalletScreen, MoreScreen });
