'use client'
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { useState, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { DynamicError, AccessBlockedError } from '@dynamic-labs/utils';
import { Badge } from '../../../components/Badge/Badge.js';
import { Checkbox } from '../../../components/Checkbox/Checkbox.js';
import { EmbeddedWalletExport } from '../../../components/EmbeddedWalletExport/EmbeddedWalletExport.js';
import { ErrorContainer } from '../../../components/ErrorContainer/ErrorContainer.js';
import { IconButton } from '../../../components/IconButton/IconButton.js';
import { ModalHeader } from '../../../components/ModalHeader/ModalHeader.js';
import { NeedHelpSection } from '../../../components/NeedHelpSection/NeedHelpSection.js';
import { Typography } from '../../../components/Typography/Typography.js';
import { TypographyButton } from '../../../components/TypographyButton/TypographyButton.js';
import '../../../context/DynamicContext/useDynamicContext/useDynamicContext.js';
import { useInternalDynamicContext } from '../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import { useViewContext } from '../../../context/ViewContext/ViewContext.js';
import { dynamicEvents } from '../../../events/dynamicEvents.js';
import { getProperErrorMessage } from '../../../modals/SignMessageConfirmationModal/getProperErrorMessage.js';
import { ReactComponent as SvgClose } from '../../../shared/assets/close.js';
import { ReactComponent as SvgExportEmbeddedHero } from '../../../shared/assets/export-embedded-hero.js';
import { ReactComponent as SvgEyeOffIcon } from '../../../shared/assets/eye-off-icon.js';
import { ReactComponent as SvgInfo } from '../../../shared/assets/info.js';
import { ReactComponent as SvgWalletV2 } from '../../../shared/assets/wallet-v2.js';
import '@dynamic-labs/iconic';
import { logger } from '../../../shared/logger.js';
import { INVALID_WALLET_DATA } from '../../../utils/constants/errors.js';
import { exportWalletCredential } from '../../../utils/functions/exportWalletCredential/exportWalletCredential.js';
import { getTurnkeyWalletId } from '../../../utils/functions/getTurnkeyWalletId/getTurnkeyWalletId.js';
import '../../../../../_virtual/_tslib.js';
import '@dynamic-labs/wallet-connector-core';
import '../../../context/CaptchaContext/CaptchaContext.js';
import '@dynamic-labs/sdk-api-core';
import '../../../context/ErrorContext/ErrorContext.js';
import '@dynamic-labs/wallet-book';
import '../../../utils/constants/colors.js';
import '../../../utils/constants/values.js';
import '../../../shared/consts/index.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../../store/state/nonce/nonce.js';
import '@dynamic-labs-wallet/browser-wallet-client';
import '@dynamic-labs-sdk/client/core';
import 'eventemitter3';
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 '../../../utils/functions/getWaasAddressTypeLabel/getWaasAddressTypeLabel.js';
import '../../../context/AccessDeniedContext/AccessDeniedContext.js';
import '../../../context/AccountExistsContext/AccountExistsContext.js';
import { useUserWalletsExternal } from '../../../context/UserWalletsContext/UserWalletsContext.js';
import '../../../store/state/authMode/authMode.js';
import '../../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '../../../context/VerificationContext/VerificationContext.js';
import 'react-dom';
import '../../../utils/functions/compareChains/compareChains.js';
import '../../Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import '../../../context/ThemeContext/ThemeContext.js';
import { useSmartWallets } from '../../../utils/hooks/useSmartWallets/useSmartWallets.js';
import '../../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.js';
import { useMutation } from '../../../utils/hooks/useMutation/useMutation.js';
import 'bs58';
import '@dynamic-labs/types';
import '../../../context/SocialRedirectContext/SocialRedirectContext.js';
import '../../../context/LoadingContext/LoadingContext.js';
import '../../../context/WalletContext/WalletContext.js';
import { cleanupExport } from '../utils/turnkeyExport/turnkeyExport.js';
import '../../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.js';
import 'yup';
import '../../../context/MockContext/MockContext.js';
import '../../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 '../../../components/Accordion/components/AccordionItem/AccordionItem.js';
import '../../../components/Alert/Alert.js';
import '../../../components/ShadowDOM/ShadowDOM.js';
import '../../../components/InlineWidget/InlineWidget.js';
import '../../../components/Input/Input.js';
import '../../../components/IsBrowser/IsBrowser.js';
import '../../../components/MenuList/Dropdown/Dropdown.js';
import '../../../components/OverlayCard/OverlayCard.js';
import '../../../components/Transition/ZoomTransition/ZoomTransition.js';
import '../../../components/Transition/SlideInUpTransition/SlideInUpTransition.js';
import '../../../components/Transition/OpacityTransition/OpacityTransition.js';
import '../../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.js';
import '../../../components/Popper/Popper/Popper.js';
import '../../../components/Popper/PopperContext/PopperContext.js';
import 'react-focus-lock';
import 'qrcode';
import 'formik';
import '../../../utils/hooks/useSubdomainCheck/useSubdomainCheck.js';
import '../../../context/WalletGroupContext/WalletGroupContext.js';
import { useWidgetContext } from '../../../widgets/DynamicWidget/context/DynamicWidgetContext.js';
import '../../../utils/hooks/useGetMfaToken/useGetMfaToken.js';
import '../../../utils/hooks/useWalletBackup/useWalletBackup.js';
import '../../../utils/hooks/useWalletBackup/BackupError.js';
import '../../../utils/hooks/useWalletBackup/types.js';
import '../../../utils/hooks/useWalletBackup/cloudProviders.js';
import '@hcaptcha/react-hcaptcha';
import '@marsidev/react-turnstile';
import '../../../context/IpConfigurationContext/IpConfigurationContext.js';
import '../../../context/ConnectWithOtpContext/ConnectWithOtpContext.js';
import '../../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.js';
import { cleanupExport as cleanupExport$1 } from '../utils/waasExport/waasExport.js';
import '../../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.js';
import '../../ExchangeWhitelistWarning/ExchangeWhitelistWarning.js';
import '../../../context/ErrorContext/hooks/useErrorText/useErrorText.js';
import '../../../context/FooterAnimationContext/index.js';
import '../../MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.js';
import '../../../context/PasskeyContext/PasskeyContext.js';
import '../../../context/OnrampContext/OnrampContext.js';
import '../../../utils/hooks/useWalletDelegation/DelegationError.js';
import '../../../store/state/sendBalances.js';
import '../../../store/state/connectorsInitializing/connectorsInitializing.js';
import '../../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.js';
import '../../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.js';
import '../../TransactionConfirmationView/TransactionConfirmationView.js';
import '../../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.js';
import '../../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.js';
import '../../../../index.js';
import '../../../widgets/DynamicWidget/views/ManagePasskeysMfaWidgetView/ManagePasskeysMfaWidgetView.js';
import '../../../widgets/DynamicWidget/views/ManageTotpMfaWidgetView/ManageTotpMfaWidgetView.js';
import '../../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.js';
import '../../../store/state/tokenBalances.js';
import '../../../store/state/multichainBalances.js';
import { useSyncEmbeddedWalletFlow } from '../../../utils/hooks/useSyncEmbeddedWalletFlow/useSyncEmbeddedWalletFlow.js';
import '@dynamic-labs/store';
import '../../../shared/utils/functions/getInitialUrl/getInitialUrl.js';

const EmbeddedRevealView = ({ exportPrivateKey, isPromptForExport = false, walletId, }) => {
    var _a, _b, _c, _d, _e;
    const { primaryWallet, user, setShowAuthFlow, environmentId } = useInternalDynamicContext();
    const userWallets = useUserWalletsExternal();
    const { handleAcknowledgeExportPrompt } = 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 } = useWidgetContext();
    const { pushView } = useViewContext();
    const { getEOAWallet, isSmartWallet } = useSmartWallets();
    const [isAcknowledged, setIsAcknowledged] = useState(false);
    const [iframeContainerRef, setIframeContainerRef] = 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 DynamicError('Wallet not found. Please try again.', INVALID_WALLET_DATA);
    }
    const targetWallet = walletFromId !== null && walletFromId !== void 0 ? walletFromId : primaryWallet;
    if (!targetWallet) {
        throw new DynamicError('No primary wallet found', INVALID_WALLET_DATA);
    }
    let primaryTurnkeyWalletId;
    try {
        primaryTurnkeyWalletId = 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
    useEffect(() => {
        return () => {
            if (isTurnkeyWallet) {
                cleanupExport({
                    wallet: wallet,
                });
            }
            if (isWaasWallet) {
                cleanupExport$1({
                    wallet: wallet,
                });
            }
        };
        // only run once on unmount
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);
    const { mutate: handleExportWallet, isLoading, error, data, } = useMutation(() => exportWalletCredential({
        environmentId,
        exportPrivateKey,
        handleAcknowledgeExportPrompt,
        iframeContainerRef: iframeContainerRef,
        isTurnkeyWallet,
        isWaasWallet,
        user,
        wallet,
    }), {
        onFailure: (err) => {
            logger.error('Failed to export', err);
            dynamicEvents.emit('embeddedWalletRevealFailed', err);
        },
    });
    const errorText = useMemo(() => {
        if (!error) {
            return undefined;
        }
        if (error instanceof DynamicError) {
            return error.message;
        }
        try {
            return getProperErrorMessage(error, user);
        }
        catch (e) {
            if (e instanceof AccessBlockedError) {
                pushView('access-blocked');
            }
            return;
        }
    }, [error, pushView, user]);
    const { t } = useTranslation();
    const hasInjectedCredential = !isLoading && data && !error;
    // Track successful reveal for emitting event on unmount
    const revealedWalletRef = useRef(null);
    useEffect(() => {
        if (hasInjectedCredential && wallet) {
            revealedWalletRef.current = wallet;
        }
    }, [hasInjectedCredential, wallet]);
    // Emit success event when user exits the screen after successful reveal
    useEffect(() => () => {
        if (revealedWalletRef.current) {
            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 = (jsx(IconButton, { onClick: () => {
            setShowAuthFlow(false);
        }, type: 'button', children: jsx(SvgClose, {}) }));
    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 && (jsxs("div", { className: 'embedded-reveal-view__zerodev-warning', children: [jsxs("div", { className: 'embedded-reveal-view__zerodev-warning__title-row', children: [jsx(SvgInfo, { className: 'embedded-reveal-view__zerodev-warning__icon' }), jsx(Typography, { variant: 'body_normal', weight: 'bold', copykey: 'dyn_embedded_reveal.aa_warning.title', children: t('dyn_embedded_reveal.aa_warning.title') })] }), jsxs(Typography, { variant: 'body_normal', weight: 'regular', copykey: 'dyn_embedded_reveal.aa_warning.subtitle', children: [t('dyn_embedded_reveal.aa_warning.subtitle'), jsx("button", { onClick: () => {
                            setShowAuthFlow(false);
                            setDynamicWidgetView('send-balance');
                        }, className: 'embedded-reveal-view__zerodev-warning__link-button', children: jsx(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 = (jsx("div", { children: jsx("div", { className: 'embedded-reveal-view__body__description', children: !hasInjectedCredential && (jsx("div", { className: 'embedded-reveal-view__header', children: jsx("div", { className: 'embedded-reveal-view__header__hero', children: jsx(SvgExportEmbeddedHero, {}) }) })) }) }));
    return (jsxs(Fragment, { children: [jsx(ModalHeader, { trailing: isPromptForExport ? null : closeButton, children: jsx(Typography, { as: 'h1', variant: 'title', color: 'primary', "data-testid": 'dynamic-auth-modal-heading', className: 'header__typography', children: title }) }), jsx("div", { className: 'embedded-reveal-view', children: jsxs("div", { className: getBodyClassName(), children: [aaWarning, (!isWaasWallet ||
                            !hasInjectedCredential ||
                            title !== credentialTitle) &&
                            contentHeader, (isTurnkeyWallet || isWaasWallet) && (jsx(EmbeddedWalletExport, { wallet: wallet, isTurnkeyWallet: isTurnkeyWallet, isWaasWallet: isWaasWallet, data: data, onIframeContainerRef: setIframeContainerRef, isVisible: !title.includes('Agree') })), hasInjectedCredential ? (jsxs(Fragment, { children: [jsx(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 && (jsx(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') }))] })) : (jsxs(Fragment, { children: [jsxs("div", { className: 'embedded-reveal-view__body__description', children: [jsx("div", { className: 'embedded-reveal-view__body__badge-container', children: jsx(Badge, { text: t('dyn_embedded_reveal.badge_label'), className: 'embedded-reveal-view__body__badge' }) }), jsx(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 && jsx(ErrorContainer, { children: errorText }), jsxs("div", { className: 'embedded-reveal-view__body__card', children: [jsxs("div", { className: 'embedded-reveal-view__body__card__statement', children: [jsx("div", { className: 'embedded-reveal-view__body__card__icon', children: jsx(SvgWalletV2, { height: 16, width: 16 }) }), jsxs("div", { className: 'embedded-reveal-view__body__card__statement__text', children: [jsxs(Typography, { variant: 'body_small', color: 'primary', copykey: 'dyn_embedded_reveal.statement_1.title', children: [t('dyn_embedded_reveal.statement_1.title'), ":"] }), jsx(Typography, { variant: 'body_small', color: 'primary', copykey: 'dyn_embedded_reveal.statement_1.description', children: t('dyn_embedded_reveal.statement_1.description') })] })] }), jsxs("div", { className: 'embedded-reveal-view__body__card__statement', children: [jsx("div", { className: 'embedded-reveal-view__body__card__icon', children: jsx(SvgEyeOffIcon, { height: 16, width: 16 }) }), jsx("div", { className: 'embedded-reveal-view__body__card__statement__text', children: jsx(Typography, { variant: 'body_small', color: 'primary', copykey: 'dyn_embedded_reveal.statement_2.title', children: t('dyn_embedded_reveal.statement_2.title') }) })] })] }), jsx("div", { className: 'embedded-reveal-view__body__confirm_card', children: jsxs("button", { className: 'embedded-reveal-view__body__card__acknowledgement', onClick: () => setIsAcknowledged(!isAcknowledged), children: [jsx("div", { children: jsx(Checkbox, { checked: isAcknowledged, onChange: () => setIsAcknowledged(!isAcknowledged), className: 'embedded-reveal-view__body__card__statement__checkbox', id: 'export-agreement-checkbox' }) }), jsx("div", { children: jsx(Typography, { variant: 'body_small', color: 'primary', style: { letterSpacing: '-0.15px' }, copykey: 'dyn_embedded_reveal.checkbox_label', children: t('dyn_embedded_reveal.checkbox_label') }) })] }) }), jsx(NeedHelpSection, { isExport: true, walletCredential: walletCredential }), jsxs("div", { className: 'embedded-reveal-view__body__button_section', children: [isPromptForExport && (jsx(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') })), jsx(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') })] })] }))] }) })] }));
};

export { EmbeddedRevealView };
