"use client";

import { useEffect } from "react";

import { getPublicCurrencies } from "@/api/currency";
import { usePlayerSessionStore } from "@/stores/player-session-store";

let inflightCurrencyLoad: Promise<void> | null = null;

export function useCurrencyCatalog() {
  const currencies = usePlayerSessionStore((state) => state.currencies);
  const setCurrencies = usePlayerSessionStore((state) => state.setCurrencies);

  useEffect(() => {
    if (currencies.length > 0 || inflightCurrencyLoad !== null) {
      return;
    }

    inflightCurrencyLoad = getPublicCurrencies()
      .then((data) => {
        setCurrencies(data.items);
      })
      .catch(() => {
        // 币种元数据失败时退回默认 2 位小数，不打断主流程。
      })
      .finally(() => {
        inflightCurrencyLoad = null;
      });
  }, [currencies.length, setCurrencies]);

  return currencies;
}
