'use client'
import { __awaiter } from '../../../../../../_virtual/_tslib.js';
import { jsx, jsxs } from 'react/jsx-runtime';
import { useState, useRef, useMemo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import '../../../../context/DynamicContext/DynamicContext.js';
import '../../../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import { ReactComponent as SvgCheck } from '../../../../shared/assets/check.js';
import { ReactComponent as SvgChevronDown } from '../../../../shared/assets/chevron-down.js';
import '../../../../context/ViewContext/ViewContext.js';
import { ReactComponent as SvgReloadIcon } from '../../../../shared/assets/reload-icon.js';
import '../../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '@dynamic-labs/utils';
import '../../../../utils/constants/colors.js';
import '../../../../utils/constants/values.js';
import '@dynamic-labs/sdk-api-core';
import '../../../../shared/consts/index.js';
import '../../../../events/dynamicEvents.js';
import '../../../../context/CaptchaContext/CaptchaContext.js';
import '../../../../context/ErrorContext/ErrorContext.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../../../store/state/nonce/nonce.js';
import '@dynamic-labs-sdk/client/core';
import '../../../../client/client.js';
import '@dynamic-labs-sdk/client';
import '../../../../config/ApiEndpoint.js';
import { useProjectSettings } from '../../../../client/extension/projectSettings/useProjectSettings/useProjectSettings.js';
import '@dynamic-labs/locale';
import '../../../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../../../store/state/primaryWalletId/primaryWalletId.js';
import '../../../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../../../../context/AccessDeniedContext/AccessDeniedContext.js';
import '../../../../context/AccountExistsContext/AccountExistsContext.js';
import '../../../../context/UserWalletsContext/UserWalletsContext.js';
import { useAuthMode } from '../../../../store/state/authMode/authMode.js';
import '../../../../context/VerificationContext/VerificationContext.js';
import 'react-dom';
import '../../../../utils/functions/compareChains/compareChains.js';
import '../../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import '../../../../context/ThemeContext/ThemeContext.js';
import '../../../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.js';
import 'bs58';
import { usePromise } from '../../../../utils/hooks/usePromise/usePromise.js';
import '@dynamic-labs/types';
import '../../../../context/SocialRedirectContext/SocialRedirectContext.js';
import '../../../../context/LoadingContext/LoadingContext.js';
import '../../../../context/WalletContext/WalletContext.js';
import '../../../../utils/hooks/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 { AccordionItem } from '../../../../components/Accordion/components/AccordionItem/AccordionItem.js';
import '../../../../components/Alert/Alert.js';
import { Typography } from '../../../../components/Typography/Typography.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 '../../../../utils/hooks/useSubdomainCheck/useSubdomainCheck.js';
import { Skeleton } from '../../../../components/Skeleton/Skeleton.js';
import '../../../../context/WalletGroupContext/WalletGroupContext.js';
import '../../../../context/IpConfigurationContext/IpConfigurationContext.js';
import '../../../../context/ConnectWithOtpContext/ConnectWithOtpContext.js';
import '../../../DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.js';
import { Balance } from '../Balance/Balance.js';
import '@hcaptcha/react-hcaptcha';
import '../../context/DynamicWidgetContext.js';
import '../../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 '../DynamicWidgetHeader/DynamicWidgetHeader.js';
import '../../../../views/TransactionConfirmationView/TransactionConfirmationView.js';
import '../PasskeyCard/PasskeyCard.js';
import '../../views/CryptoComOnramp/CryptoComOnramp.js';
import '../../../../../index.js';
import '../../views/ReceiveWalletFunds/ReceiveWalletFunds.js';
import { useTokenBalances } from '../../../../utils/hooks/useTokenBalances/useTokenBalances.js';
import '../../../../store/state/multichainBalances.js';
import '../../../../shared/utils/functions/getInitialUrl/getInitialUrl.js';
import { useInternalDynamicContext } from '../../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import { TokenBalanceList } from './TokenBalanceList/TokenBalanceList.js';

/** Component to display token balances for the primary wallet */
const ActiveWalletBalance = ({ isLoading = false, }) => {
    var _a;
    const { t } = useTranslation();
    /** Controls for the multi asset balance accordion */
    const [balanceIsExpanded, setBalanceIsExpanded] = useState(false);
    /** Controls for the shadow on scroll of the multi asset balance section */
    const [hasShadow, setHasShadow] = useState(false);
    const [isRefreshing, setIsRefreshing] = useState(false);
    const [isSuccess, setIsSuccess] = useState(false);
    const contentRef = useRef(null);
    const successTimeoutRef = useRef(null);
    const refreshTimeoutRef = useRef(null);
    const { primaryWallet, network, showFiat, multiAsset } = useInternalDynamicContext();
    const authMode = useAuthMode();
    const projectSettings = useProjectSettings();
    const { data: testnet } = usePromise(() => __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, fetchAccountBalances, } = useTokenBalances({
        chainName: primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector.connectedChain,
        includeFiat: showFiat,
        includeNativeBalance: true,
    });
    const filteredTokenBalances = useMemo(() => (tokenBalances === null || tokenBalances === void 0 ? void 0 : tokenBalances.filter((token) => token.name)) || [], [tokenBalances]);
    const totalValue = useMemo(() => filteredTokenBalances.reduce((acc, token) => acc + ((token === null || token === void 0 ? void 0 : token.marketValue) || 0), 0), [filteredTokenBalances]);
    const enableMultiAsset = useMemo(() => {
        var _a;
        return (authMode === 'connect-and-sign' ||
            (authMode === 'connect-only' &&
                ((_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.featureFlags) === null || _a === void 0 ? void 0 : _a.connectOnlyMultiAsset))) &&
            multiAsset;
    }, [
        authMode,
        (_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 = useMemo(() => !testnet && showFiat && showMultiAsset && !errorTokenBalances, [testnet, showFiat, showMultiAsset, errorTokenBalances]);
    const handleScroll = () => {
        if (contentRef.current) {
            setHasShadow(contentRef.current.scrollTop > 0);
        }
    };
    const handleRefresh = useCallback((event) => __awaiter(void 0, void 0, void 0, function* () {
        event.stopPropagation();
        if (isRefreshing || isSuccess)
            return;
        // Clear any existing timeouts
        if (successTimeoutRef.current) {
            clearTimeout(successTimeoutRef.current);
            successTimeoutRef.current = null;
        }
        if (refreshTimeoutRef.current) {
            clearTimeout(refreshTimeoutRef.current);
            refreshTimeoutRef.current = null;
        }
        setIsRefreshing(true);
        setIsSuccess(false);
        try {
            yield fetchAccountBalances(true);
            setIsRefreshing(false);
            setIsSuccess(true);
            successTimeoutRef.current = setTimeout(() => {
                setIsSuccess(false);
                successTimeoutRef.current = null;
            }, 5000);
        }
        catch (error) {
            refreshTimeoutRef.current = setTimeout(() => {
                setIsRefreshing(false);
                refreshTimeoutRef.current = null;
            }, 1000);
        }
    }), [isRefreshing, isSuccess, fetchAccountBalances]);
    const primaryWalletNativeBalance = () => {
        if (!primaryWallet || isLoadingTokenBalances || isLoading) {
            return jsx(Skeleton, { className: 'balance-container__skeleton' });
        }
        return canShowFiat ? (jsx(Typography, { variant: 'numbers_display', color: 'primary', children: totalValue === 0 || totalValue >= 0.01
                ? currencyFormatter.format(parseFloat(totalValue.toFixed(2)))
                : '<$0.01' })) : (jsx(Balance, { className: 'balance-header__balance', wallet: primaryWallet, network: network, variant: 'numbers_display' }));
    };
    const balanceHeaderTitle = () => (jsxs("div", { className: 'balance-header__title', children: [isLoadingTokenBalances || isLoading ? (jsx(Skeleton, { className: 'balance-header__title-skeleton' })) : (jsx(Typography, { color: 'secondary', variant: 'body_normal', copykey: 'dyn_active_wallet_info.balance', children: t('dyn_active_wallet_info.balance') })), jsxs("div", { className: 'balance-header__balance', children: [primaryWalletNativeBalance(), isSuccess ? (jsx("div", { className: 'balance-header__success-icon', children: jsx(SvgCheck, { "data-testid": 'success-icon' }) })) : (jsx(SvgReloadIcon, { "data-testid": 'refresh-balances', className: `balance-header__refresh-icon ${isRefreshing ? 'balance-header__refresh-icon--spinning' : ''}`, onClick: handleRefresh, style: {
                            cursor: isRefreshing ? 'not-allowed' : 'pointer',
                            opacity: isRefreshing ? 0.5 : 1,
                        }, title: 'Refresh balances' }))] })] }));
    const toggleBalanceAccordion = useCallback(() => {
        if (!isLoadingTokenBalances) {
            setBalanceIsExpanded(!balanceIsExpanded);
        }
    }, [isLoadingTokenBalances, balanceIsExpanded]);
    if (!showMultiAsset) {
        return jsx("div", { className: 'balance-container', children: balanceHeaderTitle() });
    }
    return (jsx("div", { className: 'balance-container', children: jsxs("div", { className: 'multi-asset-balance-container', children: [jsx("div", { className: `${hasShadow ? 'shadow' : ''}`, children: jsxs("button", { onClick: toggleBalanceAccordion, className: 'balance-header', "data-testid": 'balance-header', children: [balanceHeaderTitle(), !isLoadingTokenBalances && (jsx("div", { className: balanceIsExpanded ? 'balance-header__chevron' : '', children: jsx(SvgChevronDown, {}) }))] }) }), jsx(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: jsx(TokenBalanceList, { tokenBalances: filteredTokenBalances }) })] }) }));
};

export { ActiveWalletBalance };
