import { useEffect, useState } from "react";

export interface DeltaProduct {
  symbol: string;
  description?: string;
  contract_type?: string;
  state?: string;
  underlying_asset?: { symbol?: string };
  quoting_asset?: { symbol?: string };
}

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

let cache: DeltaProduct[] | null = null;
let inflight: Promise<DeltaProduct[]> | null = null;

async function fetchProducts(): Promise<DeltaProduct[]> {
  if (cache) return cache;
  if (inflight) return inflight;
  inflight = (async () => {
    for (const url of ENDPOINTS) {
      try {
        const r = await fetch(url);
        if (!r.ok) continue;
        const j = await r.json();
        const list: DeltaProduct[] = (j?.result ?? []).filter((p: any) => p?.symbol);
        if (list.length) {
          cache = list;
          return list;
        }
      } catch {
        // try next
      }
    }
    return [];
  })();
  try {
    return await inflight;
  } finally {
    inflight = null;
  }
}

export function useDeltaProducts() {
  const [products, setProducts] = useState<DeltaProduct[]>(cache ?? []);
  const [loading, setLoading] = useState(!cache);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let alive = true;
    if (cache) return;
    fetchProducts()
      .then((list) => {
        if (!alive) return;
        setProducts(list);
        if (list.length === 0) setError("No products available");
      })
      .catch((e) => alive && setError(e instanceof Error ? e.message : "Failed to load"))
      .finally(() => alive && setLoading(false));
    return () => {
      alive = false;
    };
  }, []);

  return { products, loading, error };
}
