'use client'
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _tslib = require('../../../../../_virtual/_tslib.cjs');
var React = require('react');
require('@dynamic-labs-sdk/client/core');
require('@dynamic-labs/sdk-api-core');
require('../../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../../config/ApiEndpoint.cjs');
require('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
require('react/jsx-runtime');
require('../../../context/ViewContext/ViewContext.cjs');
var logger = require('../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('@dynamic-labs/utils');
require('../../constants/colors.cjs');
require('../../constants/values.cjs');
require('../../../shared/consts/index.cjs');
var errors = require('../../constants/errors.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../store/state/nonce/nonce.cjs');
var utils = require('../../../data/api/utils.cjs');
require('@dynamic-labs/locale');
require('../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../../events/dynamicEvents.cjs');
var getUserProfile = require('../../../client/extension/user/getUserProfile/getUserProfile.cjs');
var getProjectSettings = require('../../../client/extension/projectSettings/getProjectSettings/getProjectSettings.cjs');
var authMode = require('../../../store/state/authMode/authMode.cjs');
var multichainBalances = require('../../../store/state/multichainBalances.cjs');
var useGetMultichainTokenBalances = require('../useGetMultichainTokenBalances/useGetMultichainTokenBalances.cjs');

// Hook to fetch multichain token balances with caching to reduce re-querying
const useMultichainTokenBalances = (props) => {
    const { requests, forceRefresh = false, filterSpamTokens = true } = props;
    const multichainTokenBalancesState = multichainBalances.useMultichainTokenBalancesState();
    const getMultichainTokenBalances = useGetMultichainTokenBalances.useGetMultichainTokenBalances();
    const { multichainTokenBalances, isLoading, error, requestsKey } = multichainTokenBalancesState;
    // Create a stable key for the current request to avoid unnecessary re-fetching
    const currentRequestsKey = React.useMemo(() => {
        if (!requests || requests.length === 0)
            return '';
        return JSON.stringify(requests
            .map(({ chain, address, networkIds }) => ({
            address,
            chain,
            networkIds: [...networkIds].sort((a, b) => a - b),
        }))
            .sort((a, b) => a.address.localeCompare(b.address)));
    }, [requests]);
    // Helper function to check if user is authorized to fetch balances
    const checkAuthorization = React.useCallback(() => {
        var _a;
        const user = getUserProfile.getUserProfile();
        const authMode$1 = authMode.getAuthMode();
        if (authMode$1 !== 'connect-only' && !user) {
            multichainBalances.setMultichainTokenBalanceVariable('error', errors.USER_NOT_LOGGED_IN);
            return false;
        }
        const projectSettings = getProjectSettings.getProjectSettings();
        if (authMode$1 === 'connect-only' &&
            !((_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.featureFlags) === null || _a === void 0 ? void 0 : _a.connectOnlyMultiAsset)) {
            return false;
        }
        return true;
    }, []);
    // Helper function to check if we can use cached data
    const canUseCachedData = React.useCallback((shouldForceRefresh) => !shouldForceRefresh &&
        !forceRefresh &&
        requestsKey === currentRequestsKey &&
        Boolean(multichainTokenBalances) &&
        !isLoading, [
        forceRefresh,
        requestsKey,
        currentRequestsKey,
        multichainTokenBalances,
        isLoading,
    ]);
    // Helper function to validate requests
    const validateRequests = React.useCallback(() => {
        if (!requests || requests.length === 0) {
            multichainBalances.setMultichainTokenBalanceVariable('multichainTokenBalances', undefined);
            multichainBalances.setMultichainTokenBalanceVariable('requestsKey', undefined);
            return false;
        }
        const isValidRequest = requests.every((request) => request.address &&
            request.chain &&
            request.networkIds &&
            request.networkIds.length > 0);
        if (isLoading || !isValidRequest) {
            multichainBalances.setMultichainTokenBalanceVariable('multichainTokenBalances', undefined);
            multichainBalances.setMultichainTokenBalanceVariable('requestsKey', undefined);
            return false;
        }
        return true;
    }, [requests, isLoading]);
    // Helper function to get error message from exception
    const getErrorMessage = React.useCallback((error) => {
        if ((error === null || error === void 0 ? void 0 : error.code) === 429) {
            return 'Too many requests fetching multichain balances';
        }
        if (error === null || error === void 0 ? void 0 : error.message) {
            return error.message;
        }
        return 'error fetching multichain token balances';
    }, []);
    const fetchMultichainBalances = React.useCallback((...args_1) => _tslib.__awaiter(void 0, [...args_1], void 0, function* (shouldForceRefresh = false) {
        // Check authorization
        if (!checkAuthorization()) {
            return;
        }
        // Check if we can use cached data
        if (canUseCachedData(shouldForceRefresh)) {
            logger.logger.logVerboseTroubleshootingMessage('[useMultichainTokenBalances] using cached data', { currentRequestsKey, requestsKey });
            return;
        }
        // Validate requests
        if (!validateRequests()) {
            return;
        }
        logger.logger.logVerboseTroubleshootingMessage('[useMultichainTokenBalances] will try to fetch multichain token balances', { isLoading, requests });
        multichainBalances.setMultichainTokenBalanceVariable('isLoading', true);
        try {
            const response = yield getMultichainTokenBalances({
                balanceRequests: requests,
                filterSpamTokens,
            });
            if (!response) {
                multichainBalances.setMultichainTokenBalanceVariable('error', 'No multichain token balances found');
                return;
            }
            multichainBalances.setMultichainTokenBalanceVariable('error', undefined);
            multichainBalances.setMultichainTokenBalanceVariable('multichainTokenBalances', response);
            multichainBalances.setMultichainTokenBalanceVariable('requestsKey', currentRequestsKey);
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
        }
        catch (e) {
            const logLevel = (e === null || e === void 0 ? void 0 : e.code) >= 500 || (e === null || e === void 0 ? void 0 : e.code) < 400 ? 'error' : 'warn';
            yield utils.logResponseError(e, 'Error getting multichain token balances', logLevel);
            const errorMessage = getErrorMessage(e);
            multichainBalances.setMultichainTokenBalanceVariable('error', errorMessage);
        }
        finally {
            multichainBalances.setMultichainTokenBalanceVariable('isLoading', false);
        }
    }), [
        checkAuthorization,
        canUseCachedData,
        validateRequests,
        getErrorMessage,
        getMultichainTokenBalances,
        requests,
        currentRequestsKey,
        requestsKey,
        isLoading,
    ]);
    // Only fetch when the requests key changes to prevent unnecessary re-fetching
    React.useEffect(() => {
        if (currentRequestsKey && requestsKey !== currentRequestsKey) {
            fetchMultichainBalances();
        }
        // Removed fetchMultichainBalances from the dependency array to prevent unnecessary re-fetching (infinite loop)
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [currentRequestsKey, requestsKey]);
    return {
        error,
        fetchMultichainBalances,
        isError: Boolean(error),
        isLoading,
        multichainTokenBalances,
    };
};

exports.useMultichainTokenBalances = useMultichainTokenBalances;
