'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 walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
var Badge = require('../../../../../components/Badge/Badge.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 backupArrow = require('../../../../../shared/assets/backupArrow.cjs');
var chevronLeft = require('../../../../../shared/assets/chevron-left.cjs');
var exportPrivateKey = require('../../../../../shared/assets/export-private-key.cjs');
var exportRecoveryPhrase = require('../../../../../shared/assets/export-recovery-phrase.cjs');
var lock = require('../../../../../shared/assets/lock.cjs');
require('@dynamic-labs/iconic');
var logger = require('../../../../../shared/logger.cjs');
require('../../../../../events/dynamicEvents.cjs');
require('@dynamic-labs/utils');
require('../../../../../context/CaptchaContext/CaptchaContext.cjs');
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');
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('../../../../../views/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 usePasskeyRecovery = require('../../../../../utils/hooks/usePasskeyRecovery/usePasskeyRecovery.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('../../../../../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('../../../../../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');
require('formik');
require('../../../../../utils/hooks/useSubdomainCheck/useSubdomainCheck.cjs');
require('../../../../../context/WalletGroupContext/WalletGroupContext.cjs');
var DynamicWidgetContext = require('../../../context/DynamicWidgetContext.cjs');
require('../../../../../utils/hooks/useGetMfaToken/useGetMfaToken.cjs');
var useWalletBackup = 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');
var useStepUpAuthentication = require('../../../../../utils/hooks/useStepUpAuthentication/useStepUpAuthentication.cjs');
require('../../../../../context/IpConfigurationContext/IpConfigurationContext.cjs');
require('../../../../../context/ConnectWithOtpContext/ConnectWithOtpContext.cjs');
require('../../../../DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.cjs');
require('../../../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');
var useWalletPassword = require('../../../../../utils/hooks/useWalletPassword/useWalletPassword.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('../../../components/DynamicWidgetHeader/DynamicWidgetHeader.cjs');
require('../../../../../views/TransactionConfirmationView/TransactionConfirmationView.cjs');
require('../../../components/PasskeyCard/PasskeyCard.cjs');
var useEmbeddedReveal = require('../../../../../utils/hooks/useEmbeddedReveal/useEmbeddedReveal.cjs');
var useIsPasswordEncrypted = require('../../../../../utils/hooks/useIsPasswordEncrypted/useIsPasswordEncrypted.cjs');
require('../../CryptoComOnramp/CryptoComOnramp.cjs');
require('../../../../../../index.cjs');
require('../../ManagePasskeysMfaWidgetView/ManagePasskeysMfaWidgetView.cjs');
require('../../ManageTotpMfaWidgetView/ManageTotpMfaWidgetView.cjs');
require('../../ReceiveWalletFunds/ReceiveWalletFunds.cjs');
require('../../../../../store/state/tokenBalances.cjs');
require('../../../../../store/state/multichainBalances.cjs');
require('@dynamic-labs/store');
require('../../../../../shared/utils/functions/getInitialUrl/getInitialUrl.cjs');
var useIsMfaRequiredForAction = require('../../../../../utils/hooks/useIsMfaRequiredForAction/useIsMfaRequiredForAction.cjs');

const EmbeddedWalletExportSection = () => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
    const { t } = reactI18next.useTranslation();
    const { setDynamicWidgetView } = DynamicWidgetContext.useWidgetContext();
    const { primaryWallet, user, projectSettings, setShowAuthFlow } = useInternalDynamicContext.useInternalDynamicContext();
    const { pushView } = ViewContext.useViewContext();
    const { getEOAWallet } = useSmartWallets.useSmartWallets();
    const { setPassword } = useWalletPassword.useWalletPassword();
    const isPasswordEncrypted = useIsPasswordEncrypted.useIsPasswordEncrypted();
    const { initPasskeyRecoveryProcess, shouldInitRecovery } = usePasskeyRecovery.usePasskeyRecovery();
    const { initExportProcess } = useEmbeddedReveal.useEmbeddedReveal();
    const { isStepUpRequired, promptMfa, promptStepUpAuth } = useStepUpAuthentication.useStepUpAuthentication();
    const isMfaRequiredForAction = useIsMfaRequiredForAction.useIsMfaRequiredForAction();
    const eoaWallet = primaryWallet && getEOAWallet(primaryWallet);
    const wallet = eoaWallet !== null && eoaWallet !== void 0 ? eoaWallet : primaryWallet;
    const isEmbeddedWallet = Boolean(wallet &&
        (((_b = (_a = wallet === null || wallet === void 0 ? void 0 : wallet.connector) === null || _a === void 0 ? void 0 : _a.key) === null || _b === void 0 ? void 0 : _b.startsWith('turnkey')) ||
            ((_d = (_c = wallet === null || wallet === void 0 ? void 0 : wallet.connector) === null || _c === void 0 ? void 0 : _c.key) === null || _d === void 0 ? void 0 : _d.startsWith('dynamicwaas'))));
    const turnkeyWalletProperties = (_f = (_e = user === null || user === void 0 ? void 0 : user.verifiedCredentials) === null || _e === void 0 ? void 0 : _e.find(({ walletName, id }) => (walletName === null || walletName === void 0 ? void 0 : walletName.startsWith('turnkey')) &&
        ((primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.id) ? id === (primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.id) : true))) === null || _f === void 0 ? void 0 : _f.walletProperties;
    const isTurnkeyHDWallet = Boolean(turnkeyWalletProperties === null || turnkeyWalletProperties === void 0 ? void 0 : turnkeyWalletProperties.turnkeyHDWalletId);
    const isSessionKeyCompatible = (primaryWallet && walletConnectorCore.isSessionKeyCompatibleWallet(primaryWallet)) ||
        (eoaWallet && walletConnectorCore.isSessionKeyCompatibleWallet(eoaWallet));
    const isV3WaasWallet = Boolean(wallet && ((_h = (_g = wallet === null || wallet === void 0 ? void 0 : wallet.connector) === null || _g === void 0 ? void 0 : _g.key) === null || _h === void 0 ? void 0 : _h.startsWith('dynamicwaas')));
    const shouldShowPasswordSetup = isV3WaasWallet;
    const handlePasscodeClick = React.useCallback(() => {
        setDynamicWidgetView('setup-password', {
            onComplete: (password) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
                if (!(wallet === null || wallet === void 0 ? void 0 : wallet.address) || !(wallet === null || wallet === void 0 ? void 0 : wallet.chain)) {
                    logger.logger.error('No wallet address or chain available for password setup');
                    return;
                }
                yield setPassword({
                    accountAddress: wallet.address,
                    chainName: wallet.chain,
                    newPassword: password,
                });
            }),
        });
    }, [setDynamicWidgetView, wallet, setPassword]);
    const handleResetPasswordClick = React.useCallback(() => {
        setShowAuthFlow(true, {
            ignoreIfIsEmbeddedWidget: false,
            performMultiWalletChecks: false,
        });
        pushView('reset-password-flow');
    }, [setShowAuthFlow, pushView]);
    const handleExportClick = React.useCallback((recoveryPhrase) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        var _l;
        // Pin the primary wallet's id: when the primary wallet is a smart wallet,
        // the derived EOA wallet is not registered in userWallets, so its id
        // would fail EmbeddedRevealView's lookup. The view derives the EOA from
        // the pinned wallet itself.
        const targetWalletId = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.id;
        logger.logger.info('Starting embedded wallet export process', {
            userId: user === null || user === void 0 ? void 0 : user.userId,
            walletId: targetWalletId,
            walletName: (_l = wallet === null || wallet === void 0 ? void 0 : wallet.connector) === null || _l === void 0 ? void 0 : _l.name,
        });
        const stepUpRequired = yield isStepUpRequired({
            scope: sdkApiCore.TokenScope.Walletexport,
        });
        if (stepUpRequired) {
            try {
                yield promptStepUpAuth({
                    requestedScopes: [sdkApiCore.TokenScope.Walletexport],
                });
            }
            catch (_m) {
                return;
            }
        }
        else {
            const isMfaRequired = yield isMfaRequiredForAction({
                mfaAction: sdkApiCore.MFAAction.WalletWaasExport,
            });
            if (isMfaRequired) {
                try {
                    yield promptMfa({ createMfaToken: true });
                }
                catch (_o) {
                    return;
                }
            }
        }
        if (!isSessionKeyCompatible) {
            if (yield shouldInitRecovery()) {
                yield initPasskeyRecoveryProcess(undefined, {
                    type: 'reveal',
                });
            }
        }
        return initExportProcess(recoveryPhrase, false, targetWalletId);
    }), [
        primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.id,
        wallet,
        user,
        isStepUpRequired,
        promptStepUpAuth,
        isMfaRequiredForAction,
        promptMfa,
        shouldInitRecovery,
        initPasskeyRecoveryProcess,
        initExportProcess,
        isSessionKeyCompatible,
    ]);
    const handleExportButtonClick = React.useCallback(() => {
        handleExportClick();
    }, [handleExportClick]);
    const handleExportWithPhraseClick = React.useCallback(() => handleExportClick(true), [handleExportClick]);
    const exportIconClasses = 'settings-view__body__section__button__icon';
    const backupOptions = (_k = (_j = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _j === void 0 ? void 0 : _j.waas) === null || _k === void 0 ? void 0 : _k.backupOptions;
    const isCloudBackupEnabled = Boolean((backupOptions === null || backupOptions === void 0 ? void 0 : backupOptions.includes(sdkApiCore.WaasBackupOptionsEnum.GoogleDrive)) ||
        (backupOptions === null || backupOptions === void 0 ? void 0 : backupOptions.includes(sdkApiCore.WaasBackupOptionsEnum.ICloud)));
    const shouldShowBackupOption = isV3WaasWallet && isCloudBackupEnabled;
    const { areAllWalletsBackedUp } = useWalletBackup.useWalletBackup();
    const handleBackupClick = React.useCallback(() => {
        setShowAuthFlow(true, {
            ignoreIfIsEmbeddedWidget: false,
            performMultiWalletChecks: false,
        });
        pushView(areAllWalletsBackedUp ? 'waas-backup-download-view' : 'waas-backup-view');
    }, [setShowAuthFlow, pushView, areAllWalletsBackedUp]);
    const exportButtonStartSlot = React.useMemo(() => (jsxRuntime.jsxs("div", { className: 'settings-view__body__section__button__start-slot', children: [jsxRuntime.jsx(exportPrivateKey.ReactComponent, { className: exportIconClasses }), jsxRuntime.jsx(Typography.Typography, { color: 'primary', weight: 'medium', copykey: isV3WaasWallet
                    ? 'dyn_settings.export_section.export_button'
                    : 'dyn_settings.export_section.private_key_button', children: isV3WaasWallet
                    ? t('dyn_settings.export_section.export_button')
                    : t('dyn_settings.export_section.private_key_button') })] })), [exportIconClasses, isV3WaasWallet, t]);
    const recoveryPhraseButtonStartSlot = React.useMemo(() => (jsxRuntime.jsxs("div", { className: 'settings-view__body__section__button__start-slot', children: [jsxRuntime.jsx(exportRecoveryPhrase.ReactComponent, { className: exportIconClasses }), jsxRuntime.jsx(Typography.Typography, { color: 'primary', weight: 'medium', copykey: 'dyn_settings.export_section.srp_button', children: t('dyn_settings.export_section.srp_button') })] })), [exportIconClasses, t]);
    if (!isEmbeddedWallet) {
        return null;
    }
    return (jsxRuntime.jsxs("div", { className: 'settings-view__body__section', children: [jsxRuntime.jsx("div", { className: 'settings-view__body__section__title', children: jsxRuntime.jsx(Typography.Typography, { copykey: 'dyn_settings.wallet_security_section.title', color: 'secondary', weight: 'medium', children: t('dyn_settings.wallet_security_section.title') }) }), shouldShowPasswordSetup && (jsxRuntime.jsx(TypographyButton.TypographyButton, { dataTestId: 'password-setup-button', onClick: isPasswordEncrypted ? handleResetPasswordClick : handlePasscodeClick, buttonClassName: 'settings-view__body__section__button', startSlot: 
                // eslint-disable-next-line react/jsx-wrap-multilines
                jsxRuntime.jsxs("div", { className: 'settings-view__body__section__button__start-slot', children: [jsxRuntime.jsx(lock.ReactComponent, { className: 'settings-view__body__section__button__icon' }), jsxRuntime.jsx(Typography.Typography, { color: 'primary', weight: 'medium', copykey: isPasswordEncrypted
                                ? 'dyn_settings.account_security.password.reset_button'
                                : 'dyn_settings.account_security.password.set_button', children: isPasswordEncrypted
                                ? t('dyn_settings.account_security.password.reset_button')
                                : t('dyn_settings.account_security.password.set_button') })] }), endSlot: jsxRuntime.jsx(chevronLeft.ReactComponent, { className: 'settings-view__body__section__button__icon-secondary--rotate' }), showInternalLoading: false })), jsxRuntime.jsx(TypographyButton.TypographyButton, { dataTestId: 'embedded-reveal-account-button', onClick: handleExportButtonClick, buttonClassName: 'settings-view__body__section__button', startSlot: exportButtonStartSlot, endSlot: jsxRuntime.jsx(chevronLeft.ReactComponent, { className: 'settings-view__body__section__button__icon-secondary--rotate' }), showInternalLoading: false }), isTurnkeyHDWallet && !isV3WaasWallet && (jsxRuntime.jsx(TypographyButton.TypographyButton, { dataTestId: 'embedded-reveal-button', onClick: handleExportWithPhraseClick, buttonClassName: 'settings-view__body__section__button', startSlot: recoveryPhraseButtonStartSlot, endSlot: jsxRuntime.jsx(chevronLeft.ReactComponent, { className: 'settings-view__body__section__button__icon-secondary--rotate' }), showInternalLoading: false })), shouldShowBackupOption && (jsxRuntime.jsx(TypographyButton.TypographyButton, { dataTestId: 'backup-button', onClick: handleBackupClick, buttonClassName: 'settings-view__body__section__button', startSlot: 
                // eslint-disable-next-line react/jsx-wrap-multilines
                jsxRuntime.jsxs("div", { className: 'settings-view__body__section__button__start-slot', children: [jsxRuntime.jsx(backupArrow.ReactComponent, { className: exportIconClasses }), jsxRuntime.jsx(Typography.Typography, { color: 'primary', weight: 'medium', copykey: 'dyn_settings.export_section.backup_button', children: t('dyn_settings.export_section.backup_button') })] }), endSlot: areAllWalletsBackedUp ? (jsxRuntime.jsx(Badge.Badge, { variant: 'primary', text: t('dyn_waas.backup.backed_up'), copykey: 'dyn_waas.backup.backed_up' })) : (jsxRuntime.jsx(chevronLeft.ReactComponent, { className: 'settings-view__body__section__button__icon-secondary--rotate' })), showInternalLoading: false }))] }));
};

exports.EmbeddedWalletExportSection = EmbeddedWalletExportSection;
