// wci26/wci-market.jsx - live WCI26 market adapter from the public WCI26/WETH pair.

const WCI26_MAINNET_TOKEN_ADDRESS = '0x80171b59e47EB9c385af40b09Cc345d79Ea40Ba8';
const WCI26_MAINNET_PAIR_ADDRESS = '0xe8d5B1768b6dCdd14A699DF855C63aB62E1fD8B1';
const WCI26_DEXSCREENER_URL = 'https://dexscreener.com/ethereum/0xe8d5b1768b6dcdd14a699df855c63ab62e1fd8b1';
const WCI26_DEXSCREENER_API = 'https://api.dexscreener.com/latest/dex/pairs/ethereum/0xe8d5b1768b6dcdd14a699df855c63ab62e1fd8b1';

const wciMarketNumber = (value, fallback = 0) => {
  const n = Number(value);
  return Number.isFinite(n) ? n : fallback;
};

const wciFormatUsdPrice = (value, fallback = '--') => {
  const n = Number(value);
  if (!Number.isFinite(n) || n <= 0) return fallback;
  if (n < 0.01) {
    return `$${n.toFixed(8).replace(/0+$/, '').replace(/\.$/, '')}`;
  }
  if (n < 1) return `$${n.toFixed(4)}`;
  return `$${n.toLocaleString('en-US', { maximumFractionDigits: 2 })}`;
};

const wciFormatCompactUsd = (value, fallback = '--') => {
  const n = Number(value);
  if (!Number.isFinite(n) || n <= 0) return fallback;
  if (n >= 1e9) return `$${(n / 1e9).toFixed(2)}B`;
  if (n >= 1e6) return `$${(n / 1e6).toFixed(2)}M`;
  if (n >= 1e3) return `$${(n / 1e3).toFixed(1)}K`;
  return `$${n.toFixed(0)}`;
};

const wciEstimateEthUsd = (marketSnapshot) => {
  const market = marketSnapshot || (typeof WCI_MARKET_DATA !== 'undefined' && WCI_MARKET_DATA.getSnapshot
    ? WCI_MARKET_DATA.getSnapshot()
    : null);
  const priceUsd = wciMarketNumber(market?.priceUsd);
  const priceNative = wciMarketNumber(market?.priceNative);
  return priceUsd > 0 && priceNative > 0 ? priceUsd / priceNative : 0;
};

const wciWethToUsd = (valueWeth, options = {}) => {
  const ethUsd = wciMarketNumber(options.ethUsd) || wciEstimateEthUsd(options.market);
  const weth = wciMarketNumber(valueWeth);
  return ethUsd > 0 && weth > 0 ? weth * ethUsd : 0;
};

const wciLooksLiveCountry = (country = {}) => {
  const state = [
    country.dashboardDataState,
    country.liveDataState,
    country.dataState,
    country.volumeUnit,
    country.volume24hUnit,
  ].map((value) => String(value || '').toLowerCase()).join(' ');
  return /live|rpc|sepolia|indexer|weth/.test(state)
    || wciMarketNumber(country.recentSwapVolumeWETH) > 0
    || wciMarketNumber(country.volume24hWETH) > 0
    || wciMarketNumber(country.priceWETH) > 0;
};

const wciFirstPositive = (...values) => {
  for (const value of values) {
    const n = wciMarketNumber(value);
    if (n > 0) return n;
  }
  return 0;
};

const wciCountryMarketCapUsd = (country = {}, options = {}) => {
  const explicitUsd = wciMarketNumber(country.marketCapUsd || country.mcapUsd);
  if (explicitUsd > 0) return explicitUsd;

  const marketCapWETH = wciMarketNumber(country.marketCapWETH);
  const converted = wciWethToUsd(marketCapWETH, options);
  if (converted > 0) return converted;

  const legacyMcap = wciMarketNumber(country.mcap);
  return legacyMcap > 1000 ? legacyMcap : 0;
};

const wciCountryPriceUsd = (country = {}, options = {}) => {
  const explicitUsd = wciMarketNumber(country.priceUsd || country.usdPrice || country.tokenPriceUsd);
  if (explicitUsd > 0) return explicitUsd;

  const priceWETH = wciFirstPositive(country.priceWETH, country.tokenPriceWETH);
  const converted = wciWethToUsd(priceWETH, options);
  if (converted > 0) return converted;

  const legacyPrice = wciMarketNumber(country.price);
  if (legacyPrice <= 0) return 0;
  const liveConverted = wciLooksLiveCountry(country) ? wciWethToUsd(legacyPrice, options) : 0;
  return liveConverted > 0 ? liveConverted : legacyPrice;
};

const wciCountryVolumeUsd = (country = {}, options = {}) => {
  const explicitUsd = wciMarketNumber(country.volume24hUsd || country.poolVolumeUsd);
  if (explicitUsd > 0) return explicitUsd;

  const volumeWETH = wciFirstPositive(
    country.volume24hWETH,
    country.rolling24hVolumeWETH,
    country.recentSwapVolumeWETH,
    country.totalVolumeWETH,
    country.contractVolumeWETH
  );
  const converted = wciWethToUsd(volumeWETH, options);
  if (converted > 0) return converted;

  const legacyVolume = wciMarketNumber(country.volume24h);
  const liveConverted = wciLooksLiveCountry(country) ? wciWethToUsd(legacyVolume, options) : 0;
  if (liveConverted > 0) return liveConverted;
  return legacyVolume > 0 ? legacyVolume : 0;
};

const wciAggregateCountryVolumeUsd = (countries = [], options = {}) => (
  (Array.isArray(countries) ? countries : [])
    .reduce((sum, country) => sum + wciCountryVolumeUsd(country, options), 0)
);

const wciAggregateCountryMarketCapUsd = (countries = [], options = {}) => (
  (Array.isArray(countries) ? countries : [])
    .reduce((sum, country) => sum + wciCountryMarketCapUsd(country, options), 0)
);

const wciFormatCountryMarketCap = (country, options = {}) => (
  wciFormatCompactUsd(wciCountryMarketCapUsd(country, options), options.fallback || '$--')
);

const wciFormatCountryPrice = (country, options = {}) => (
  wciFormatUsdPrice(wciCountryPriceUsd(country, options), options.fallback || '--')
);

const wciFormatCountryVolume = (country, options = {}) => (
  wciFormatCompactUsd(wciCountryVolumeUsd(country, options), options.fallback || '$0')
);

const wciFormatAggregateCountryVolume = (countries, options = {}) => (
  wciFormatCompactUsd(wciAggregateCountryVolumeUsd(countries, options), options.fallback || '$0')
);

const wciFormatAggregateCountryMarketCap = (countries, options = {}) => (
  wciFormatCompactUsd(wciAggregateCountryMarketCapUsd(countries, options), options.fallback || '$--')
);

const wciFormatWethUsd = (valueWeth, options = {}) => (
  wciFormatCompactUsd(wciWethToUsd(valueWeth, options), options.fallback || '$0')
);

const wciFormatPct = (value, fallback = '--') => {
  const n = Number(value);
  if (!Number.isFinite(n)) return fallback;
  return `${n >= 0 ? '+' : ''}${n.toFixed(1)}%`;
};

const WCI_MARKET_EMPTY = {
  symbol: '$WCI26',
  name: 'World Cup Inu',
  tokenAddress: WCI26_MAINNET_TOKEN_ADDRESS,
  pairAddress: WCI26_MAINNET_PAIR_ADDRESS,
  chainId: 'ethereum',
  dexId: 'uniswap',
  sourceUrl: WCI26_DEXSCREENER_URL,
  apiUrl: WCI26_DEXSCREENER_API,
  priceUsd: 0,
  priceNative: 0,
  priceChange24h: 0,
  liquidityUsd: 0,
  pooledWci26: 0,
  pooledWeth: 0,
  marketCapUsd: 0,
  fdvUsd: 0,
  volume24hUsd: 0,
  txns24h: 0,
  buys24h: 0,
  sells24h: 0,
  updatedAt: null,
  dataState: 'loading',
  error: null,
};

const wciNormalizeMarketPair = (payload) => {
  const pair = payload?.pair || payload?.pairs?.[0] || payload;
  if (!pair) throw new Error('DexScreener WCI26 pair missing');

  const baseToken = pair.baseToken || {};
  const quoteToken = pair.quoteToken || {};
  const txns24h = pair.txns?.h24 || {};
  const liquidity = pair.liquidity || {};
  const symbol = baseToken.symbol || 'WCI26';

  return {
    ...WCI_MARKET_EMPTY,
    symbol: symbol.startsWith('$') ? symbol : `$${symbol}`,
    name: baseToken.name || WCI_MARKET_EMPTY.name,
    tokenAddress: baseToken.address || WCI26_MAINNET_TOKEN_ADDRESS,
    quoteSymbol: quoteToken.symbol || 'WETH',
    pairAddress: pair.pairAddress || WCI26_MAINNET_PAIR_ADDRESS,
    chainId: pair.chainId || 'ethereum',
    dexId: pair.dexId || 'uniswap',
    sourceUrl: pair.url || WCI26_DEXSCREENER_URL,
    priceUsd: wciMarketNumber(pair.priceUsd),
    priceNative: wciMarketNumber(pair.priceNative),
    priceChange24h: wciMarketNumber(pair.priceChange?.h24),
    liquidityUsd: wciMarketNumber(liquidity.usd),
    pooledWci26: wciMarketNumber(liquidity.base),
    pooledWeth: wciMarketNumber(liquidity.quote),
    marketCapUsd: wciMarketNumber(pair.marketCap || pair.fdv),
    fdvUsd: wciMarketNumber(pair.fdv || pair.marketCap),
    volume24hUsd: wciMarketNumber(pair.volume?.h24),
    txns24h: wciMarketNumber(txns24h.buys) + wciMarketNumber(txns24h.sells),
    buys24h: wciMarketNumber(txns24h.buys),
    sells24h: wciMarketNumber(txns24h.sells),
    updatedAt: Date.now(),
    dataState: 'live',
    error: null,
  };
};

const createWciMarketData = () => {
  let snapshot = { ...WCI_MARKET_EMPTY };
  let refreshPromise = null;
  const listeners = new Set();

  const notify = () => listeners.forEach((listener) => listener(snapshot));
  const setSnapshot = (next) => {
    snapshot = { ...snapshot, ...next };
    notify();
    return snapshot;
  };

  const refresh = async () => {
    if (refreshPromise) return refreshPromise;
    refreshPromise = fetch(WCI26_DEXSCREENER_API, { cache: 'no-store' })
      .then((response) => {
        if (!response.ok) throw new Error(`DexScreener WCI26 market fetch failed: ${response.status}`);
        return response.json();
      })
      .then((payload) => setSnapshot(wciNormalizeMarketPair(payload)))
      .catch((error) => {
        setSnapshot({
          dataState: snapshot.updatedAt ? 'stale' : 'error',
          error: error?.message || String(error),
        });
        throw error;
      })
      .finally(() => {
        refreshPromise = null;
      });
    return refreshPromise;
  };

  return {
    getSnapshot: () => snapshot,
    refresh,
    subscribe: (listener) => {
      listeners.add(listener);
      return () => listeners.delete(listener);
    },
    formatUsdPrice: wciFormatUsdPrice,
    formatCompactUsd: wciFormatCompactUsd,
    formatPct: wciFormatPct,
  };
};

const WCI_MARKET_DATA = createWciMarketData();

Object.assign(window, {
  WCI26_MAINNET_TOKEN_ADDRESS,
  WCI26_MAINNET_PAIR_ADDRESS,
  WCI26_DEXSCREENER_URL,
  WCI26_DEXSCREENER_API,
  WCI_MARKET_EMPTY,
  WCI_MARKET_DATA,
  wciFormatUsdPrice,
  wciFormatCompactUsd,
  wciEstimateEthUsd,
  wciWethToUsd,
  wciCountryPriceUsd,
  wciCountryMarketCapUsd,
  wciCountryVolumeUsd,
  wciAggregateCountryVolumeUsd,
  wciAggregateCountryMarketCapUsd,
  wciFormatCountryMarketCap,
  wciFormatCountryPrice,
  wciFormatCountryVolume,
  wciFormatAggregateCountryVolume,
  wciFormatAggregateCountryMarketCap,
  wciFormatWethUsd,
  wciFormatPct,
});
