'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { useCallback, useEffect, useMemo } from 'react';
import { ChainEnum } from '@dynamic-labs/sdk-api-core';
import '@dynamic-labs-sdk/client/core';
import '../../../client/client.js';
import '@dynamic-labs-sdk/client';
import '../../../config/ApiEndpoint.js';
import '../../constants/values.js';
import '@dynamic-labs/utils';
import { USER_NOT_LOGGED_IN } from '../../constants/errors.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../constants/colors.js';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import 'react/jsx-runtime';
import '../../../context/ViewContext/ViewContext.js';
import { logger } from '../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '../../../shared/consts/index.js';
import '../../../store/state/nonce/nonce.js';
import { logResponseError } from '../../../data/api/utils.js';
import '@dynamic-labs/locale';
import { useDynamicSettings, getEnvironmentId } from '../../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../../store/state/primaryWalletId/primaryWalletId.js';
import '../../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../../../events/dynamicEvents.js';
import { getUserProfile } from '../../../client/extension/user/getUserProfile/getUserProfile.js';
import { getProjectSettings } from '../../../client/extension/projectSettings/getProjectSettings/getProjectSettings.js';
import '../../../context/DynamicContext/DynamicContext.js';
import '../../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import { useInternalDynamicEvents } from '../events/useDynamicEvents/useDynamicEvents.js';
import '../../../context/CaptchaContext/CaptchaContext.js';
import '../../../context/ErrorContext/ErrorContext.js';
import '../../../context/AccessDeniedContext/AccessDeniedContext.js';
import '../../../context/AccountExistsContext/AccountExistsContext.js';
import '../../../context/UserWalletsContext/UserWalletsContext.js';
import { getAuthMode } from '../../../store/state/authMode/authMode.js';
import '../../../context/VerificationContext/VerificationContext.js';
import 'react-dom';
import '../../functions/compareChains/compareChains.js';
import '../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import '../../../context/ThemeContext/ThemeContext.js';
import '../useUserUpdateRequest/useUpdateUser/userFieldsSchema.js';
import 'bs58';
import '@dynamic-labs/types';
import '../../../context/SocialRedirectContext/SocialRedirectContext.js';
import '../../../context/LoadingContext/LoadingContext.js';
import '../../../context/WalletContext/WalletContext.js';
import '../useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.js';
import 'yup';
import '../../../context/MockContext/MockContext.js';
import '../../../views/CollectUserDataView/useFields.js';
import '../../../context/FieldsStateContext/FieldsStateContext.js';
import '../../../context/UserFieldEditorContext/UserFieldEditorContext.js';
import '@dynamic-labs/rpc-providers';
import '../../../store/state/walletOptions/walletOptions.js';
import 'react-i18next';
import '../../../components/Accordion/components/AccordionItem/AccordionItem.js';
import '../../../components/Alert/Alert.js';
import '../../../components/ShadowDOM/ShadowDOM.js';
import '../../../components/IconButton/IconButton.js';
import '../../../components/InlineWidget/InlineWidget.js';
import '../../../components/Input/Input.js';
import '../../../components/IsBrowser/IsBrowser.js';
import '../../../components/MenuList/Dropdown/Dropdown.js';
import '../../../components/OverlayCard/OverlayCard.js';
import '../../../components/Transition/ZoomTransition/ZoomTransition.js';
import '../../../components/Transition/SlideInUpTransition/SlideInUpTransition.js';
import '../../../components/Transition/OpacityTransition/OpacityTransition.js';
import '../../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.js';
import '../../../components/Popper/Popper/Popper.js';
import '../../../components/Popper/PopperContext/PopperContext.js';
import 'react-focus-lock';
import 'qrcode';
import 'formik';
import '../useSubdomainCheck/useSubdomainCheck.js';
import '../../../context/WalletGroupContext/WalletGroupContext.js';
import '../../../context/IpConfigurationContext/IpConfigurationContext.js';
import '../../../context/ConnectWithOtpContext/ConnectWithOtpContext.js';
import '../../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.js';
import '@hcaptcha/react-hcaptcha';
import '../../../widgets/DynamicWidget/context/DynamicWidgetContext.js';
import '../../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.js';
import '../../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.js';
import '../../../context/ErrorContext/hooks/useErrorText/useErrorText.js';
import '../../../context/FooterAnimationContext/index.js';
import '../../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.js';
import '../../../context/PasskeyContext/PasskeyContext.js';
import '../../../context/OnrampContext/OnrampContext.js';
import '../../../store/state/sendBalances.js';
import '../../../store/state/connectorsInitializing/connectorsInitializing.js';
import '../../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.js';
import '../../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.js';
import '../../../views/TransactionConfirmationView/TransactionConfirmationView.js';
import '../../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.js';
import '../../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.js';
import '../../../../index.js';
import '../../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.js';
import { getAccountTokenBalances } from '../../../data/api/chains/balances.js';
import { useTokenBalancesState, setTokenBalanceVariable } from '../../../store/state/tokenBalances.js';
import '../../../store/state/multichainBalances.js';
import '../../../shared/utils/functions/getInitialUrl/getInitialUrl.js';
import { useInternalDynamicContext } from '../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';

// Hook exposed to customers and used internally to fetch account balances
const useTokenBalances = ({ accountAddress, networkId, chainName, tokenAddresses, includeFiat = false, includeNativeBalance = false, filterSpamTokens = true, forceRefresh = false, whitelistedContracts, } = {}) => {
    var _a;
    const tokenBalancesState = useTokenBalancesState();
    const { tokenBalances, isLoading, error } = tokenBalancesState;
    const { primaryWallet, network } = useInternalDynamicContext();
    const walletConnector = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector;
    const requestAccount = accountAddress !== null && accountAddress !== void 0 ? accountAddress : primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.address;
    const requestChainName = (_a = chainName !== null && chainName !== void 0 ? chainName : walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.connectedChain) !== null && _a !== void 0 ? _a : ChainEnum.Evm;
    const fetchAccountBalances = useCallback((...args_1) => __awaiter(void 0, [...args_1], void 0, function* (forceRefresh = false) {
        var _b;
        const user = getUserProfile();
        const authMode = getAuthMode();
        if (authMode !== 'connect-only' && !user) {
            setTokenBalanceVariable('error', USER_NOT_LOGGED_IN);
            return;
        }
        const projectSettings = getProjectSettings();
        if (authMode === 'connect-only' &&
            !((_b = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.featureFlags) === null || _b === void 0 ? void 0 : _b.connectOnlyMultiAsset)) {
            return;
        }
        // the reason why we need to get the network here again insteaf of using the value
        // from DynamicContext is because this function might run before the network state is
        // properly set when switching wallets, so we want to make sure we have the latest network
        let requestNetwork = networkId !== null && networkId !== void 0 ? networkId : (yield (walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.getNetwork(true)));
        if (requestChainName === ChainEnum.Btc) {
            // Bitcoin does not need a network ID to fetch token balances but the request requires a network ID
            requestNetwork = 1;
        }
        const isValidRequest = requestNetwork && !isNaN(Number(requestNetwork));
        logger.logVerboseTroubleshootingMessage('[useTokenBalances] will try to fetch token balances', {
            isLoading,
            isValidRequest,
            networkId,
            requestAccount,
            requestChainName,
            requestNetwork,
        });
        if (isLoading || !requestAccount || !isValidRequest) {
            setTokenBalanceVariable('tokenBalances', undefined);
            return;
        }
        setTokenBalanceVariable('isLoading', true);
        let response = [];
        try {
            response = yield getAccountTokenBalances({
                accountAddress: requestAccount,
                chainName: requestChainName,
                environmentId: getEnvironmentId(),
                filterSpamTokens,
                forceRefresh,
                includeNative: includeNativeBalance,
                includePrices: includeFiat,
                networkId: Number(requestNetwork),
                whitelistedContracts,
            });
            if (!response) {
                setTokenBalanceVariable('error', 'No token balances found');
                return;
            }
            setTokenBalanceVariable('error', undefined);
            // 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 logResponseError(e, 'Error getting token balances', logLevel);
            let errorMessage = '';
            if ((e === null || e === void 0 ? void 0 : e.code) === 429) {
                errorMessage = 'Too many requests fetching balances';
            }
            else if (e === null || e === void 0 ? void 0 : e.message) {
                errorMessage = e.message;
            }
            else {
                errorMessage = 'error fetching token balance';
            }
            setTokenBalanceVariable('error', errorMessage);
        }
        finally {
            // remove tokens with 0 balance.
            // This is needed because native tokens, unlike other tokens,
            // are returned in the response even if the balance is 0
            const filteredResponse = response === null || response === void 0 ? void 0 : response.filter((token) => token.balance !== 0);
            setTokenBalanceVariable('tokenBalances', filteredResponse);
            setTokenBalanceVariable('isLoading', false);
        }
    }), [
        requestChainName,
        isLoading,
        requestAccount,
        includeNativeBalance,
        includeFiat,
        filterSpamTokens,
        networkId,
        walletConnector,
    ]);
    useInternalDynamicEvents('tokenBalancesChanged', () => fetchAccountBalances(true));
    useEffect(() => {
        fetchAccountBalances(forceRefresh);
    }, [requestAccount, network, networkId, forceRefresh]);
    const { tokensFilter } = useDynamicSettings();
    const lowerTokenAddresses = useMemo(() => tokenAddresses === null || tokenAddresses === void 0 ? void 0 : tokenAddresses.map((address) => address.toLowerCase()), [tokenAddresses]);
    const initialTokenBalances = useMemo(() => lowerTokenAddresses
        ? tokenBalances === null || tokenBalances === void 0 ? void 0 : tokenBalances.filter((token) => lowerTokenAddresses === null || lowerTokenAddresses === void 0 ? void 0 : lowerTokenAddresses.includes(token.address.toLowerCase()))
        : tokenBalances, [lowerTokenAddresses, tokenBalances]);
    const filteredTokenBalances = useMemo(() => (initialTokenBalances ? tokensFilter(initialTokenBalances) : []), [initialTokenBalances, tokensFilter]);
    return {
        error,
        fetchAccountBalances,
        isError: Boolean(error),
        isLoading,
        tokenBalances: filteredTokenBalances,
    };
};

export { useTokenBalances };
