'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');
var sdkApiCore = require('@dynamic-labs/sdk-api-core');
var utils = require('@dynamic-labs/utils');
var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
var ChainIcon = require('../../components/ChainIcon/ChainIcon.cjs');
var SendBalancePageLayout = require('../../components/SendBalancePageLayout/SendBalancePageLayout.cjs');
var spinner = require('../../components/Spinner/spinner.cjs');
var TransactionStatusLayout = require('../../components/TransactionStatusLayout/TransactionStatusLayout.cjs');
require('../../context/DynamicContext/DynamicContext.cjs');
require('../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('@dynamic-labs/iconic');
require('../../context/ViewContext/ViewContext.cjs');
var logger = require('../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('../../utils/constants/colors.cjs');
require('../../utils/constants/values.cjs');
require('../../shared/consts/index.cjs');
var dynamicEvents = 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('../Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('../../context/ThemeContext/ThemeContext.cjs');
require('../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
require('bs58');
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('../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('../../components/Accordion/components/AccordionItem/AccordionItem.cjs');
require('../../components/Alert/Alert.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');
var useFetchChain = require('../../widgets/DynamicWidget/hooks/useFetchChain/useFetchChain.cjs');
var shortenWalletAddress = require('../../shared/utils/functions/shortenWalletAddress/shortenWalletAddress.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('../ExchangeWhitelistWarning/ExchangeWhitelistWarning.cjs');
require('../../context/ErrorContext/hooks/useErrorText/useErrorText.cjs');
require('../../context/FooterAnimationContext/index.cjs');
require('../MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.cjs');
require('../../context/PasskeyContext/PasskeyContext.cjs');
require('../../context/OnrampContext/OnrampContext.cjs');
var sendBalances = require('../../store/state/sendBalances.cjs');
require('../../store/state/connectorsInitializing/connectorsInitializing.cjs');
require('../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.cjs');
require('../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.cjs');
var TransactionConfirmationView = require('../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');
var useNetworkDataFromWallet = require('../../utils/hooks/useNetworkDataFromWallet/useNetworkDataFromWallet.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');

const usingNative = (token) => Boolean(token.isNative);
const getTransactionValue = (transaction, isNativeToken) => {
    if (isNativeToken)
        return transaction.value
            ? transaction.format(transaction.value, { precision: 6 })
            : '0';
    return transaction.nonNativeValue && transaction.formatNonNativeToken
        ? transaction.formatNonNativeToken(transaction.nonNativeValue, transaction.nonNativeDecimal || 18)
        : '0';
};
const getSupportedChainName = (connectedChain) => {
    const supportedChains = {
        EVM: sdkApiCore.ChainEnum.Evm,
        SOL: sdkApiCore.ChainEnum.Sol,
        SUI: sdkApiCore.ChainEnum.Sui,
    };
    return connectedChain && connectedChain in supportedChains
        ? supportedChains[connectedChain]
        : sdkApiCore.ChainEnum.Evm;
};
const SendBalanceView = ({ initialRecipientAddress = '', initialValue, onClickBack, onClickClose, onError, onSuccess, onDone, displayPoweredByDynamicFooter = false, }) => {
    const [stage, setStage] = React.useState('form');
    const { primaryWallet, walletUiUtils } = useInternalDynamicContext.useInternalDynamicContext();
    const { t } = reactI18next.useTranslation();
    const [isNativeToken, setIsNativeToken] = React.useState(false);
    const [currentToken, setCurrentToken] = React.useState(undefined);
    const [tokenBalances, setTokenBalances] = React.useState(undefined);
    const [transactionHash, setTransactionHash] = React.useState(undefined);
    const { showFiat } = useInternalDynamicContext.useInternalDynamicContext();
    const walletConnector = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector;
    const { chain } = useFetchChain.useFetchChain(walletConnector);
    // token balances are ordered in the backend - this should just be a passthrough
    const { tokenBalances: orderedTokenBalances, isLoading } = useTokenBalances.useTokenBalances({
        chainName: getSupportedChainName(walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.connectedChain),
        includeFiat: showFiat,
        includeNativeBalance: true,
    });
    if (!primaryWallet) {
        throw new utils.DynamicError('Primary wallet is not available, send balance cannot be displayed');
    }
    if (walletConnector && !walletConnectorCore.isSendBalanceWalletConnector(walletConnector)) {
        throw new utils.DynamicError('Primary wallet is not eligible for this operation. It must implement ISendBalanceWalletConnector');
    }
    const [transaction, setTransaction] = React.useState(null);
    React.useEffect(() => {
        const evmChain = (walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.connectedChain) === 'EVM'
            ? networksAndChains.getEvmChainName(Number(chain === null || chain === void 0 ? void 0 : chain.chainId))
            : undefined;
        sendBalances.setSendBalanceVariable('chainName', evmChain || (chain === null || chain === void 0 ? void 0 : chain.name) || (walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.connectedChain));
        return () => {
            sendBalances.resetSendBalanceState();
        };
    }, [chain === null || chain === void 0 ? void 0 : chain.chainId, chain === null || chain === void 0 ? void 0 : chain.name, walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.connectedChain]);
    React.useEffect(() => {
        if (orderedTokenBalances)
            setTokenBalances(orderedTokenBalances);
    }, [orderedTokenBalances]);
    React.useEffect(() => {
        if (!walletConnector)
            return;
        // If address is zero or 1 address it's native token, otherwise non-native token
        if (currentToken)
            setIsNativeToken(usingNative(currentToken));
        walletConnector
            .createUiTransaction(primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.address)
            .then((transaction) => {
            if (initialRecipientAddress)
                transaction.to = initialRecipientAddress;
            if (initialValue)
                transaction.value = initialValue;
            if (currentToken && !usingNative(currentToken)) {
                transaction.nonNativeAddress = currentToken === null || currentToken === void 0 ? void 0 : currentToken.address;
                transaction.nonNativeValue = BigInt(0);
                transaction.nonNativeDecimal = currentToken === null || currentToken === void 0 ? void 0 : currentToken.decimals;
            }
            setTransaction(transaction);
        })
            .catch((error) => {
            logger.logger.debug('[SendBalanceView] Error creating transaction', error);
            if (error instanceof utils.DynamicError && error.code === '0') {
                // means user cancelled the request for sync'ing the wallet
                onDone === null || onDone === void 0 ? void 0 : onDone();
                return;
            }
            onError === null || onError === void 0 ? void 0 : onError(error);
        });
    }, [currentToken]);
    const networkData = useNetworkDataFromWallet.useNetworkDataFromWallet(primaryWallet);
    if (!transaction || !networkData) {
        return (jsxRuntime.jsx("div", { className: 'send-balance-widget-view__spinner', "data-testid": 'send-balance-spinner', children: jsxRuntime.jsx(spinner.Spinner, {}) }));
    }
    const handleSuccessToRefreshBalance = (txHash) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        // SOL
        if ((walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.connectedChain) === 'SOL') {
            // Just to make absolutely sure the block has been validated
            // and confirmed on the Solana blockchain
            setTimeout(() => dynamicEvents.dynamicEvents.emit('tokenBalancesChanged'), 5000);
        }
        // EVM
        if (walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.confirmTransactionStatus) {
            yield (walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.confirmTransactionStatus(txHash));
            dynamicEvents.dynamicEvents.emit('tokenBalancesChanged');
        }
    });
    const networkCurrency = (currentToken === null || currentToken === void 0 ? void 0 : currentToken.symbol) || networkData.nativeCurrency.symbol;
    const currencyIcon = (chain === null || chain === void 0 ? void 0 : chain.name) && (jsxRuntime.jsx(ChainIcon.ChainIcon, { chain: chain, chainName: chain.name }));
    const buildFormStage = () => (jsxRuntime.jsx(SendBalancePageLayout.SendBalancePageLayout, { transaction: transaction, onClickBack: onClickBack, networkName: networkData.vanityName || networkData.name, networkIcon: currencyIcon, networkCurrencyDecimals: networkData.nativeCurrency.symbol === 'SOL'
            ? 9
            : networkData.nativeCurrency.decimals, walletAddress: shortenWalletAddress.shortenWalletAddress(currentToken === null || currentToken === void 0 ? void 0 : currentToken.address), walletKey: primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector.key, onClickClose: onClickClose, displayPoweredByDynamicFooter: displayPoweredByDynamicFooter, onSubmit: () => setStage('confirmation'), tokenBalances: tokenBalances !== null && tokenBalances !== void 0 ? tokenBalances : (currentToken && [currentToken]), currentToken: currentToken, setCurrentToken: setCurrentToken, isLoading: isLoading, isNativeToken: isNativeToken }));
    const buildTransactionStage = () => (jsxRuntime.jsx(TransactionConfirmationView.TransactionConfirmationView, { walletConnector: primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector, transaction: transaction, mutation: () => {
            walletUiUtils.disabledConfirmationOnce();
            return transaction.submit();
        }, copykey: 'dyn_send_transaction.confirmation.title', title: t('dyn_send_transaction.confirmation.title'), onClickBack: () => setStage('form'), onError: onError, displayPoweredByDynamicFooter: displayPoweredByDynamicFooter, onSuccess: (txHash) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
            if (!txHash)
                return;
            onSuccess === null || onSuccess === void 0 ? void 0 : onSuccess(txHash);
            setTransactionHash(txHash);
            setStage('success');
            handleSuccessToRefreshBalance(txHash);
        }), currentToken: currentToken, isNativeToken: isNativeToken, transactionValue: getTransactionValue(transaction, isNativeToken), sendBalanceTransaction: true }));
    const buildSuccessState = () => {
        var _a;
        return (jsxRuntime.jsx(TransactionStatusLayout.TransactionStatusLayout, { transactionValue: getTransactionValue(transaction, isNativeToken), destinationAddress: (_a = transaction.to) !== null && _a !== void 0 ? _a : '', networkCurrency: networkCurrency, networkName: networkData.name || '', NetworkIcon: currencyIcon, onClickClose: onClickClose, onDone: () => onDone === null || onDone === void 0 ? void 0 : onDone(), displayPoweredByDynamicFooter: displayPoweredByDynamicFooter, transaction: transaction, currentToken: currentToken, isNativeToken: isNativeToken, transactionHash: transactionHash }));
    };
    const getCurrentView = () => {
        switch (stage) {
            case 'form':
                return buildFormStage();
            case 'confirmation':
                return buildTransactionStage();
            case 'success':
                return buildSuccessState();
        }
    };
    return getCurrentView();
};

exports.SendBalanceView = SendBalanceView;
exports.getTransactionValue = getTransactionValue;
exports.usingNative = usingNative;
