// Live data hook — only rock-solid free APIs, no CORS proxies, no fragile sources.
//
//   Crypto  → CoinGecko (https://api.coingecko.com)              — works in browser
//   Forex   → Fawaz currency-api on jsDelivr CDN                 — guaranteed CORS
//
// Indices, commodities and yields keep their seed values — the free APIs that
// expose them (Yahoo, Stooq) block browser CORS or require API keys, and the
// user explicitly does not need tick-level data here.

window.useLiveTicker = function useLiveTicker() {
  const seed = [
    { sym: 'BTC·USD', px: '94,820',  ch: '+1.42%', positive: true  },
    { sym: 'ETH·USD', px: '3,318',   ch: '+0.86%', positive: true  },
    { sym: 'SOL·USD', px: '178.4',   ch: '−0.92%', positive: false },
    { sym: 'SPX',     px: '5,712.4', ch: '+0.34%', positive: true  },
    { sym: 'NDX',     px: '20,184',  ch: '+0.51%', positive: true  },
    { sym: 'DXY',     px: '105.92',  ch: '−0.18%', positive: false },
    { sym: 'EUR·USD', px: '1.0814',  ch: '+0.12%', positive: true  },
    { sym: 'USD·JPY', px: '154.62',  ch: '+0.28%', positive: true  },
    { sym: 'GOLD',    px: '2,418',   ch: '+0.42%', positive: true  },
    { sym: 'WTI',     px: '78.14',   ch: '−0.56%', positive: false },
    { sym: 'US10Y',   px: '4.382%',  ch: '+0.6bp', positive: true  },
    { sym: 'VIX',     px: '14.82',   ch: '−1.2%',  positive: false },
  ];

  const [ticks,     setTicks]     = React.useState(seed);
  const [status,    setStatus]    = React.useState('seed');
  const [updatedAt, setUpdatedAt] = React.useState(null);

  React.useEffect(() => {
    let alive = true;

    const fmt = (n, dec = 2) =>
      isFinite(n) ? Number(n).toLocaleString('en-US', { minimumFractionDigits: dec, maximumFractionDigits: dec }) : '—';
    const pct = n => (n >= 0 ? '+' : '−') + Math.abs(n).toFixed(2) + '%';

    async function safeJson(url) {
      try {
        const r = await fetch(url, { cache: 'no-store' });
        if (!r.ok) return null;
        return await r.json();
      } catch { return null; }
    }

    // Crypto via CoinGecko
    async function loadCrypto() {
      const url = 'https://api.coingecko.com/api/v3/simple/price'
        + '?ids=bitcoin,ethereum,solana&vs_currencies=usd&include_24hr_change=true';
      const d = await safeJson(url);
      if (!d) return [];
      const map = { bitcoin: 'BTC·USD', ethereum: 'ETH·USD', solana: 'SOL·USD' };
      const out = [];
      for (const [id, sym] of Object.entries(map)) {
        const p = d[id];
        if (!p || !isFinite(p.usd)) continue;
        const ch  = p.usd_24h_change ?? 0;
        const dec = p.usd > 1000 ? 0 : (p.usd > 10 ? 1 : 2);
        out.push({ sym, px: fmt(p.usd, dec), ch: pct(ch), positive: ch >= 0 });
      }
      return out;
    }

    // Forex via Fawaz on jsDelivr (primary) + Cloudflare mirror (fallback).
    // jsDelivr serves npm packages with universal CORS — this works in every browser.
    async function loadForex() {
      const fetchBase = async (base) => {
        const lower = base.toLowerCase();
        // Primary: jsDelivr
        let d = await safeJson(`https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/${lower}.json`);
        if (d?.[lower]) return d[lower];
        // Fallback: Cloudflare Pages mirror of the same dataset
        d = await safeJson(`https://latest.currency-api.pages.dev/v1/currencies/${lower}.json`);
        if (d?.[lower]) return d[lower];
        return null;
      };

      const out = [];
      const [eur, usd] = await Promise.all([fetchBase('EUR'), fetchBase('USD')]);

      if (eur && isFinite(eur.usd)) {
        out.push({ sym: 'EUR·USD', px: fmt(eur.usd, 4), ch: pct(0), positive: true });
      }
      if (usd && isFinite(usd.jpy)) {
        out.push({ sym: 'USD·JPY', px: fmt(usd.jpy, 2), ch: pct(0), positive: true });
      }
      return out;
    }

    async function loadAll() {
      // Start from seed so any symbol that fails simply keeps its previous/seed value.
      const merged = seed.map(x => ({ ...x }));
      const apply = (arr) => {
        for (const item of (arr || [])) {
          const i = merged.findIndex(x => x.sym === item.sym);
          if (i >= 0) merged[i] = { ...merged[i], ...item };
        }
      };

      const [crypto, fx] = await Promise.all([loadCrypto(), loadForex()]);
      apply(crypto);
      apply(fx);

      const liveCount = (crypto?.length || 0) + (fx?.length || 0);

      if (!alive) return;
      setTicks(merged);
      setStatus(liveCount > 0 ? 'live' : 'seed');
      if (liveCount > 0) setUpdatedAt(new Date());
    }

    loadAll();
    const id = setInterval(loadAll, 60_000);
    return () => { alive = false; clearInterval(id); };
  }, []);

  return { ticks, status, updatedAt };
};
