'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 arrowLeft = require('../../shared/assets/arrow-left.cjs');
var close = require('../../shared/assets/close.cjs');
require('../../context/ViewContext/ViewContext.cjs');
var logger = 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');
var networksAndChains = require('../../utils/functions/networksAndChains/networksAndChains.cjs');
require('@dynamic-labs-sdk/client/core');
require('../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../config/ApiEndpoint.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');
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');
require('../Accordion/components/AccordionItem/AccordionItem.cjs');
var Alert = require('../Alert/Alert.cjs');
var AnimatePresence = require('../AnimatePresence/AnimatePresence.cjs');
var Typography = require('../Typography/Typography.cjs');
require('../ShadowDOM/ShadowDOM.cjs');
var IconButton = require('../IconButton/IconButton.cjs');
require('../InlineWidget/InlineWidget.cjs');
require('../Input/Input.cjs');
require('../IsBrowser/IsBrowser.cjs');
require('../MenuList/Dropdown/Dropdown.cjs');
require('../OverlayCard/OverlayCard.cjs');
require('../Transition/ZoomTransition/ZoomTransition.cjs');
require('../Transition/SlideInUpTransition/SlideInUpTransition.cjs');
require('../Transition/OpacityTransition/OpacityTransition.cjs');
var VerticalDrawerTransition = require('../Transition/VerticalDrawerTransition/VerticalDrawerTransition.cjs');
var ModalHeader = require('../ModalHeader/ModalHeader.cjs');
require('../PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.cjs');
require('../Popper/Popper/Popper.cjs');
require('../Popper/PopperContext/PopperContext.cjs');
require('react-focus-lock');
var PoweredByDynamic = require('../PoweredByDynamic/PoweredByDynamic.cjs');
require('qrcode');
var useFetchChain = require('../../widgets/DynamicWidget/hooks/useFetchChain/useFetchChain.cjs');
require('formik');
require('../../utils/hooks/useSubdomainCheck/useSubdomainCheck.cjs');
require('../../context/WalletGroupContext/WalletGroupContext.cjs');
require('../../context/IpConfigurationContext/IpConfigurationContext.cjs');
require('../../context/ConnectWithOtpContext/ConnectWithOtpContext.cjs');
require('../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.cjs');
require('@hcaptcha/react-hcaptcha');
require('../../widgets/DynamicWidget/context/DynamicWidgetContext.cjs');
require('../../widgets/DynamicWidget/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');
var SendBalanceForm = require('../SendBalanceForm/SendBalanceForm.cjs');
var useNetworkConfigurationsFromProjectSettings = require('../../utils/hooks/useNetworkConfigurationsFromProjectSettings/useNetworkConfigurationsFromProjectSettings.cjs');
var constants = require('./components/TokensBalanceDropdown/constants.cjs');
require('../../store/state/sendBalances.cjs');
require('../../store/state/connectorsInitializing/connectorsInitializing.cjs');
require('../OverlayCardBase/OverlayCardTarget/OverlayCardTarget.cjs');
require('../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.cjs');
require('../../views/TransactionConfirmationView/TransactionConfirmationView.cjs');
require('../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.cjs');
require('../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.cjs');
require('../../../index.cjs');
require('../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.cjs');
require('../../store/state/tokenBalances.cjs');
require('../../store/state/multichainBalances.cjs');
require('../../shared/utils/functions/getInitialUrl/getInitialUrl.cjs');
var useInternalDynamicContext = require('../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');

const SendBalancePageLayout = ({ error, onClickClose, onClickBack, onSubmit, displayPoweredByDynamicFooter = false, transaction, networkCurrencyDecimals, tokenBalances, currentToken, setCurrentToken, isLoading, isNativeToken, }) => {
    var _a;
    const { t } = reactI18next.useTranslation();
    const { primaryWallet, projectSettings, overrides } = useInternalDynamicContext.useInternalDynamicContext();
    const networkInfo = useNetworkConfigurationsFromProjectSettings.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.useFetchChain(walletConnector);
    const closeButton = onClickClose && (jsxRuntime.jsx(IconButton.IconButton, { type: 'button', onClick: onClickClose, "data-testid": 'close-button', children: jsxRuntime.jsx(close.ReactComponent, {}) }));
    const backButton = onClickBack && (jsxRuntime.jsx(IconButton.IconButton, { type: 'button', onClick: onClickBack, "data-testid": 'back-button', children: jsxRuntime.jsx(arrowLeft.ReactComponent, {}) }));
    const { data: balance } = usePromise.usePromise(() => transaction.getBalance(), {
        deps: [transaction],
    });
    React.useEffect(() => {
        const getNativeTokenAndFetchBalance = () => _tslib.__awaiter(void 0, void 0, void 0, function* () {
            var _a;
            const nativeTokenInfo = networksAndChains.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.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' ? constants.nativeSolanaAddress : constants.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 = () => _tslib.__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 (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx(ModalHeader.ModalHeader, { leading: backButton, trailing: closeButton, alignContent: 'bottom', children: jsxRuntime.jsx("div", { className: 'send-balance-page-layout__header-content', children: jsxRuntime.jsx(Typography.Typography, { variant: 'title', color: 'primary', copykey: 'dyn_send_transaction.data.send', children: t('dyn_send_transaction.data.send') }) }) }), jsxRuntime.jsxs("div", { className: 'send-balance-page-layout__body', children: [jsxRuntime.jsx(AnimatePresence.AnimatePresence, { animationComponent: jsxRuntime.jsx(VerticalDrawerTransition.VerticalDrawerTransition, {}), children: error && (jsxRuntime.jsx("div", { className: 'send-balance-page-layout__error', children: jsxRuntime.jsx(Alert.Alert, { icon: 'error', variant: 'error', children: error }) })) }), jsxRuntime.jsx(SendBalanceForm.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 && (jsxRuntime.jsx(PoweredByDynamic.PoweredByDynamic, { classNameRoot: 'send-balance-page-layout__footer' }))] })] }));
};

exports.SendBalancePageLayout = SendBalancePageLayout;
