"use client";

import { useEffect, useState } from "react";

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

const MAX_CURRENCY_LOAD_ATTEMPTS = 3;
const RETRY_DELAY_MS = 2_000;

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

export function useCurrencyCatalog() {
  const currencies = usePlayerSessionStore((state) => state.currencies);
  const setCurrencies = usePlayerSessionStore((state) => state.setCurrencies);
  const [loadGeneration, setLoadGeneration] = useState(0);

  useEffect(() => {
    if (currencies.length > 0 || loadGeneration >= MAX_CURRENCY_LOAD_ATTEMPTS) {
      return;
    }

    if (inflightCurrencyLoad !== null) {
      return;
    }

    inflightCurrencyLoad = getPublicCurrencies()
      .then((data) => {
        if (data.items.length > 0) {
          setCurrencies(data.items);
          return;
        }
        throw new Error("empty_currency_catalog");
      })
      .catch(() => {
        window.setTimeout(() => {
          setLoadGeneration((current) => current + 1);
        }, RETRY_DELAY_MS);
      })
      .finally(() => {
        inflightCurrencyLoad = null;
      });
  }, [currencies.length, setCurrencies, loadGeneration]);

  return currencies;
}