// wci26/country-tokens.jsx — 48 country tokens with geo + market data
// Extends TEAM_NAMES, TEAM_COLORS, GROUPS from data.jsx

// Primary flag-derived color (vivid, single). Used for globe pulses, beams, card accents.
// Secondary is a complementary flag color.
const COUNTRY_GEO = {
  // [lat, lng, primary, secondary]
  MEX: [23.6345, -102.5528, '#006341', '#CE1126'],
  RSA: [-30.5595, 22.9375, '#007749', '#FFB81C'],
  KOR: [35.9078, 127.7669, '#CD2E3A', '#003478'],
  CZE: [49.8175, 15.4730, '#D7141A', '#11457E'],
  CAN: [56.1304, -106.3468, '#FF0000', '#FFFFFF'],
  BIH: [43.9159, 17.6791, '#FECB00', '#002F6C'],
  QAT: [25.3548, 51.1839, '#8A1538', '#FFFFFF'],
  SUI: [46.8182, 8.2275, '#FF0000', '#FFFFFF'],
  BRA: [-14.2350, -51.9253, '#FEDB00', '#009B3A'],
  MAR: [31.7917, -7.0926, '#C1272D', '#006233'],
  HAI: [18.9712, -72.2852, '#D21034', '#00209F'],
  SCO: [56.4907, -4.2026, '#0065BF', '#FFFFFF'],
  USA: [37.0902, -95.7129, '#B22234', '#0B1F3F'],
  PAR: [-23.4425, -58.4438, '#D52B1E', '#0038A8'],
  AUS: [-25.2744, 133.7751, '#FFCD00', '#00843D'],
  TUR: [38.9637, 35.2433, '#E30A17', '#FFFFFF'],
  GER: [51.1657, 10.4515, '#FFCE00', '#DD0000'],
  CUW: [12.1696, -68.9900, '#002B7F', '#F9E814'],
  CIV: [7.5400, -5.5471, '#FF8200', '#009A44'],
  ECU: [-1.8312, -78.1834, '#FFD100', '#E8112D'],
  NED: [52.1326, 5.2913, '#F36C21', '#21468B'],
  JPN: [36.2048, 138.2529, '#BC002D', '#FFFFFF'],
  SWE: [60.1282, 18.6435, '#FECC00', '#006AA7'],
  TUN: [33.8869, 9.5375, '#E70013', '#FFFFFF'],
  BEL: [50.5039, 4.4699, '#FAE042', '#000000'],
  EGY: [26.8206, 30.8025, '#CE1126', '#000000'],
  IRN: [32.4279, 53.6880, '#239F40', '#DA0000'],
  NZL: [-40.9006, 174.8860, '#0C2340', '#CE1126'],
  ESP: [40.4637, -3.7492, '#FFC400', '#C60B1E'],
  CPV: [16.5388, -23.0418, '#003893', '#FFFFFF'],
  KSA: [23.8859, 45.0792, '#006C35', '#FFFFFF'],
  URU: [-32.5228, -55.7658, '#74ACDF', '#FCD116'],
  FRA: [46.2276, 2.2137, '#0055A4', '#EF4135'],
  SEN: [14.4974, -14.4524, '#00853F', '#FDEF42'],
  IRQ: [33.2232, 43.6793, '#CE1126', '#007A3D'],
  NOR: [60.4720, 8.4689, '#EF2B2D', '#002868'],
  ARG: [-38.4161, -63.6167, '#74ACDF', '#FFFFFF'],
  ALG: [28.0339, 1.6596, '#006233', '#D21034'],
  AUT: [47.5162, 14.5501, '#ED2939', '#FFFFFF'],
  JOR: [30.5852, 36.2384, '#007A3D', '#000000'],
  POR: [39.3999, -8.2245, '#046A38', '#FF0000'],
  COD: [-4.0383, 21.7587, '#007FFF', '#F7D618'],
  UZB: [41.3775, 64.5853, '#1EB53A', '#0099B5'],
  COL: [4.5709, -74.2973, '#FCD116', '#CE1126'],
  ENG: [52.3555, -1.1743, '#CE1124', '#FFFFFF'],
  CRO: [45.1000, 15.2000, '#FF0000', '#171796'],
  GHA: [7.9465, -1.0232, '#FCD116', '#CE1126'],
  PAN: [8.5380, -80.7821, '#D21034', '#005293'],
};

// Map ISO-3 → numeric topojson IDs for world-atlas (matches Natural Earth admin-0)
const ISO3_TO_NUM = {
  MEX: '484', RSA: '710', KOR: '410', CZE: '203', CAN: '124', BIH: '070',
  QAT: '634', SUI: '756', BRA: '076', MAR: '504', HAI: '332', SCO: '826', // Scotland → GBR (we'll specialcase)
  USA: '840', PAR: '600', AUS: '036', TUR: '792', GER: '276', CUW: '531',
  CIV: '384', ECU: '218', NED: '528', JPN: '392', SWE: '752', TUN: '788',
  BEL: '056', EGY: '818', IRN: '364', NZL: '554', ESP: '724', CPV: '132',
  KSA: '682', URU: '858', FRA: '250', SEN: '686', IRQ: '368', NOR: '578',
  ARG: '032', ALG: '012', AUT: '040', JOR: '400', POR: '620', COD: '180',
  UZB: '860', COL: '170', ENG: '826', CRO: '191', GHA: '288', PAN: '591',
};
// ENG + SCO both share '826' (United Kingdom in topojson) — both will color it; that's fine for UI

const WCI_COUNTRY_TOKEN_REGISTRY = {
  ALG: { name: 'Algeria 26', countryName: 'Algeria', ticker: 'ALG26' },
  ARG: { name: 'Argentina 26', countryName: 'Argentina', ticker: 'ARG26' },
  AUS: { name: 'Australia 26', countryName: 'Australia', ticker: 'AUS26' },
  AUT: { name: 'Austria 26', countryName: 'Austria', ticker: 'AUT26' },
  BEL: { name: 'Belgium 26', countryName: 'Belgium', ticker: 'BEL26' },
  BIH: { name: 'Bosnia 26', countryName: 'Bosnia', ticker: 'BIH26' },
  BRA: { name: 'Brazil 26', countryName: 'Brazil', ticker: 'BRA26' },
  CAN: { name: 'Canada 26', countryName: 'Canada', ticker: 'CAN26' },
  CPV: { name: 'Cape Verde 26', countryName: 'Cape Verde', ticker: 'CPV26' },
  COL: { name: 'Colombia 26', countryName: 'Colombia', ticker: 'COL26' },
  CRO: { name: 'Croatia 26', countryName: 'Croatia', ticker: 'CRO26' },
  CUW: { name: 'Curacao 26', countryName: 'Curacao', ticker: 'CUR26' },
  CZE: { name: 'Czechia 26', countryName: 'Czechia', ticker: 'CZE26' },
  COD: { name: 'DR Congo 26', countryName: 'DR Congo', ticker: 'COD26' },
  ECU: { name: 'Ecuador 26', countryName: 'Ecuador', ticker: 'ECU26' },
  EGY: { name: 'Egypt 26', countryName: 'Egypt', ticker: 'EGY26' },
  ENG: { name: 'England 26', countryName: 'England', ticker: 'ENG26' },
  FRA: { name: 'France 26', countryName: 'France', ticker: 'FRA26' },
  GER: { name: 'Germany 26', countryName: 'Germany', ticker: 'GER26' },
  GHA: { name: 'Ghana 26', countryName: 'Ghana', ticker: 'GHA26' },
  HAI: { name: 'Haiti 26', countryName: 'Haiti', ticker: 'HAI26' },
  IRN: { name: 'Iran 26', countryName: 'Iran', ticker: 'IRN26' },
  IRQ: { name: 'Iraq 26', countryName: 'Iraq', ticker: 'IRQ26' },
  CIV: { name: 'Ivory Coast 26', countryName: 'Ivory Coast', ticker: 'CIV26' },
  JPN: { name: 'Japan 26', countryName: 'Japan', ticker: 'JPN26' },
  JOR: { name: 'Jordan 26', countryName: 'Jordan', ticker: 'JOR26' },
  MEX: { name: 'Mexico 26', countryName: 'Mexico', ticker: 'MEX26' },
  MAR: { name: 'Morocco 26', countryName: 'Morocco', ticker: 'MAR26' },
  NED: { name: 'Netherlands 26', countryName: 'Netherlands', ticker: 'NED26' },
  NZL: { name: 'New Zealand 26', countryName: 'New Zealand', ticker: 'NZL26' },
  NOR: { name: 'Norway 26', countryName: 'Norway', ticker: 'NOR26' },
  PAN: { name: 'Panama 26', countryName: 'Panama', ticker: 'PAN26' },
  PAR: { name: 'Paraguay 26', countryName: 'Paraguay', ticker: 'PAR26' },
  POR: { name: 'Portugal 26', countryName: 'Portugal', ticker: 'POR26' },
  QAT: { name: 'Qatar 26', countryName: 'Qatar', ticker: 'QAT26' },
  KSA: { name: 'Saudi Arabia 26', countryName: 'Saudi Arabia', ticker: 'SAU26' },
  SCO: { name: 'Scotland 26', countryName: 'Scotland', ticker: 'SCO26' },
  SEN: { name: 'Senegal 26', countryName: 'Senegal', ticker: 'SEN26' },
  RSA: { name: 'South Africa 26', countryName: 'South Africa', ticker: 'RSA26' },
  KOR: { name: 'South Korea 26', countryName: 'South Korea', ticker: 'KOR26' },
  ESP: { name: 'Spain 26', countryName: 'Spain', ticker: 'ESP26' },
  SWE: { name: 'Sweden 26', countryName: 'Sweden', ticker: 'SWE26' },
  SUI: { name: 'Switzerland 26', countryName: 'Switzerland', ticker: 'SUI26' },
  TUN: { name: 'Tunisia 26', countryName: 'Tunisia', ticker: 'TUN26' },
  TUR: { name: 'Turkey 26', countryName: 'Turkey', ticker: 'TUR26' },
  URU: { name: 'Uruguay 26', countryName: 'Uruguay', ticker: 'URU26' },
  USA: { name: 'USA 26', countryName: 'USA', ticker: 'USA26' },
  UZB: { name: 'Uzbekistan 26', countryName: 'Uzbekistan', ticker: 'UZB26' },
};

const getWciCountryTokenInfo = (code) => {
  const normalized = String(code || '').toUpperCase();
  const fallbackName = window.TEAM_NAMES?.[normalized] || normalized;
  return WCI_COUNTRY_TOKEN_REGISTRY[normalized] || {
    name: `${fallbackName} 26`,
    countryName: fallbackName,
    ticker: `${normalized}26`,
  };
};

const wciCountryTicker = (countryOrCode) => {
  if (typeof countryOrCode === 'string') return getWciCountryTokenInfo(countryOrCode).ticker;
  return String(countryOrCode?.ticker || countryOrCode?.symbol || getWciCountryTokenInfo(countryOrCode?.code).ticker)
    .replace(/^\$/, '');
};

const wciCountryDollarTicker = (countryOrCode) => `$${wciCountryTicker(countryOrCode)}`;

// Generate market data with rank-based distribution
// Pre-seeded so order is stable across reloads
const MARKET_SEED = {
  // [code, baseRank, basePrice, momentum] — momentum = how spicy this country is
  BRA: [1,  0.0000421, 1.20], ARG: [2,  0.0000384, 1.15], ENG: [3,  0.0000352, 1.10],
  FRA: [4,  0.0000341, 1.08], GER: [5,  0.0000324, 1.05], ESP: [6,  0.0000297, 1.02],
  POR: [7,  0.0000281, 1.00], NED: [8,  0.0000265, 0.98], USA: [9,  0.0000248, 0.95],
  ITA: [99, 0,         0],    // not in WC, ignore
  BEL: [10, 0.0000231, 0.92], JPN: [11, 0.0000218, 0.90], KOR: [12, 0.0000204, 0.88],
  MEX: [13, 0.0000193, 0.86], URU: [14, 0.0000181, 0.85], COL: [15, 0.0000172, 0.83],
  CRO: [16, 0.0000164, 0.81], MAR: [17, 0.0000156, 0.80], SEN: [18, 0.0000148, 0.78],
  SUI: [19, 0.0000141, 0.77], TUR: [20, 0.0000134, 0.76], AUS: [21, 0.0000128, 0.74],
  GHA: [22, 0.0000122, 0.73], NOR: [23, 0.0000117, 0.72], SWE: [24, 0.0000112, 0.71],
  AUT: [25, 0.0000107, 0.70], CIV: [26, 0.0000102, 0.69], EGY: [27, 0.0000098, 0.68],
  PAR: [28, 0.0000094, 0.67], ECU: [29, 0.0000090, 0.66], IRN: [30, 0.0000086, 0.65],
  TUN: [31, 0.0000083, 0.64], ALG: [32, 0.0000080, 0.63], CAN: [33, 0.0000077, 0.62],
  KSA: [34, 0.0000074, 0.61], CZE: [35, 0.0000071, 0.60], SCO: [36, 0.0000068, 0.59],
  RSA: [37, 0.0000066, 0.58], COD: [38, 0.0000063, 0.57], UZB: [39, 0.0000061, 0.56],
  PAN: [40, 0.0000059, 0.55], JOR: [41, 0.0000057, 0.54], IRQ: [42, 0.0000055, 0.53],
  NZL: [43, 0.0000053, 0.52], HAI: [44, 0.0000051, 0.51], BIH: [45, 0.0000049, 0.50],
  QAT: [46, 0.0000047, 0.49], CPV: [47, 0.0000046, 0.48], CUW: [48, 0.0000044, 0.47],
};

// Seeded pseudo-random for stable per-country values
const seedRand = (seed) => {
  let s = seed;
  return () => {
    s = (s * 9301 + 49297) % 233280;
    return s / 233280;
  };
};

// Build full country roster
const buildCountryTokens = (marketState = 'live') => {
  // Multiplier per state
  const stateMul = { calm: 0.4, live: 1.0, euphoric: 2.4 }[marketState] || 1.0;

  const rows = [];
  for (const code of Object.keys(COUNTRY_GEO)) {
    const seed = MARKET_SEED[code];
    if (!seed) continue;
    const [baseRank, basePrice, momentum] = seed;
    const r = seedRand(code.charCodeAt(0) * 137 + code.charCodeAt(1) * 31 + code.charCodeAt(2));
    const [lat, lng, primary, secondary] = COUNTRY_GEO[code];
    const tokenInfo = getWciCountryTokenInfo(code);

    // Volume scales with momentum + state, with country-specific jitter
    const volume24h = Math.round(momentum * stateMul * (1.4e6 + r() * 1.6e6));
    const holders = Math.round(momentum * (2400 + r() * 8000));
    const change24h = ((r() - 0.3) * 40 * (stateMul * 0.6 + 0.4));
    const price = basePrice * (1 + change24h / 200);
    // Mcap = price × ~1T tokens supply (meme coin scale)
    const mcap = Math.round(price * (8e11 + r() * 4e11));
    const buys1m = Math.round(momentum * stateMul * (20 + r() * 60));

    rows.push({
      code,
      name: tokenInfo.name,
      countryName: tokenInfo.countryName,
      ticker: tokenInfo.ticker,
      symbol: tokenInfo.ticker,
      tokenSymbol: `$${tokenInfo.ticker}`,
      group: window.teamGroup?.(code) || '?',
      lat, lng,
      color: primary,
      secondary,
      price,
      change24h,
      volume24h,
      holders,
      mcap,
      buys1m,
      momentum,
      rank: 0, // assigned below
    });
  }

  // Sort by volume24h desc → assign ranks
  rows.sort((a, b) => b.volume24h - a.volume24h);
  rows.forEach((r, i) => { r.rank = i + 1; });
  return rows;
};

// Live ticker — recent buys (synthetic)
const buildTicker = (countries, count = 24) => {
  const ticker = [];
  for (let i = 0; i < count; i++) {
    const c = countries[Math.floor(Math.random() * Math.min(20, countries.length))];
    const amount = Math.round(100 + Math.random() * 4900);
    ticker.push({
      id: `t-${Date.now()}-${i}`,
      code: c.code,
      name: c.name,
      ticker: c.ticker,
      symbol: c.symbol,
      tokenSymbol: c.tokenSymbol,
      amount,
      color: c.color,
      ts: Date.now() - i * 4000 - Math.random() * 3000,
    });
  }
  return ticker;
};

// Format helpers
const fmtPrice = (p) => {
  if (p < 0.001) return `$${p.toFixed(7)}`;
  if (p < 1) return `$${p.toFixed(4)}`;
  return `$${p.toFixed(2)}`;
};
const fmtVol = (v) => {
  if (v >= 1e6) return `$${(v / 1e6).toFixed(2)}M`;
  if (v >= 1e3) return `$${(v / 1e3).toFixed(1)}K`;
  return `$${v}`;
};
const fmtNum = (n) => n.toLocaleString('en-US');
const fmtMcap = (n) => {
  if (n >= 1e9) return `$${(n / 1e9).toFixed(2)}B`;
  if (n >= 1e6) return `$${(n / 1e6).toFixed(1)}M`;
  return `$${(n / 1e3).toFixed(0)}K`;
};

// Buyback pool — fees from all country tokens flow here
const calcBuybackPool = (countries) => {
  // 5% fee on every buy → roughly 1% of daily volume across all 48 countries goes to buyback
  const totalVol = countries.reduce((s, c) => s + c.volume24h, 0);
  return Math.round(totalVol * 0.05);
};

// $WCI26 token info
const WCI_TOKEN = {
  symbol: '$WCI26',
  price: 0,
  change24h: 0,
  marketCap: 0,
  buybackPool: 0, // computed
  buybackTarget: 1_000_000,
  totalBuybacks: 0,
  holders: 0,
  dataState: 'external-market-feed',
};

Object.assign(window, {
  COUNTRY_GEO, ISO3_TO_NUM, MARKET_SEED,
  WCI_COUNTRY_TOKEN_REGISTRY, getWciCountryTokenInfo, wciCountryTicker, wciCountryDollarTicker,
  buildCountryTokens, buildTicker,
  fmtPrice, fmtVol, fmtNum, fmtMcap,
  calcBuybackPool, WCI_TOKEN,
});
