"use client";

import { useState } from "react";

import { useSocketEvent } from "@/hooks/socket/useSocketEvent";

import { useUserBalance } from "./useUserBalance";

export const useBalance = () => {
  const [socketBalance, setSocketBalance] = useState<number | null>(null);

  // Получаем начальный баланс через API
  const { balance: apiBalance, isLoading } = useUserBalance();

  // Слушаем обновления баланса через WebSocket
  useSocketEvent("balance_updated", b => {
    setSocketBalance(b.data.balance);
  });

  // Приоритет: WebSocket > API > 0
  const currentBalance = socketBalance ?? apiBalance ?? 0;

  return {
    balance: currentBalance,
    isLoading,
  };
};
