'use client'
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var jsxRuntime = require('react/jsx-runtime');
var React = require('react');
var reactI18next = require('react-i18next');
var utils = require('@dynamic-labs/utils');
var Badge = require('../../../components/Badge/Badge.cjs');
var Checkbox = require('../../../components/Checkbox/Checkbox.cjs');
var EmbeddedWalletExport = require('../../../components/EmbeddedWalletExport/EmbeddedWalletExport.cjs');
var ErrorContainer = require('../../../components/ErrorContainer/ErrorContainer.cjs');
var IconButton = require('../../../components/IconButton/IconButton.cjs');
var ModalHeader = require('../../../components/ModalHeader/ModalHeader.cjs');
var NeedHelpSection = require('../../../components/NeedHelpSection/NeedHelpSection.cjs');
var Typography = require('../../../components/Typography/Typography.cjs');
var TypographyButton = require('../../../components/TypographyButton/TypographyButton.cjs');
require('../../../context/DynamicContext/useDynamicContext/useDynamicContext.cjs');
var useInternalDynamicContext = require('../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');
var ViewContext = require('../../../context/ViewContext/ViewContext.cjs');
var dynamicEvents = require('../../../events/dynamicEvents.cjs');
var getProperErrorMessage = require('../../../modals/SignMessageConfirmationModal/getProperErrorMessage.cjs');
var close = require('../../../shared/assets/close.cjs');
var exportEmbeddedHero = require('../../../shared/assets/export-embedded-hero.cjs');
var eyeOffIcon = require('../../../shared/assets/eye-off-icon.cjs');
var info = require('../../../shared/assets/info.cjs');
var walletV2 = require('../../../shared/assets/wallet-v2.cjs');
require('@dynamic-labs/iconic');
var logger = require('../../../shared/logger.cjs');
var errors = require('../../../utils/constants/errors.cjs');
var exportWalletCredential = require('../../../utils/functions/exportWalletCredential/exportWalletCredential.cjs');
var getTurnkeyWalletId = require('../../../utils/functions/getTurnkeyWalletId/getTurnkeyWalletId.cjs');
require('../../../../../_virtual/_tslib.cjs');
require('@dynamic-labs/wallet-connector-core');
require('../../../context/CaptchaContext/CaptchaContext.cjs');
require('@dynamic-labs/sdk-api-core');
require('../../../context/ErrorContext/ErrorContext.cjs');
require('@dynamic-labs/wallet-book');
require('../../../utils/constants/colors.cjs');
require('../../../utils/constants/values.cjs');
require('../../../shared/consts/index.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../store/state/nonce/nonce.cjs');
require('@dynamic-labs-wallet/browser-wallet-client');
require('@dynamic-labs-sdk/client/core');
require('eventemitter3');
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('../../../utils/functions/getWaasAddressTypeLabel/getWaasAddressTypeLabel.cjs');
require('../../../context/AccessDeniedContext/AccessDeniedContext.cjs');
require('../../../context/AccountExistsContext/AccountExistsContext.cjs');
var UserWalletsContext = require('../../../context/UserWalletsContext/UserWalletsContext.cjs');
require('../../../store/state/authMode/authMode.cjs');
require('../../../store/state/loadingAndLifecycle/loadingAndLifecycle.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');
var useSmartWallets = require('../../../utils/hooks/useSmartWallets/useSmartWallets.cjs');
require('../../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
var useMutation = require('../../../utils/hooks/useMutation/useMutation.cjs');
require('bs58');
require('@dynamic-labs/types');
require('../../../context/SocialRedirectContext/SocialRedirectContext.cjs');
require('../../../context/LoadingContext/LoadingContext.cjs');
require('../../../context/WalletContext/WalletContext.cjs');
var turnkeyExport = require('../utils/turnkeyExport/turnkeyExport.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/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');
require('formik');
require('../../../utils/hooks/useSubdomainCheck/useSubdomainCheck.cjs');
require('../../../context/WalletGroupContext/WalletGroupContext.cjs');
var DynamicWidgetContext = require('../../../widgets/DynamicWidget/context/DynamicWidgetContext.cjs');
require('../../../utils/hooks/useGetMfaToken/useGetMfaToken.cjs');
require('../../../utils/hooks/useWalletBackup/useWalletBackup.cjs');
require('../../../utils/hooks/useWalletBackup/BackupError.cjs');
require('../../../utils/hooks/useWalletBackup/types.cjs');
require('../../../utils/hooks/useWalletBackup/cloudProviders.cjs');
require('@hcaptcha/react-hcaptcha');
require('@marsidev/react-turnstile');
require('../../../context/IpConfigurationContext/IpConfigurationContext.cjs');
require('../../../context/ConnectWithOtpContext/ConnectWithOtpContext.cjs');
require('../../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.cjs');
var waasExport = require('../utils/waasExport/waasExport.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');
require('../../../utils/hooks/useWalletDelegation/DelegationError.cjs');
require('../../../store/state/sendBalances.cjs');
require('../../../store/state/connectorsInitializing/connectorsInitializing.cjs');
require('../../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.cjs');
require('../../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.cjs');
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/ManagePasskeysMfaWidgetView/ManagePasskeysMfaWidgetView.cjs');
require('../../../widgets/DynamicWidget/views/ManageTotpMfaWidgetView/ManageTotpMfaWidgetView.cjs');
require('../../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.cjs');
require('../../../store/state/tokenBalances.cjs');
require('../../../store/state/multichainBalances.cjs');
var useSyncEmbeddedWalletFlow = require('../../../utils/hooks/useSyncEmbeddedWalletFlow/useSyncEmbeddedWalletFlow.cjs');
require('@dynamic-labs/store');
require('../../../shared/utils/functions/getInitialUrl/getInitialUrl.cjs');

const EmbeddedRevealView = ({ exportPrivateKey, isPromptForExport = false, walletId, }) => {
    var _a, _b, _c, _d, _e;
    const { primaryWallet, user, setShowAuthFlow, environmentId } = useInternalDynamicContext.useInternalDynamicContext();
    const userWallets = UserWalletsContext.useUserWalletsExternal();
    const { handleAcknowledgeExportPrompt } = useSyncEmbeddedWalletFlow.useSyncEmbeddedWalletFlow();
    const isWaasWallet = Boolean(user === null || user === void 0 ? void 0 : user.verifiedCredentials.find((vc) => { var _a; return (_a = vc.walletName) === null || _a === void 0 ? void 0 : _a.startsWith('dynamicwaas'); }));
    const { setDynamicWidgetView } = DynamicWidgetContext.useWidgetContext();
    const { pushView } = ViewContext.useViewContext();
    const { getEOAWallet, isSmartWallet } = useSmartWallets.useSmartWallets();
    const [isAcknowledged, setIsAcknowledged] = React.useState(false);
    const [iframeContainerRef, setIframeContainerRef] = React.useState(null);
    // Smart wallets' signer EOAs are not registered in userWallets, so also
    // match a user wallet whose derived EOA carries the requested id
    const walletFromId = walletId
        ? userWallets.find((w) => { var _a; return w.id === walletId || ((_a = getEOAWallet(w)) === null || _a === void 0 ? void 0 : _a.id) === walletId; })
        : undefined;
    if (walletId && !walletFromId) {
        throw new utils.DynamicError('Wallet not found. Please try again.', errors.INVALID_WALLET_DATA);
    }
    const targetWallet = walletFromId !== null && walletFromId !== void 0 ? walletFromId : primaryWallet;
    if (!targetWallet) {
        throw new utils.DynamicError('No primary wallet found', errors.INVALID_WALLET_DATA);
    }
    let primaryTurnkeyWalletId;
    try {
        primaryTurnkeyWalletId = getTurnkeyWalletId.getTurnkeyWalletId(targetWallet.id, (user === null || user === void 0 ? void 0 : user.verifiedCredentials) || []);
    }
    catch (error) {
        // waas wallet
    }
    const turnkeyCredential = (_a = user === null || user === void 0 ? void 0 : user.verifiedCredentials) === null || _a === void 0 ? void 0 : _a.find(({ walletName, id }) => (walletName === null || walletName === void 0 ? void 0 : walletName.startsWith('turnkey')) && id === primaryTurnkeyWalletId);
    const walletProperties = turnkeyCredential === null || turnkeyCredential === void 0 ? void 0 : turnkeyCredential.walletProperties;
    const walletCredential = (_b = user === null || user === void 0 ? void 0 : user.verifiedCredentials) === null || _b === void 0 ? void 0 : _b.find((cred) => cred.address === targetWallet.address);
    const isTurnkeyHDWallet = walletProperties === null || walletProperties === void 0 ? void 0 : walletProperties.turnkeyHDWalletId;
    const wallet = (_c = (targetWallet && getEOAWallet(targetWallet))) !== null && _c !== void 0 ? _c : targetWallet;
    const isTurnkeyWallet = Boolean((_e = (_d = wallet === null || wallet === void 0 ? void 0 : wallet.connector) === null || _d === void 0 ? void 0 : _d.key) === null || _e === void 0 ? void 0 : _e.startsWith('turnkey'));
    // eslint-disable-next-line arrow-body-style
    React.useEffect(() => {
        return () => {
            if (isTurnkeyWallet) {
                turnkeyExport.cleanupExport({
                    wallet: wallet,
                });
            }
            if (isWaasWallet) {
                waasExport.cleanupExport({
                    wallet: wallet,
                });
            }
        };
        // only run once on unmount
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    const { mutate: handleExportWallet, isLoading, error, data, } = useMutation.useMutation(() => exportWalletCredential.exportWalletCredential({
        environmentId,
        exportPrivateKey,
        handleAcknowledgeExportPrompt,
        iframeContainerRef: iframeContainerRef,
        isTurnkeyWallet,
        isWaasWallet,
        user,
        wallet,
    }), {
        onFailure: (err) => {
            logger.logger.error('Failed to export', err);
            dynamicEvents.dynamicEvents.emit('embeddedWalletRevealFailed', err);
        },
    });
    const errorText = React.useMemo(() => {
        if (!error) {
            return undefined;
        }
        if (error instanceof utils.DynamicError) {
            return error.message;
        }
        try {
            return getProperErrorMessage.getProperErrorMessage(error, user);
        }
        catch (e) {
            if (e instanceof utils.AccessBlockedError) {
                pushView('access-blocked');
            }
            return;
        }
    }, [error, pushView, user]);
    const { t } = reactI18next.useTranslation();
    const hasInjectedCredential = !isLoading && data && !error;
    // Track successful reveal for emitting event on unmount
    const revealedWalletRef = React.useRef(null);
    React.useEffect(() => {
        if (hasInjectedCredential && wallet) {
            revealedWalletRef.current = wallet;
        }
    }, [hasInjectedCredential, wallet]);
    // Emit success event when user exits the screen after successful reveal
    React.useEffect(() => () => {
        if (revealedWalletRef.current) {
            dynamicEvents.dynamicEvents.emit('embeddedWalletRevealCompleted', revealedWalletRef.current);
        }
    }, []);
    const credentialTitle = !isTurnkeyHDWallet || exportPrivateKey
        ? t('dyn_embedded_reveal.private_key_title')
        : t('dyn_embedded_reveal.recovery_phrase_title');
    const getTitle = () => {
        if (hasInjectedCredential) {
            return credentialTitle;
        }
        if (isPromptForExport) {
            return t('dyn_embedded_reveal.prompt_for_export_title');
        }
        return t('dyn_embedded_reveal.agreement_title');
    };
    const title = getTitle();
    const handleClickUnlink = () => {
        pushView('embedded-delete-view');
    };
    const closeButton = (jsxRuntime.jsx(IconButton.IconButton, { onClick: () => {
            setShowAuthFlow(false);
        }, type: 'button', children: jsxRuntime.jsx(close.ReactComponent, {}) }));
    const getBodyClassName = () => {
        const baseClass = 'embedded-reveal-view__body';
        if (isWaasWallet && hasInjectedCredential && title === credentialTitle) {
            return `${baseClass} ${baseClass}--waas-credentials`;
        }
        return baseClass;
    };
    const isEip7702SmartWallet = Boolean(targetWallet === null || targetWallet === void 0 ? void 0 : targetWallet.id.endsWith('-zerodev'));
    const isErc4337SmartWallet = Boolean(targetWallet && isSmartWallet(targetWallet)) &&
        !isEip7702SmartWallet;
    const shouldShowAaWarning = isErc4337SmartWallet && !isLoading && Boolean(data) && !error;
    const aaWarning = shouldShowAaWarning && (jsxRuntime.jsxs("div", { className: 'embedded-reveal-view__zerodev-warning', children: [jsxRuntime.jsxs("div", { className: 'embedded-reveal-view__zerodev-warning__title-row', children: [jsxRuntime.jsx(info.ReactComponent, { className: 'embedded-reveal-view__zerodev-warning__icon' }), jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', weight: 'bold', copykey: 'dyn_embedded_reveal.aa_warning.title', children: t('dyn_embedded_reveal.aa_warning.title') })] }), jsxRuntime.jsxs(Typography.Typography, { variant: 'body_normal', weight: 'regular', copykey: 'dyn_embedded_reveal.aa_warning.subtitle', children: [t('dyn_embedded_reveal.aa_warning.subtitle'), jsxRuntime.jsx("button", { onClick: () => {
                            setShowAuthFlow(false);
                            setDynamicWidgetView('send-balance');
                        }, className: 'embedded-reveal-view__zerodev-warning__link-button', children: jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', weight: 'regular', color: 'primary', className: 'underline', copykey: 'dyn_embedded_reveal.aa_warning.button', children: t('dyn_embedded_reveal.aa_warning.button') }) })] })] }));
    const contentHeader = (jsxRuntime.jsx("div", { children: jsxRuntime.jsx("div", { className: 'embedded-reveal-view__body__description', children: !hasInjectedCredential && (jsxRuntime.jsx("div", { className: 'embedded-reveal-view__header', children: jsxRuntime.jsx("div", { className: 'embedded-reveal-view__header__hero', children: jsxRuntime.jsx(exportEmbeddedHero.ReactComponent, {}) }) })) }) }));
    return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx(ModalHeader.ModalHeader, { trailing: isPromptForExport ? null : closeButton, children: jsxRuntime.jsx(Typography.Typography, { as: 'h1', variant: 'title', color: 'primary', "data-testid": 'dynamic-auth-modal-heading', className: 'header__typography', children: title }) }), jsxRuntime.jsx("div", { className: 'embedded-reveal-view', children: jsxRuntime.jsxs("div", { className: getBodyClassName(), children: [aaWarning, (!isWaasWallet ||
                            !hasInjectedCredential ||
                            title !== credentialTitle) &&
                            contentHeader, (isTurnkeyWallet || isWaasWallet) && (jsxRuntime.jsx(EmbeddedWalletExport.EmbeddedWalletExport, { wallet: wallet, isTurnkeyWallet: isTurnkeyWallet, isWaasWallet: isWaasWallet, data: data, onIframeContainerRef: setIframeContainerRef, isVisible: !title.includes('Agree') })), hasInjectedCredential ? (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx(TypographyButton.TypographyButton, { buttonPadding: 'medium', buttonVariant: 'brand-primary', onClick: () => {
                                        setShowAuthFlow(false);
                                    }, loading: isLoading, copykey: 'dyn_embedded_reveal.done_button_label', typographyProps: {
                                        color: 'inherit',
                                    }, children: t('dyn_embedded_reveal.done_button_label') }), !exportPrivateKey && (jsxRuntime.jsx(TypographyButton.TypographyButton, { buttonClassName: 'embedded-reveal-view__body__unlink_button', buttonVariant: 'tertiary', buttonPadding: 'none', copykey: 'dyn_embedded_reveal.unlink', onClick: handleClickUnlink, typographyProps: {
                                        color: 'secondary',
                                        variant: 'button_tertiary',
                                    }, children: t('dyn_embedded_reveal.unlink') }))] })) : (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsxs("div", { className: 'embedded-reveal-view__body__description', children: [jsxRuntime.jsx("div", { className: 'embedded-reveal-view__body__badge-container', children: jsxRuntime.jsx(Badge.Badge, { text: t('dyn_embedded_reveal.badge_label'), className: 'embedded-reveal-view__body__badge' }) }), jsxRuntime.jsx(Typography.Typography, { variant: 'body_normal', color: 'primary', weight: 'regular', copykey: 'dyn_embedded_reveal.prompt_for_export_description', children: t('dyn_embedded_reveal.prompt_for_export_description') })] }), errorText && jsxRuntime.jsx(ErrorContainer.ErrorContainer, { children: errorText }), jsxRuntime.jsxs("div", { className: 'embedded-reveal-view__body__card', children: [jsxRuntime.jsxs("div", { className: 'embedded-reveal-view__body__card__statement', children: [jsxRuntime.jsx("div", { className: 'embedded-reveal-view__body__card__icon', children: jsxRuntime.jsx(walletV2.ReactComponent, { height: 16, width: 16 }) }), jsxRuntime.jsxs("div", { className: 'embedded-reveal-view__body__card__statement__text', children: [jsxRuntime.jsxs(Typography.Typography, { variant: 'body_small', color: 'primary', copykey: 'dyn_embedded_reveal.statement_1.title', children: [t('dyn_embedded_reveal.statement_1.title'), ":"] }), jsxRuntime.jsx(Typography.Typography, { variant: 'body_small', color: 'primary', copykey: 'dyn_embedded_reveal.statement_1.description', children: t('dyn_embedded_reveal.statement_1.description') })] })] }), jsxRuntime.jsxs("div", { className: 'embedded-reveal-view__body__card__statement', children: [jsxRuntime.jsx("div", { className: 'embedded-reveal-view__body__card__icon', children: jsxRuntime.jsx(eyeOffIcon.ReactComponent, { height: 16, width: 16 }) }), jsxRuntime.jsx("div", { className: 'embedded-reveal-view__body__card__statement__text', children: jsxRuntime.jsx(Typography.Typography, { variant: 'body_small', color: 'primary', copykey: 'dyn_embedded_reveal.statement_2.title', children: t('dyn_embedded_reveal.statement_2.title') }) })] })] }), jsxRuntime.jsx("div", { className: 'embedded-reveal-view__body__confirm_card', children: jsxRuntime.jsxs("button", { className: 'embedded-reveal-view__body__card__acknowledgement', onClick: () => setIsAcknowledged(!isAcknowledged), children: [jsxRuntime.jsx("div", { children: jsxRuntime.jsx(Checkbox.Checkbox, { checked: isAcknowledged, onChange: () => setIsAcknowledged(!isAcknowledged), className: 'embedded-reveal-view__body__card__statement__checkbox', id: 'export-agreement-checkbox' }) }), jsxRuntime.jsx("div", { children: jsxRuntime.jsx(Typography.Typography, { variant: 'body_small', color: 'primary', style: { letterSpacing: '-0.15px' }, copykey: 'dyn_embedded_reveal.checkbox_label', children: t('dyn_embedded_reveal.checkbox_label') }) })] }) }), jsxRuntime.jsx(NeedHelpSection.NeedHelpSection, { isExport: true, walletCredential: walletCredential }), jsxRuntime.jsxs("div", { className: 'embedded-reveal-view__body__button_section', children: [isPromptForExport && (jsxRuntime.jsx(TypographyButton.TypographyButton, { buttonPadding: 'medium', buttonVariant: 'primary', onClick: () => {
                                                handleAcknowledgeExportPrompt();
                                                setShowAuthFlow(false);
                                            }, dataTestId: 'export-agreement-skip-button', copykey: 'dyn_embedded_reveal.skip_button_label', expanded: true, buttonClassName: 'embedded-reveal-view__body__button', children: t('dyn_embedded_reveal.skip_button_label') })), jsxRuntime.jsx(TypographyButton.TypographyButton, { buttonPadding: 'medium', buttonVariant: 'brand-primary', typographyProps: {
                                                color: 'inherit',
                                            }, onClick: () => handleExportWallet(), disabled: !isAcknowledged, loading: isLoading, dataTestId: 'embedded-reveal-button', copykey: isPromptForExport
                                                ? 'dyn_embedded_reveal.backup_button_label'
                                                : 'dyn_embedded_reveal.reveal_button_label', style: { width: '100%' }, className: 'embedded-reveal-view__body__button', expanded: true, children: isPromptForExport
                                                ? t('dyn_embedded_reveal.backup_button_label')
                                                : t('dyn_embedded_reveal.reveal_button_label') })] })] }))] }) })] }));
};

exports.EmbeddedRevealView = EmbeddedRevealView;
