'use client'
import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
import React__default, { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import { ReactComponent as SvgTooltip } from '../../shared/assets/tooltip.js';
import '../../context/ViewContext/ViewContext.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 { getNetworkInfoEntry } from '../../utils/functions/networksAndChains/networksAndChains.js';
import { Icon } from '../Icon/Icon.js';
import { Typography } from '../Typography/Typography.js';
import '../../context/DynamicContext/DynamicContext.js';
import '../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '../../events/dynamicEvents.js';
import '../../../../_virtual/_tslib.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 '@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 '@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/Alert.js';
import { Tooltip } from '../Tooltip/Tooltip.js';
import '../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 '../PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.js';
import '../Popper/Popper/Popper.js';
import '../Popper/PopperContext/PopperContext.js';
import '../ShadowDOM/ShadowDOM.js';
import 'react-focus-lock';
import 'qrcode';
import { useFetchChain } from '../../widgets/DynamicWidget/hooks/useFetchChain/useFetchChain.js';
import { shortenWalletAddress } from '../../shared/utils/functions/shortenWalletAddress/shortenWalletAddress.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 '../../store/state/sendBalances.js';
import { useNetworkConfigurationsFromProjectSettings } from '../../utils/hooks/useNetworkConfigurationsFromProjectSettings/useNetworkConfigurationsFromProjectSettings.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 TransactionCard = ({ transaction, simulationResult, isGasSponsored, isAATransaction, recipient, }) => {
    var _a, _b, _c, _d, _e, _f, _g;
    const { t } = useTranslation();
    const { primaryWallet, projectSettings, overrides } = useInternalDynamicContext();
    const networkInfo = useNetworkConfigurationsFromProjectSettings({
        evmNetworksOverrides: overrides === null || overrides === void 0 ? void 0 : overrides.evmNetworks,
        projectSettings,
    });
    const { chain } = useFetchChain(primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector);
    const networkInfoEntry = 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,
    });
    const { symbol: nativeCurrencySymbol, decimals: nativeCurrencyDecimals } = (_b = networkInfoEntry === null || networkInfoEntry === void 0 ? void 0 : networkInfoEntry.nativeCurrency) !== null && _b !== void 0 ? _b : {};
    const blockaidOn = simulationResult === null || simulationResult === void 0 ? void 0 : simulationResult.showTotalFiat;
    const feeInUsd = useMemo(() => {
        var _a;
        const nativeTokenUsdPrice = (_a = simulationResult === null || simulationResult === void 0 ? void 0 : simulationResult.priceData) === null || _a === void 0 ? void 0 : _a.nativeTokenUsdPrice;
        if (!nativeTokenUsdPrice || !nativeCurrencyDecimals) {
            return undefined;
        }
        return ((Number(nativeTokenUsdPrice) * Number(transaction.fee.gas)) /
            Math.pow(10, nativeCurrencyDecimals));
    }, [simulationResult, nativeCurrencyDecimals, transaction.fee.gas]);
    const getFeeInUsdDisplay = (feeInUsd) => {
        if (!feeInUsd)
            return undefined;
        return feeInUsd < 0.01 ? '<$0.01' : `~$${feeInUsd.toFixed(2)}`;
    };
    const totalAmountInUsd = useMemo(() => {
        var _a;
        const outgoingAssetsTotal = ((_a = simulationResult === null || simulationResult === void 0 ? void 0 : simulationResult.outAssets) === null || _a === void 0 ? void 0 : _a.reduce((acc, transfer) => {
            var _a;
            const transferOutTotal = ((_a = transfer.transferOut) === null || _a === void 0 ? void 0 : _a.reduce((sum, t) => sum + Number((t === null || t === void 0 ? void 0 : t.usdPrice) || 0), 0)) || 0;
            return acc + transferOutTotal;
        }, 0)) || 0;
        if (blockaidOn && isAATransaction) {
            return outgoingAssetsTotal;
        }
        // for solana, the fee is included in the outgoing assets already
        return (outgoingAssetsTotal +
            (nativeCurrencySymbol === 'SOL' || isGasSponsored ? 0 : feeInUsd || 0));
    }, [simulationResult === null || simulationResult === void 0 ? void 0 : simulationResult.outAssets, nativeCurrencySymbol, feeInUsd]);
    const getTotalAmountInUsdDisplay = (totalAmountInUsd) => {
        if (!totalAmountInUsd)
            return undefined;
        return totalAmountInUsd < 0.01
            ? '<$0.01'
            : `~$${totalAmountInUsd.toFixed(2)}`;
    };
    const renderAssetTransfer = (transfer, index, array) => {
        var _a, _b, _c;
        if (['NATIVE', 'SOL', 'ETH'].includes(transfer.asset.type) &&
            ((_a = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector) === null || _a === void 0 ? void 0 : _a.connectedChain) === 'SOL' &&
            transaction.fee.gas) {
            transfer.amount = (Number(transfer.amount) -
                Number(transaction.fee.gas) / Math.pow(10, 9)).toString();
            transfer.usdPrice = (Number(transfer.usdPrice) - Number(feeInUsd)).toString();
        }
        const getAmountDisplay = () => {
            const amount = Number(transfer.amount);
            if (Number.isInteger(amount)) {
                return amount;
            }
            return amount < 0.000001 ? '<0.000001' : amount.toFixed(6);
        };
        const getUsdPriceDisplay = () => {
            const usdPrice = Number(transfer.usdPrice);
            if (usdPrice < 0.01) {
                return '<$0.01';
            }
            return `$${usdPrice.toFixed(2)}`;
        };
        return (jsxs(Fragment, { children: [jsx("div", { className: `transaction-card__${transfer.direction}`, children: jsxs("div", { className: 'transaction-card__info-container', children: [jsx(Typography, { variant: 'body_normal', color: 'secondary', children: transfer.direction === 'in' ? 'Receive' : 'Send' }), jsxs("div", { className: 'transaction-card__amount-symbol', children: [jsxs("div", { className: 'transaction-card__token-info', children: [jsxs("div", { className: 'transaction-card__token-row', children: [jsxs(Typography, { variant: 'body_normal', color: transfer.direction === 'in' ? 'green-1' : 'error-1', children: [transfer.direction === 'out' ? '-' : '+', getAmountDisplay()] }), jsx(Typography, { variant: 'body_normal', color: 'primary', children: (_b = (transfer.asset.symbol || transfer.asset.name)) !== null && _b !== void 0 ? _b : nativeCurrencySymbol })] }), Number(transfer.usdPrice) > 0 && (jsx(Typography, { variant: 'body_small', color: transfer.direction === 'in' ? 'green-1' : 'error-1', children: getUsdPriceDisplay() }))] }), jsx("div", { className: 'transaction-card__icon', children: jsx("div", { className: 'transaction-card__icon__container', children: jsx("img", { src: transfer.asset.logoUrl ||
                                                    (networkInfoEntry === null || networkInfoEntry === void 0 ? void 0 : networkInfoEntry.nativeCurrency.iconUrl), alt: (_c = transfer.asset.symbol) !== null && _c !== void 0 ? _c : nativeCurrencySymbol, width: 32, height: 32, className: 'transaction-card__icon__container__main' }) }) })] })] }) }), index < array.length - 1 && (jsx("div", { className: 'transaction-card__divider' }))] }));
    };
    const inAssets = ((_c = simulationResult === null || simulationResult === void 0 ? void 0 : simulationResult.inAssets) === null || _c === void 0 ? void 0 : _c.flatMap((assetDiff) => {
        var _a;
        return ((_a = assetDiff.transferIn) === null || _a === void 0 ? void 0 : _a.map((inTransfer) => {
            var _a, _b;
            return ({
                amount: (_a = inTransfer === null || inTransfer === void 0 ? void 0 : inTransfer.value) !== null && _a !== void 0 ? _a : '',
                asset: assetDiff.asset,
                direction: 'in',
                usdPrice: (_b = inTransfer === null || inTransfer === void 0 ? void 0 : inTransfer.usdPrice) !== null && _b !== void 0 ? _b : '',
            });
        })) || [];
    })) || [];
    const outAssets = ((_d = simulationResult === null || simulationResult === void 0 ? void 0 : simulationResult.outAssets) === null || _d === void 0 ? void 0 : _d.flatMap((assetDiff) => {
        var _a;
        return ((_a = assetDiff.transferOut) === null || _a === void 0 ? void 0 : _a.map((outTransfer) => {
            var _a, _b;
            return ({
                amount: (_a = outTransfer === null || outTransfer === void 0 ? void 0 : outTransfer.value) !== null && _a !== void 0 ? _a : '',
                asset: assetDiff.asset,
                direction: 'out',
                usdPrice: (_b = outTransfer === null || outTransfer === void 0 ? void 0 : outTransfer.usdPrice) !== null && _b !== void 0 ? _b : '',
            });
        })) || [];
    })) || [];
    // for solana, the simulation out asset includes the gas fee.
    // so if the gas fee is the same as the total solana spend, then there is no solana being sent, only a gas fee
    const outAssetsWithoutFee = outAssets.filter((asset) => !((asset.asset.type === 'NATIVE' || asset.asset.type === 'SOL') &&
        asset.asset.chainName === 'Solana' &&
        Number(asset.amount) === Number(transaction.fee.gas) / Math.pow(10, 9)));
    //for evm AA with blockaid ON, the outAssets includes the gas fee,
    //so we need to remove it if the transaction doesnt have a tx.value (ETH spend)
    const outAssetsWithoutFeeEvm = outAssetsWithoutFee.filter((asset) => !(asset.asset.type === 'NATIVE' &&
        transaction.chain === 'EVM' &&
        !transaction.value));
    const allAssets = [...outAssetsWithoutFeeEvm, ...inAssets];
    const getGasFeeDisplay = () => {
        if (feeInUsd) {
            return getFeeInUsdDisplay(feeInUsd);
        }
        if (transaction.fee.gas) {
            return `${transaction.format(transaction.fee.gas, {
                precision: 8,
            })} ${nativeCurrencySymbol}`;
        }
        return `-- ${nativeCurrencySymbol}`;
    };
    return (jsxs("div", { className: 'transaction-card-container', children: [allAssets.length > 0 && (jsx("div", { className: 'transaction-card', children: jsx("div", { className: 'transaction-card__assets-container', children: allAssets.map((asset, index, array) => (jsx(React__default.Fragment, { children: renderAssetTransfer(asset, index, array) }, `asset-${index}`))) }) })), jsx("div", { className: 'transaction-card', children: jsxs("div", { className: 'transaction-card__details', children: [recipient && (jsxs(Fragment, { children: [jsxs("div", { className: 'transaction-card__row', children: [jsx(Typography, { variant: 'body_normal', color: 'secondary', copykey: 'dyn_send_transaction.confirmation.data.recipient', children: t('dyn_send_transaction.confirmation.data.recipient') }), jsx(Typography, { variant: 'body_normal', color: 'primary', "data-testid": 'transaction-recipient', children: shortenWalletAddress(recipient) })] }), jsx("div", { className: 'transaction-card__divider' })] })), !recipient &&
                            (transaction.to || ((_e = simulationResult === null || simulationResult === void 0 ? void 0 : simulationResult.counterparties) === null || _e === void 0 ? void 0 : _e[0])) && (jsxs(Fragment, { children: [jsxs("div", { className: 'transaction-card__row', children: [jsx(Typography, { variant: 'body_normal', color: 'secondary', copykey: 'dyn_send_transaction.confirmation.data.destination', children: t('dyn_send_transaction.confirmation.data.destination') }), jsx(Typography, { variant: 'body_normal', color: 'primary', "data-testid": 'transaction-destination', children: shortenWalletAddress((_f = transaction.to) !== null && _f !== void 0 ? _f : (_g = simulationResult === null || simulationResult === void 0 ? void 0 : simulationResult.counterparties) === null || _g === void 0 ? void 0 : _g[0]) })] }), jsx("div", { className: 'transaction-card__divider' })] })), jsxs("div", { className: 'transaction-card__row', children: [jsx(Typography, { variant: 'body_normal', color: 'secondary', copykey: 'dyn_send_transaction.confirmation.data.network', children: t('dyn_send_transaction.confirmation.data.network') }), jsxs("div", { className: 'transaction-card__network-info', children: [jsx(Typography, { variant: 'body_normal', color: 'primary', children: (networkInfoEntry === null || networkInfoEntry === void 0 ? void 0 : networkInfoEntry.name) || 'Ethereum' }), jsx("img", { src: networkInfoEntry === null || networkInfoEntry === void 0 ? void 0 : networkInfoEntry.iconUrls[0], alt: (networkInfoEntry === null || networkInfoEntry === void 0 ? void 0 : networkInfoEntry.name) || 'Network icon', width: 16, height: 16, className: 'transaction-card__network-icon' })] })] }), !isGasSponsored && (jsxs(Fragment, { children: [jsx("div", { className: 'transaction-card__divider' }), jsxs("div", { className: 'transaction-card__row', children: [jsxs("div", { className: 'transaction-card__label-with-tooltip', children: [jsx(Typography, { variant: 'body_normal', color: 'secondary', copykey: 'dyn_send_transaction.confirmation.data.gas_estimate', children: t('dyn_send_transaction.confirmation.data.gas_estimate') }), jsx(Tooltip, { content: 'Network fees are paid to process your transaction', className: 'transaction-confirmation', children: jsx(Icon, { size: 'small', className: 'fee-tooltip', children: jsx(SvgTooltip, {}) }) })] }), jsx("div", { className: 'transaction-card__value', children: jsx(Typography, { variant: 'body_normal', color: 'primary', "data-testid": 'transaction-estimated-gas-fee', children: getGasFeeDisplay() }) })] })] })), blockaidOn &&
                            totalAmountInUsd !== undefined &&
                            totalAmountInUsd > 0 &&
                            !(isAATransaction && !isGasSponsored) && (jsxs(Fragment, { children: [jsx("div", { className: 'transaction-card__divider' }), jsxs("div", { className: 'transaction-card__row', children: [jsx(Typography, { variant: 'body_normal', color: 'secondary', weight: 'bold', copykey: 'dyn_send_transaction.confirmation.data.total', children: t('dyn_send_transaction.confirmation.data.total') }), jsx("div", { className: 'transaction-card__total-amount', children: jsx(Typography, { variant: 'body_normal', color: 'primary', "data-testid": 'transaction-estimated-total', children: getTotalAmountInUsdDisplay(totalAmountInUsd) }) })] })] }))] }) })] }));
};

export { TransactionCard };
