"use client";

import { useCallback, useMemo } from "react";

import { useCurrencyCatalog } from "@/hooks/use-currency-catalog";
import { listBettableCurrencies, pickActivePlayerCurrency } from "@/lib/player-currency-options";
import { usePlayerSessionStore } from "@/stores/player-session-store";

export function useActivePlayerCurrency() {
  useCurrencyCatalog();

  const profile = usePlayerSessionStore((state) => state.profile);
  const currencies = usePlayerSessionStore((state) => state.currencies);
  const selectedCurrency = usePlayerSessionStore((state) => state.selectedCurrency);
  const setSelectedCurrency = usePlayerSessionStore((state) => state.setSelectedCurrency);

  const bettableCurrencies = useMemo(
    () => listBettableCurrencies(currencies),
    [currencies],
  );

  const activeCurrency = useMemo(
    () => pickActivePlayerCurrency(profile, currencies, selectedCurrency),
    [currencies, profile, selectedCurrency],
  );

  const canSwitchCurrency = bettableCurrencies.length > 1;

  const setActiveCurrency = useCallback(
    (code: string) => {
      setSelectedCurrency(code);
    },
    [setSelectedCurrency],
  );

  return {
    activeCurrency,
    bettableCurrencies,
    canSwitchCurrency,
    setActiveCurrency,
  };
}
