/**
 * Price ticker — server component fetching live prices DIRECTLY from upstream APIs.
 * Avoids the chicken-and-egg of internal /api/prices route during build-time prerender.
 *
 * Sources:
 *  - CoinGecko free public API (BTC, ETH, SOL) — 30 calls/min, no key
 *  - gold-api.com (XAU)
 *  - open.er-api.com (USD/VND)
 *
 * Cache: 60s revalidate, gracefully degrades to null when no upstream responds.
 */

interface Quote {
  symbol: string;
  value: string;
  changePct: number;
}

async function fetchCoinGecko(): Promise<Record<string, { value: number; change: number }>> {
  try {
    const res = await fetch(
      "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum,solana&vs_currencies=usd&include_24hr_change=true",
      { next: { revalidate: 60 }, headers: { accept: "application/json" } }
    );
    if (!res.ok) return {};
    const data = (await res.json()) as Record<string, { usd: number; usd_24h_change: number }>;
    const out: Record<string, { value: number; change: number }> = {};
    if (data.bitcoin?.usd) out.BTC = { value: data.bitcoin.usd, change: data.bitcoin.usd_24h_change ?? 0 };
    if (data.ethereum?.usd) out.ETH = { value: data.ethereum.usd, change: data.ethereum.usd_24h_change ?? 0 };
    if (data.solana?.usd) out.SOL = { value: data.solana.usd, change: data.solana.usd_24h_change ?? 0 };
    return out;
  } catch {
    return {};
  }
}

async function fetchGoldUsd(): Promise<{ value: number; change: number } | null> {
  try {
    const res = await fetch("https://api.gold-api.com/price/XAU", { next: { revalidate: 300 } });
    if (!res.ok) return null;
    const json = (await res.json()) as { price: number };
    if (!json.price) return null;
    return { value: json.price, change: 0 };
  } catch {
    return null;
  }
}

async function fetchUsdVnd(): Promise<{ value: number; change: number } | null> {
  try {
    const res = await fetch("https://open.er-api.com/v6/latest/USD", { next: { revalidate: 600 } });
    if (!res.ok) return null;
    const json = (await res.json()) as { rates?: { VND?: number } };
    if (!json.rates?.VND) return null;
    return { value: json.rates.VND, change: 0 };
  } catch {
    return null;
  }
}

function fmt(n: number, dp = 0): string {
  return new Intl.NumberFormat("en-US", { maximumFractionDigits: dp }).format(n);
}

async function getQuotes(): Promise<Quote[]> {
  const [cg, gold, usdVnd] = await Promise.all([fetchCoinGecko(), fetchGoldUsd(), fetchUsdVnd()]);
  const q: Quote[] = [];
  if (cg.BTC) q.push({ symbol: "BTC", value: fmt(cg.BTC.value, 0), changePct: cg.BTC.change });
  if (cg.ETH) q.push({ symbol: "ETH", value: fmt(cg.ETH.value, 0), changePct: cg.ETH.change });
  if (cg.SOL) q.push({ symbol: "SOL", value: fmt(cg.SOL.value, 1), changePct: cg.SOL.change });
  if (gold) q.push({ symbol: "XAU", value: fmt(gold.value, 0), changePct: gold.change });
  if (usdVnd) q.push({ symbol: "USD/VND", value: fmt(usdVnd.value, 0), changePct: usdVnd.change });
  return q;
}

export async function Ticker() {
  const items = await getQuotes();

  // Hide ticker entirely when we have no live data — better than showing wrong numbers.
  if (items.length === 0) return null;

  // Need 8+ items to fill a wide screen seamlessly. Repeat reel.
  const minRepeat = 8;
  const reel: Quote[] = [];
  while (reel.length < minRepeat) reel.push(...items);
  // Duplicate once more for seamless infinite-loop animation
  reel.push(...reel.slice(0, items.length));

  return (
    <div
      className="overflow-hidden"
      style={{ background: "var(--ink)", color: "var(--paper)" }}
    >
      <div className="ticker-track py-2 text-[12px]">
        {reel.map((q, i) => (
          <span
            key={`${q.symbol}-${i}`}
            className="flex items-center gap-2 font-[family-name:var(--font-jetbrains-mono)] font-mono shrink-0"
          >
            <span className="font-semibold">{q.symbol}</span>
            <span className="opacity-50">·</span>
            <span>{q.value}</span>
            {q.changePct !== 0 && (
              <span style={{ color: q.changePct >= 0 ? "#8FB35F" : "#D6685C" }}>
                {q.changePct >= 0 ? "▲" : "▼"} {q.changePct >= 0 ? "+" : ""}
                {q.changePct.toFixed(2)}%
              </span>
            )}
          </span>
        ))}
      </div>
    </div>
  );
}
