'use client'
import { __awaiter } from '../../../../_virtual/_tslib.js';
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { useEffect } 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 SvgArrowLeft } from '../../shared/assets/arrow-left.js';
import { ReactComponent as SvgClose } from '../../shared/assets/close.js';
import '../../context/ViewContext/ViewContext.js';
import { logger } from '../../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 { getNetworkInfoEntry } from '../../utils/functions/networksAndChains/networksAndChains.js';
import '@dynamic-labs-sdk/client/core';
import '../../client/client.js';
import '@dynamic-labs-sdk/client';
import '../../config/ApiEndpoint.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 '../../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 '../Accordion/components/AccordionItem/AccordionItem.js';
import { Alert } from '../Alert/Alert.js';
import { AnimatePresence } from '../AnimatePresence/AnimatePresence.js';
import { Typography } from '../Typography/Typography.js';
import '../ShadowDOM/ShadowDOM.js';
import { IconButton } from '../IconButton/IconButton.js';
import '../InlineWidget/InlineWidget.js';
import '../Input/Input.js';
import '../IsBrowser/IsBrowser.js';
import '../MenuList/Dropdown/Dropdown.js';
import '../OverlayCard/OverlayCard.js';
import '../Transition/ZoomTransition/ZoomTransition.js';
import '../Transition/SlideInUpTransition/SlideInUpTransition.js';
import '../Transition/OpacityTransition/OpacityTransition.js';
import { VerticalDrawerTransition } from '../Transition/VerticalDrawerTransition/VerticalDrawerTransition.js';
import { ModalHeader } from '../ModalHeader/ModalHeader.js';
import '../PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.js';
import '../Popper/Popper/Popper.js';
import '../Popper/PopperContext/PopperContext.js';
import 'react-focus-lock';
import { PoweredByDynamic } from '../PoweredByDynamic/PoweredByDynamic.js';
import 'qrcode';
import { useFetchChain } from '../../widgets/DynamicWidget/hooks/useFetchChain/useFetchChain.js';
import 'formik';
import '../../utils/hooks/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 { SendBalanceForm } from '../SendBalanceForm/SendBalanceForm.js';
import { useNetworkConfigurationsFromProjectSettings } from '../../utils/hooks/useNetworkConfigurationsFromProjectSettings/useNetworkConfigurationsFromProjectSettings.js';
import { nativeSolanaAddress, zeroAddress } from './components/TokensBalanceDropdown/constants.js';
import '../../store/state/sendBalances.js';
import '../../store/state/connectorsInitializing/connectorsInitializing.js';
import '../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 '../../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';

const SendBalancePageLayout = ({ error, onClickClose, onClickBack, onSubmit, displayPoweredByDynamicFooter = false, transaction, networkCurrencyDecimals, tokenBalances, currentToken, setCurrentToken, isLoading, isNativeToken, }) => {
    var _a;
    const { t } = useTranslation();
    const { primaryWallet, projectSettings, overrides } = useInternalDynamicContext();
    const networkInfo = useNetworkConfigurationsFromProjectSettings({
        evmNetworksOverrides: overrides === null || overrides === void 0 ? void 0 : overrides.evmNetworks,
        projectSettings,
    });
    const walletConnector = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector;
    const { chain } = useFetchChain(walletConnector);
    const closeButton = onClickClose && (jsx(IconButton, { type: 'button', onClick: onClickClose, "data-testid": 'close-button', children: jsx(SvgClose, {}) }));
    const backButton = onClickBack && (jsx(IconButton, { type: 'button', onClick: onClickBack, "data-testid": 'back-button', children: jsx(SvgArrowLeft, {}) }));
    const { data: balance } = usePromise(() => transaction.getBalance(), {
        deps: [transaction],
    });
    useEffect(() => {
        const getNativeTokenAndFetchBalance = () => __awaiter(void 0, void 0, void 0, function* () {
            var _a;
            const nativeTokenInfo = getNetworkInfoEntry({
                chain: (_a = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector) === null || _a === void 0 ? void 0 : _a.connectedChain,
                networkId: chain === null || chain === void 0 ? void 0 : chain.chainId,
                networkInfo,
            });
            if (!nativeTokenInfo) {
                logger.error('Token info not found. Please make sure you are on a supported chain and it is enabled. See https://docs.dynamic.xyz/chains/enabling-chains');
                return;
            }
            const token = {
                address: (chain === null || chain === void 0 ? void 0 : chain.name) === 'Solana' ? nativeSolanaAddress : zeroAddress,
                balance: 0,
                decimals: nativeTokenInfo.nativeCurrency.decimals,
                isNative: true,
                logoURI: nativeTokenInfo.nativeCurrency.iconUrl || nativeTokenInfo.iconUrls[0],
                name: nativeTokenInfo.name,
                rawBalance: 0,
                symbol: nativeTokenInfo.nativeCurrency.symbol,
            };
            const tokenBalance = yield (primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.getBalance());
            if (tokenBalance) {
                token.balance = Number(tokenBalance);
                token.rawBalance = Number(tokenBalance) / Math.pow(10, token.decimals);
            }
            setCurrentToken(token);
        });
        const updateTokenBalances = () => __awaiter(void 0, void 0, void 0, function* () {
            if (isLoading)
                return;
            if (tokenBalances === undefined ||
                (Array.isArray(tokenBalances) && tokenBalances.length === 0)) {
                yield getNativeTokenAndFetchBalance();
            }
            else if (!currentToken) {
                setCurrentToken(tokenBalances[0]);
            }
        });
        updateTokenBalances();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [tokenBalances, chain]);
    const getAmount = () => {
        if (isNativeToken) {
            return transaction.value ? transaction.format(transaction.value) : '';
        }
        // Non-native token
        return (transaction === null || transaction === void 0 ? void 0 : transaction.formatNonNativeToken) &&
            (transaction === null || transaction === void 0 ? void 0 : transaction.nonNativeValue) &&
            (transaction === null || transaction === void 0 ? void 0 : transaction.nonNativeDecimal)
            ? transaction.formatNonNativeToken(transaction.nonNativeValue, transaction.nonNativeDecimal)
            : '';
    };
    return (jsxs(Fragment, { children: [jsx(ModalHeader, { leading: backButton, trailing: closeButton, alignContent: 'bottom', children: jsx("div", { className: 'send-balance-page-layout__header-content', children: jsx(Typography, { variant: 'title', color: 'primary', copykey: 'dyn_send_transaction.data.send', children: t('dyn_send_transaction.data.send') }) }) }), jsxs("div", { className: 'send-balance-page-layout__body', children: [jsx(AnimatePresence, { animationComponent: jsx(VerticalDrawerTransition, {}), children: error && (jsx("div", { className: 'send-balance-page-layout__error', children: jsx(Alert, { icon: 'error', variant: 'error', children: error }) })) }), jsx(SendBalanceForm, { tokenBalances: tokenBalances, setCurrentToken: setCurrentToken, isLoading: isLoading, onSubmit: ({ amount, recipient }) => {
                            if (isNativeToken) {
                                transaction.value = transaction.parse(amount);
                            }
                            else if (transaction.parseNonNativeToken) {
                                transaction.nonNativeValue = transaction.parseNonNativeToken(amount, (currentToken === null || currentToken === void 0 ? void 0 : currentToken.decimals) || 18);
                                transaction.value = BigInt(0);
                                transaction.nonNativeAddress = currentToken === null || currentToken === void 0 ? void 0 : currentToken.address;
                                transaction.nonNativeDecimal = currentToken === null || currentToken === void 0 ? void 0 : currentToken.decimals;
                            }
                            transaction.to = recipient;
                            onSubmit();
                        }, initialValues: {
                            amount: getAmount(),
                            recipient: (_a = transaction.to) !== null && _a !== void 0 ? _a : '',
                        }, decimals: isNativeToken ? networkCurrencyDecimals : currentToken === null || currentToken === void 0 ? void 0 : currentToken.decimals, validateAddress: (value) => {
                            if (!value)
                                return true;
                            return transaction.validateAddressFormat(value);
                        }, validateAmount: (amountText) => {
                            if (!amountText)
                                return false;
                            if (isNativeToken) {
                                if (!balance)
                                    return false;
                                const amount = transaction.parse(amountText);
                                return amount <= balance;
                            }
                            // Non Native
                            if (!(currentToken === null || currentToken === void 0 ? void 0 : currentToken.rawBalance) || !transaction.parseNonNativeToken)
                                return false;
                            const amount = Number(transaction.parseNonNativeToken(amountText, (currentToken === null || currentToken === void 0 ? void 0 : currentToken.decimals) || 18));
                            return amount <= currentToken.rawBalance;
                        }, currentToken: currentToken, transaction: transaction }), displayPoweredByDynamicFooter && (jsx(PoweredByDynamic, { classNameRoot: 'send-balance-page-layout__footer' }))] })] }));
};

export { SendBalancePageLayout };
