'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 utils = require('@dynamic-labs/utils');
require('../../components/Accordion/components/AccordionItem/AccordionItem.cjs');
require('@dynamic-labs/iconic');
var ViewContext = require('../../context/ViewContext/ViewContext.cjs');
require('@dynamic-labs/wallet-connector-core');
var logger = require('../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('../../utils/constants/colors.cjs');
require('../../utils/constants/values.cjs');
require('@dynamic-labs/sdk-api-core');
require('../../shared/consts/index.cjs');
require('../../components/Alert/Alert.cjs');
var dynamicEvents = require('../../events/dynamicEvents.cjs');
require('../../context/DynamicContext/DynamicContext.cjs');
require('../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('../../store/state/authMode/authMode.cjs');
var useInternalDynamicContext = require('../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.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');
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');
var exportWalletCredential = require('../../utils/functions/exportWalletCredential/exportWalletCredential.cjs');
require('../../context/AccessDeniedContext/AccessDeniedContext.cjs');
require('../../context/AccountExistsContext/AccountExistsContext.cjs');
require('../../context/UserWalletsContext/UserWalletsContext.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');
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');
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');
var Typography = require('../../components/Typography/Typography.cjs');
require('../../context/FooterAnimationContext/index.cjs');
require('../../components/ShadowDOM/ShadowDOM.cjs');
require('../../components/Transition/ZoomTransition/ZoomTransition.cjs');
require('../../components/Transition/SlideInUpTransition/SlideInUpTransition.cjs');
require('../../components/Transition/OpacityTransition/OpacityTransition.cjs');
require('../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.cjs');
require('../../context/WalletGroupContext/WalletGroupContext.cjs');
require('../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.cjs');
require('react-focus-lock');
require('../../widgets/DynamicWidget/context/DynamicWidgetContext.cjs');
var ErrorContainer = require('../../components/ErrorContainer/ErrorContainer.cjs');
require('../../components/IconButton/IconButton.cjs');
var ModalHeader = require('../../components/ModalHeader/ModalHeader.cjs');
var TypographyButton = require('../../components/TypographyButton/TypographyButton.cjs');
var useRefreshUser = require('../../utils/hooks/useRefreshUser/useRefreshUser.cjs');
var useDynamicWaas = require('../../utils/hooks/useDynamicWaas/useDynamicWaas.cjs');
require('../../components/MenuList/Dropdown/Dropdown.cjs');
require('formik');
require('../../utils/hooks/useSubdomainCheck/useSubdomainCheck.cjs');
require('../../store/state/sendBalances.cjs');
require('../../components/Input/Input.cjs');
require('../../components/OverlayCard/OverlayCard.cjs');
require('../TransactionConfirmationView/TransactionConfirmationView.cjs');
require('../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.cjs');
require('../../context/PasskeyContext/PasskeyContext.cjs');
require('../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.cjs');
require('../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.cjs');
require('../../context/OnrampContext/OnrampContext.cjs');
require('../../../index.cjs');
require('../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.cjs');
require('qrcode');
require('../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.cjs');
var Textarea = require('../../components/Textarea/Textarea.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('../ExchangeWhitelistWarning/ExchangeWhitelistWarning.cjs');
require('../../context/ErrorContext/hooks/useErrorText/useErrorText.cjs');
require('../MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.cjs');
require('../../store/state/connectorsInitializing/connectorsInitializing.cjs');
require('../../store/state/tokenBalances.cjs');
require('../../store/state/multichainBalances.cjs');
require('../../shared/utils/functions/getInitialUrl/getInitialUrl.cjs');
var EmbeddedWalletExport = require('../../components/EmbeddedWalletExport/EmbeddedWalletExport.cjs');
require('../../components/InlineWidget/InlineWidget.cjs');
require('../../components/IsBrowser/IsBrowser.cjs');
require('../../components/Popper/Popper/Popper.cjs');
require('../../components/Popper/PopperContext/PopperContext.cjs');

const WalletUpgradeFlowView = ({ wallets, method, onComplete, onCancel, }) => {
    var _a;
    const { setShowAuthFlow, user, environmentId } = useInternalDynamicContext.useInternalDynamicContext();
    const { upgradeToDynamicWaas } = useDynamicWaas.useDynamicWaas();
    const { t } = reactI18next.useTranslation();
    const { pushView } = ViewContext.useViewContext();
    const [currentWalletIndex, setCurrentWalletIndex] = React.useState(0);
    const [privateKeyInput, setPrivateKeyInput] = React.useState('');
    const [iframeContainerRef, setIframeContainerRef] = React.useState(null);
    const isLastWallet = currentWalletIndex === wallets.length - 1;
    const completedSteps = currentWalletIndex;
    const totalSteps = wallets.length;
    const refresh = useRefreshUser.useRefreshUser();
    // Check if current wallet is a WaaS wallet based on its properties
    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 onExportReady = (isReady, wallet) => {
        if (isReady) {
            handleExportWallet(wallet);
        }
    };
    const { mutate: handleExportWallet, data: exportData, error: exportError, } = useMutation.useMutation((wallet) => exportWalletCredential.exportWalletCredential({
        environmentId,
        exportPrivateKey: true,
        handleAcknowledgeExportPrompt: () => { },
        iframeContainerRef: iframeContainerRef,
        isTurnkeyWallet: true,
        isWaasWallet,
        user,
        wallet,
    }), {
        onFailure: (err) => {
            logger.logger.error('Failed to export wallet in upgrade flow', err);
            dynamicEvents.dynamicEvents.emit('embeddedWalletRevealFailed', err);
        },
    });
    const { mutate: handleUpgradeWallet, isLoading: isUpgrading, error: upgradeError, } = useMutation.useMutation(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        if (!privateKeyInput.trim()) {
            throw new utils.DynamicError('Private key is required');
        }
        yield upgradeToDynamicWaas({
            privateKey: privateKeyInput.trim(),
            wallet: wallets[currentWalletIndex],
        });
        setIframeContainerRef(null);
        setPrivateKeyInput('');
        refresh();
        if (isLastWallet) {
            onComplete === null || onComplete === void 0 ? void 0 : onComplete();
            pushView('account-upgraded');
        }
        else {
            setCurrentWalletIndex((prev) => prev + 1);
        }
    }), {
        onFailure: () => {
            logger.logger.error('Failed to upgrade wallet in upgrade flow');
        },
    });
    const handleClose = () => {
        onCancel === null || onCancel === void 0 ? void 0 : onCancel();
        setShowAuthFlow(false);
    };
    const getStepTitle = (stepIndex) => {
        var _a;
        const walletName = ((_a = wallets[stepIndex]) === null || _a === void 0 ? void 0 : _a.chain) || 'Wallet';
        return t('dyn_wallet_upgrade_flow.step_wallet_upgrade', { walletName });
    };
    if (!wallets[currentWalletIndex]) {
        return null;
    }
    if (method === 'new') {
        // For 'new' method, we would implement fresh wallet creation
        // This is a placeholder for now
        return (jsxRuntime.jsxs("div", { className: 'wallet-upgrade-flow-view', children: [jsxRuntime.jsx(ModalHeader.ModalHeader, { children: jsxRuntime.jsx(Typography.Typography, { as: 'h1', variant: 'title', color: 'primary', children: t('dyn_wallet_upgrade_flow.new_wallet_title') }) }), jsxRuntime.jsx("div", { className: 'wallet-upgrade-flow-view__content', children: jsxRuntime.jsx(Typography.Typography, { children: t('dyn_wallet_upgrade_flow.new_wallet_coming_soon') }) })] }));
    }
    return (jsxRuntime.jsxs("div", { className: 'wallet-upgrade-flow-view', children: [jsxRuntime.jsx(ModalHeader.ModalHeader, { children: totalSteps > 1 && (jsxRuntime.jsx("div", { className: 'wallet-upgrade-flow-view__header', children: jsxRuntime.jsx("div", { className: 'wallet-upgrade-flow-view__steps', children: Array.from({ length: totalSteps }, (_, index) => (jsxRuntime.jsxs("div", { className: 'wallet-upgrade-flow-view__step-container', children: [jsxRuntime.jsxs("div", { className: `wallet-upgrade-flow-view__step ${index < completedSteps
                                        ? 'wallet-upgrade-flow-view__step--completed'
                                        : ''} ${index === currentWalletIndex
                                        ? 'wallet-upgrade-flow-view__step--current'
                                        : ''}`, children: [jsxRuntime.jsx("div", { className: 'wallet-upgrade-flow-view__step-indicator', children: index < completedSteps ? (jsxRuntime.jsx("div", { className: 'wallet-upgrade-flow-view__step-check', children: "\u2713" })) : (jsxRuntime.jsx("div", { className: 'wallet-upgrade-flow-view__step-number', children: index + 1 })) }), jsxRuntime.jsx(Typography.Typography, { variant: 'body_small', color: index <= currentWalletIndex ? 'primary' : 'secondary', className: 'wallet-upgrade-flow-view__step-title', children: getStepTitle(index) })] }), index < totalSteps - 1 && (jsxRuntime.jsx("div", { className: 'wallet-upgrade-flow-view__step-separator' }))] }, index))) }) })) }), jsxRuntime.jsxs("div", { className: 'wallet-upgrade-flow-view__content', children: [exportError && (jsxRuntime.jsx(ErrorContainer.ErrorContainer, { className: 'wallet-upgrade-flow-view__error', children: exportError instanceof Error
                            ? exportError.message
                            : t('dyn_wallet_upgrade_flow.export_failed') })), upgradeError && (jsxRuntime.jsx(ErrorContainer.ErrorContainer, { className: 'wallet-upgrade-flow-view__error', children: upgradeError instanceof Error
                            ? upgradeError.message
                            : t('dyn_wallet_upgrade_flow.upgrade_failed') })), jsxRuntime.jsxs("div", { className: 'wallet-upgrade-flow-view__title-section', children: [jsxRuntime.jsx(Typography.Typography, { as: 'h1', variant: 'title', color: 'primary', children: t('dyn_wallet_upgrade_flow.title') }), jsxRuntime.jsx(Typography.Typography, { color: 'secondary', className: 'wallet-upgrade-flow-view__subtitle', children: t('dyn_wallet_upgrade_flow.copy_private_key_subtitle') })] }), jsxRuntime.jsxs("div", { className: 'wallet-upgrade-flow-view__export-section', children: [jsxRuntime.jsx(Typography.Typography, { color: 'primary', variant: 'body_normal', weight: 'bold', className: 'wallet-upgrade-flow-view__section-title', children: t('dyn_wallet_upgrade_flow.copy_private_key_title') }), jsxRuntime.jsx(EmbeddedWalletExport.EmbeddedWalletExport, { wallet: wallets[currentWalletIndex], isTurnkeyWallet: true, isWaasWallet: isWaasWallet, data: exportData, onIframeContainerRef: setIframeContainerRef, onExportReady: onExportReady }, `wallet-export-${currentWalletIndex}-${(_a = wallets[currentWalletIndex]) === null || _a === void 0 ? void 0 : _a.id}`)] }), jsxRuntime.jsx("div", { className: 'wallet-upgrade-flow-view__input-section', children: jsxRuntime.jsxs("div", { className: 'wallet-upgrade-flow-view__input-container', children: [jsxRuntime.jsxs(Typography.Typography, { variant: 'body_normal', weight: 'bold', color: 'primary', copykey: 'dyn_embedded_reveal.step_2_title', children: [jsxRuntime.jsx("span", { className: 'wallet-upgrade-flow__step-description', children: t('dyn_wallet_upgrade_flow.step_2_upgrade_description') }), ' '] }), jsxRuntime.jsx(Textarea.Textarea, { id: 'paste-private-key-input', value: privateKeyInput, onChange: (e) => setPrivateKeyInput(e.target.value), variant: 'regular', className: 'wallet-upgrade-flow__paste-input', label: '' })] }) })] }), jsxRuntime.jsxs("div", { className: 'wallet-upgrade-flow-view__actions', children: [jsxRuntime.jsx(TypographyButton.TypographyButton, { buttonVariant: 'brand-primary', onClick: () => handleUpgradeWallet(), disabled: !privateKeyInput.trim() || isUpgrading, loading: isUpgrading, copykey: 'dyn_wallet_upgrade_flow.upgrade_button', typographyProps: {
                            color: 'inherit',
                        }, expanded: true, children: t('dyn_wallet_upgrade_flow.upgrade_wallet') }), jsxRuntime.jsx(TypographyButton.TypographyButton, { buttonVariant: 'tertiary', onClick: handleClose, disabled: isUpgrading, children: t('dyn_wallet_upgrade_flow.cancel') })] })] }));
};

exports.WalletUpgradeFlowView = WalletUpgradeFlowView;
