"use client";
import {
  logger
} from "./chunk-UUHGOBKZ.js";

// src/clients/polymarket/usePolymarketAccountBalances.ts
import {
  skipToken,
  useQuery,
  useQueryClient
} from "@tanstack/react-query";
import * as dnum from "dnum";
var DEFAULT_BALANCE_REFETCH_MS = 1e3;
var polymarketAccountBalanceQueryKey = (address) => ["polymarket", "accountBalanceUsd", address ?? null];
var polymarketBalanceSettleUntilQueryKey = (address) => ["polymarket", "accountBalanceSettleUntil", address];
var PUSD_DECIMALS = 6;
var SETTLEMENT_WINDOW_MS = 3e4;
function applyOptimisticTransferBalances(queryClient, transfer) {
  const { fromAddress, toAddress, amountUsd } = transfer;
  const amount = dnum.from(amountUsd, PUSD_DECIMALS);
  shiftBalance(queryClient, fromAddress, dnum.multiply(amount, -1));
  shiftBalance(queryClient, toAddress, amount);
}
function shiftBalance(queryClient, address, deltaUsd) {
  const balanceKey = polymarketAccountBalanceQueryKey(address);
  const displayedUsd = queryClient.getQueryData(balanceKey);
  if (displayedUsd === void 0) {
    return;
  }
  void queryClient.cancelQueries({ queryKey: balanceKey });
  queryClient.setQueryData(
    polymarketBalanceSettleUntilQueryKey(address),
    Date.now() + SETTLEMENT_WINDOW_MS
  );
  queryClient.setQueryData(
    balanceKey,
    Math.max(0, dnum.toNumber(dnum.add(displayedUsd, deltaUsd, PUSD_DECIMALS)))
  );
}
async function fetchAccountBalance(queryClient, getBalanceUsd, queryKey) {
  const [, , address] = queryKey;
  if (address === null) {
    throw new Error("polymarket balance query ran without an address");
  }
  try {
    const serverUsd = await getBalanceUsd();
    const settleUntil = queryClient.getQueryData(
      polymarketBalanceSettleUntilQueryKey(address)
    );
    const displayedUsd = queryClient.getQueryData(
      polymarketAccountBalanceQueryKey(address)
    );
    if (settleUntil !== void 0 && Date.now() < settleUntil && displayedUsd !== void 0) {
      return displayedUsd;
    }
    return serverUsd;
  } catch (error) {
    logger.warn("polymarket:accountBalance:fetchFailed", {
      address,
      error: String(error)
    });
    throw error;
  }
}
function useAccountBalance(account, refetchIntervalMs) {
  const queryClient = useQueryClient();
  const getBalanceUsd = account?.getBalanceUsd;
  const address = account?.address;
  const query = useQuery({
    queryKey: polymarketAccountBalanceQueryKey(address),
    // `skipToken` disables the query when the account isn't configured (the
    // perps-transfer config is optional). It is *not* a fallback for a missing
    // balance — the getter is the single source of truth.
    queryFn: getBalanceUsd && address ? ({ queryKey }) => fetchAccountBalance(queryClient, getBalanceUsd, queryKey) : skipToken,
    refetchInterval: refetchIntervalMs,
    // The poll interval is the freshness contract: a reader mounting within it
    // (e.g. navigating between the deposit picker and the transfer step) reads
    // the cached balance as-is instead of kicking off an extra mount fetch —
    // that's what makes the navigation flash-free *and* fetch-free.
    staleTime: refetchIntervalMs
  });
  return { balanceUsd: query.data };
}
function usePolymarketAccountBalances(accounts, options) {
  const refetchIntervalMs = options?.refetchIntervalMs ?? DEFAULT_BALANCE_REFETCH_MS;
  return {
    predictions: useAccountBalance(accounts.predictions, refetchIntervalMs),
    perps: useAccountBalance(accounts.perps, refetchIntervalMs)
  };
}

export {
  polymarketAccountBalanceQueryKey,
  applyOptimisticTransferBalances,
  usePolymarketAccountBalances
};
