// Polls Delta public /v2/tickers and returns a ranked snapshot of the
// most-active USD perpetual contracts. Used by the dashboard Trend Matrix
// to auto-populate "trending" coins without a WebSocket subscription.

import { useEffect, useState } from "react";

export interface TrendingRow {
  symbol: string;
  price: number;
  change24h?: number;
  volume24h?: number;
  turnover?: number;
  contract_type?: string;
}

const ENDPOINTS = [
  "https://api.india.delta.exchange/v2/tickers",
  "https://api.delta.exchange/v2/tickers",
];

async function fetchAllTickers(): Promise<TrendingRow[]> {
  for (const url of ENDPOINTS) {
    try {
      const r = await fetch(url, { cache: "no-store" });
      if (!r.ok) continue;
      const j = await r.json();
      const list: any[] = Array.isArray(j?.result) ? j.result : [];
      if (!list.length) continue;
      const rows: TrendingRow[] = [];
      for (const row of list) {
        const symbol: string | undefined = row?.symbol;
        if (!symbol) continue;
        const contract_type: string = row.contract_type || "";
        // Only USD/USDT perpetuals — spot/options add noise to a trend matrix.
        if (contract_type && !contract_type.includes("perpetual")) continue;
        if (!/USDT?$/.test(symbol)) continue;
        const price = Number(row.mark_price ?? row.close ?? row.spot_price ?? row.last_price);
        if (!Number.isFinite(price) || price <= 0) continue;
        const open = Number(row.open ?? row.open_price ?? price);
        const change24h =
          row.change_24h != null
            ? Number(row.change_24h)
            : open
              ? ((price - open) / open) * 100
              : undefined;
        const volume24h = Number(row.volume ?? 0) || undefined;
        const turnover = Number(row.turnover_usd ?? row.turnover ?? 0) || undefined;
        rows.push({ symbol, price, change24h, volume24h, turnover, contract_type });
      }
      // Rank by turnover_usd desc (fallback: |change24h|).
      rows.sort((a, b) => {
        const ta = a.turnover ?? 0;
        const tb = b.turnover ?? 0;
        if (tb !== ta) return tb - ta;
        return Math.abs(b.change24h ?? 0) - Math.abs(a.change24h ?? 0);
      });
      return rows;
    } catch {
      /* try next endpoint */
    }
  }
  return [];
}

export function useTrendingTickers(pollMs = 15000) {
  const [rows, setRows] = useState<TrendingRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    async function pull() {
      try {
        const r = await fetchAllTickers();
        if (cancelled) return;
        if (r.length === 0) setError("No tickers available");
        else {
          setRows(r);
          setError(null);
        }
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : "Failed to load");
      } finally {
        if (!cancelled) setLoading(false);
      }
    }
    pull();
    const iv = window.setInterval(pull, pollMs);
    return () => {
      cancelled = true;
      window.clearInterval(iv);
    };
  }, [pollMs]);

  return { rows, loading, error };
}
