"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createUseRightBalanceAsset = void 0;
const react_1 = require("react");
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const sortByBalance_1 = require("../utils/sortByBalance");
const calculateProviderTotal_1 = require("../utils/calculateProviderTotal");
const groupAccountsByAsset_1 = require("../utils/groupAccountsByAsset");
function createUseRightBalanceAsset({ useBalanceDeps, balanceItem, assetsMap }) {
    const formatProviderResult = (providerCurrency, totalBalance, totalFiatValue) => {
        return {
            currency: providerCurrency,
            balance: totalBalance,
            fiatValue: totalFiatValue.toNumber(),
        };
    };
    return function useRightBalanceAsset(assets) {
        const { flattenedAccounts, state, counterValueCurrency } = useBalanceDeps();
        const grouped = (0, react_1.useMemo)(() => (0, groupAccountsByAsset_1.groupAccountsByAsset)(flattenedAccounts, state, counterValueCurrency), [flattenedAccounts, state, counterValueCurrency]);
        return (0, react_1.useMemo)(() => {
            const balanceMap = new Map();
            for (const [, { currencies, mainCurrency }] of assetsMap) {
                const { totalBalance, totalFiatValue, referenceCurrency } = (0, calculateProviderTotal_1.calculateProviderTotals)(currencies, grouped);
                // Use referenceCurrency from actual accounts if available, fallback to mainCurrency
                const currencyToUse = referenceCurrency || mainCurrency;
                const balanceData = formatProviderResult(currencyToUse, totalBalance, totalFiatValue);
                balanceMap.set(mainCurrency.id, balanceData);
            }
            const assetsWithBalanceData = assets.map(asset => {
                const balanceData = balanceMap.get(asset.id) || {
                    currency: asset,
                    balance: new bignumber_js_1.default(0),
                    fiatValue: 0,
                };
                return {
                    ...asset,
                    balanceData,
                    rightElement: balanceItem(balanceData),
                };
            });
            return assetsWithBalanceData.sort((a, b) => (0, sortByBalance_1.compareByBalanceThenFiat)(a.balanceData, b.balanceData));
        }, [assets, grouped]);
    };
}
exports.createUseRightBalanceAsset = createUseRightBalanceAsset;
//# sourceMappingURL=useRightBalanceAsset.js.map