'use client'
'use strict';

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

var _tslib = require('../../../../../../_virtual/_tslib.cjs');
var jsxRuntime = require('react/jsx-runtime');
var React = require('react');
var reactI18next = require('react-i18next');
require('../../../../context/DynamicContext/DynamicContext.cjs');
require('../../../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
var chevronDown = require('../../../../shared/assets/chevron-down.cjs');
require('../../../../context/ViewContext/ViewContext.cjs');
require('../../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('@dynamic-labs/utils');
require('../../../../utils/constants/colors.cjs');
require('../../../../utils/constants/values.cjs');
require('@dynamic-labs/sdk-api-core');
require('../../../../shared/consts/index.cjs');
require('../../../../events/dynamicEvents.cjs');
require('../../../../context/CaptchaContext/CaptchaContext.cjs');
require('../../../../context/ErrorContext/ErrorContext.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../../store/state/nonce/nonce.cjs');
require('@dynamic-labs-sdk/client/core');
require('../../../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../../../config/ApiEndpoint.cjs');
var useProjectSettings = require('../../../../client/extension/projectSettings/useProjectSettings/useProjectSettings.cjs');
require('@dynamic-labs/locale');
require('../../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../../../context/AccessDeniedContext/AccessDeniedContext.cjs');
require('../../../../context/AccountExistsContext/AccountExistsContext.cjs');
require('../../../../context/UserWalletsContext/UserWalletsContext.cjs');
var authMode = require('../../../../store/state/authMode/authMode.cjs');
require('../../../../context/VerificationContext/VerificationContext.cjs');
require('react-dom');
require('../../../../utils/functions/compareChains/compareChains.cjs');
require('../../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('../../../../context/ThemeContext/ThemeContext.cjs');
require('../../../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
require('bs58');
var usePromise = require('../../../../utils/hooks/usePromise/usePromise.cjs');
require('@dynamic-labs/types');
require('../../../../context/SocialRedirectContext/SocialRedirectContext.cjs');
require('../../../../context/LoadingContext/LoadingContext.cjs');
require('../../../../context/WalletContext/WalletContext.cjs');
require('../../../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.cjs');
require('yup');
require('../../../../context/MockContext/MockContext.cjs');
require('../../../../views/CollectUserDataView/useFields.cjs');
require('../../../../context/FieldsStateContext/FieldsStateContext.cjs');
require('../../../../context/UserFieldEditorContext/UserFieldEditorContext.cjs');
require('@dynamic-labs/rpc-providers');
require('../../../../store/state/walletOptions/walletOptions.cjs');
var AccordionItem = require('../../../../components/Accordion/components/AccordionItem/AccordionItem.cjs');
require('../../../../components/Alert/Alert.cjs');
var Typography = require('../../../../components/Typography/Typography.cjs');
require('../../../../components/ShadowDOM/ShadowDOM.cjs');
require('../../../../components/IconButton/IconButton.cjs');
require('../../../../components/InlineWidget/InlineWidget.cjs');
require('../../../../components/Input/Input.cjs');
require('../../../../components/IsBrowser/IsBrowser.cjs');
require('../../../../components/MenuList/Dropdown/Dropdown.cjs');
require('../../../../components/OverlayCard/OverlayCard.cjs');
require('../../../../components/Transition/ZoomTransition/ZoomTransition.cjs');
require('../../../../components/Transition/SlideInUpTransition/SlideInUpTransition.cjs');
require('../../../../components/Transition/OpacityTransition/OpacityTransition.cjs');
require('../../../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.cjs');
require('../../../../components/Popper/Popper/Popper.cjs');
require('../../../../components/Popper/PopperContext/PopperContext.cjs');
require('react-focus-lock');
require('qrcode');
require('formik');
require('../../../../utils/hooks/useSubdomainCheck/useSubdomainCheck.cjs');
var Skeleton = require('../../../../components/Skeleton/Skeleton.cjs');
require('../../../../context/WalletGroupContext/WalletGroupContext.cjs');
require('../../../../context/IpConfigurationContext/IpConfigurationContext.cjs');
require('../../../../context/ConnectWithOtpContext/ConnectWithOtpContext.cjs');
require('../../../DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.cjs');
var Balance = require('../Balance/Balance.cjs');
require('@hcaptcha/react-hcaptcha');
require('../../context/DynamicWidgetContext.cjs');
require('../../helpers/convertExchangeKeyAndProviderEnum.cjs');
require('../../../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.cjs');
require('../../../../context/ErrorContext/hooks/useErrorText/useErrorText.cjs');
require('../../../../context/FooterAnimationContext/index.cjs');
require('../../../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.cjs');
require('../../../../context/PasskeyContext/PasskeyContext.cjs');
require('../../../../context/OnrampContext/OnrampContext.cjs');
require('../../../../store/state/sendBalances.cjs');
require('../../../../store/state/connectorsInitializing/connectorsInitializing.cjs');
require('../../../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.cjs');
require('../DynamicWidgetHeader/DynamicWidgetHeader.cjs');
require('../../../../views/TransactionConfirmationView/TransactionConfirmationView.cjs');
require('../PasskeyCard/PasskeyCard.cjs');
require('../../views/CryptoComOnramp/CryptoComOnramp.cjs');
require('../../../../../index.cjs');
require('../../views/ReceiveWalletFunds/ReceiveWalletFunds.cjs');
var useTokenBalances = require('../../../../utils/hooks/useTokenBalances/useTokenBalances.cjs');
require('../../../../store/state/multichainBalances.cjs');
require('../../../../shared/utils/functions/getInitialUrl/getInitialUrl.cjs');
var useInternalDynamicContext = require('../../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');
var TokenBalanceList = require('./TokenBalanceList/TokenBalanceList.cjs');

/** Component to display token balances for the primary wallet */
const ActiveWalletBalance = ({ isLoading = false, }) => {
    var _a;
    const { t } = reactI18next.useTranslation();
    /** Controls for the multi asset balance accordion */
    const [balanceIsExpanded, setBalanceIsExpanded] = React.useState(false);
    /** Controls for the shadow on scroll of the multi asset balance section */
    const [hasShadow, setHasShadow] = React.useState(false);
    const contentRef = React.useRef(null);
    const { primaryWallet, network, showFiat, multiAsset } = useInternalDynamicContext.useInternalDynamicContext();
    const authMode$1 = authMode.useAuthMode();
    const projectSettings = useProjectSettings.useProjectSettings();
    const { data: testnet } = usePromise.usePromise(() => _tslib.__awaiter(void 0, void 0, void 0, function* () { return Boolean(yield (primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector.isTestnet())); }), { deps: [network], initialData: false });
    const { isLoading: isLoadingTokenBalances, tokenBalances, error: errorTokenBalances, } = useTokenBalances.useTokenBalances({
        chainName: primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector.connectedChain,
        includeFiat: showFiat,
        includeNativeBalance: true,
    });
    const filteredTokenBalances = React.useMemo(() => (tokenBalances === null || tokenBalances === void 0 ? void 0 : tokenBalances.filter((token) => token.name)) || [], [tokenBalances]);
    const totalValue = React.useMemo(() => filteredTokenBalances.reduce((acc, token) => acc + ((token === null || token === void 0 ? void 0 : token.marketValue) || 0), 0), [filteredTokenBalances]);
    const enableMultiAsset = React.useMemo(() => {
        var _a;
        return (authMode$1 === 'connect-and-sign' ||
            (authMode$1 === 'connect-only' &&
                ((_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.featureFlags) === null || _a === void 0 ? void 0 : _a.connectOnlyMultiAsset))) &&
            multiAsset;
    }, [
        authMode$1,
        (_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.featureFlags) === null || _a === void 0 ? void 0 : _a.connectOnlyMultiAsset,
        multiAsset,
    ]);
    const isTooManyRequests = errorTokenBalances === 'Too many requests fetching balances';
    const showMultiAsset = !isTooManyRequests && enableMultiAsset;
    const currencyFormatter = new Intl.NumberFormat('en-US', {
        currency: 'USD',
        style: 'currency',
    });
    const canShowFiat = React.useMemo(() => !testnet && showFiat && showMultiAsset && !errorTokenBalances, [testnet, showFiat, showMultiAsset, errorTokenBalances]);
    const handleScroll = () => {
        if (contentRef.current) {
            setHasShadow(contentRef.current.scrollTop > 0);
        }
    };
    const primaryWalletNativeBalance = () => {
        if (!primaryWallet || isLoadingTokenBalances || isLoading) {
            return jsxRuntime.jsx(Skeleton.Skeleton, { className: 'balance-container__skeleton' });
        }
        return canShowFiat ? (jsxRuntime.jsx(Typography.Typography, { variant: 'numbers_display', color: 'primary', children: totalValue === 0 || totalValue >= 0.01
                ? currencyFormatter.format(parseFloat(totalValue.toFixed(2)))
                : '<$0.01' })) : (jsxRuntime.jsx(Balance.Balance, { className: 'balance-header__balance', wallet: primaryWallet, network: network, variant: 'numbers_display' }));
    };
    const balanceHeaderTitle = () => (jsxRuntime.jsxs("div", { className: 'balance-header__title', children: [isLoadingTokenBalances || isLoading ? (jsxRuntime.jsx(Skeleton.Skeleton, { className: 'balance-header__title-skeleton' })) : (jsxRuntime.jsx(Typography.Typography, { color: 'secondary', variant: 'body_normal', copykey: 'dyn_active_wallet_info.balance', children: t('dyn_active_wallet_info.balance') })), jsxRuntime.jsx("div", { className: 'balance-header__balance', children: primaryWalletNativeBalance() })] }));
    const toggleBalanceAccordion = React.useCallback(() => {
        if (!isLoadingTokenBalances) {
            setBalanceIsExpanded(!balanceIsExpanded);
        }
    }, [isLoadingTokenBalances, balanceIsExpanded]);
    if (!showMultiAsset) {
        return jsxRuntime.jsx("div", { className: 'balance-container', children: balanceHeaderTitle() });
    }
    return (jsxRuntime.jsx("div", { className: 'balance-container', children: jsxRuntime.jsxs("div", { className: 'multi-asset-balance-container', children: [jsxRuntime.jsx("div", { className: `${hasShadow ? 'shadow' : ''}`, children: jsxRuntime.jsxs("button", { onClick: toggleBalanceAccordion, className: 'balance-header', "data-testid": 'balance-header', children: [balanceHeaderTitle(), !isLoadingTokenBalances && (jsxRuntime.jsx("div", { className: balanceIsExpanded ? 'balance-header__chevron' : '', children: jsxRuntime.jsx(chevronDown.ReactComponent, {}) }))] }) }), jsxRuntime.jsx(AccordionItem.AccordionItem, { isOpen: balanceIsExpanded, className: `multi-asset-balance-container__accordion ${'multi-asset-balance-container__accordion' +
                        (balanceIsExpanded ? '--expanded' : '--collapsed')}`, handleScroll: handleScroll, ref: contentRef, dataTestId: 'multi-asset-balance-accordion', children: jsxRuntime.jsx(TokenBalanceList.TokenBalanceList, { tokenBalances: filteredTokenBalances }) })] }) }));
};

exports.ActiveWalletBalance = ActiveWalletBalance;
