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

const WalletUpgradeFlowView = ({ wallets, method, onComplete, onCancel, }) => {
    var _a;
    const { setShowAuthFlow, user, environmentId } = useInternalDynamicContext();
    const { upgradeToDynamicWaas } = useDynamicWaas();
    const { t } = useTranslation();
    const { pushView } = useViewContext();
    const [currentWalletIndex, setCurrentWalletIndex] = useState(0);
    const [privateKeyInput, setPrivateKeyInput] = useState('');
    const [iframeContainerRef, setIframeContainerRef] = useState(null);
    const isLastWallet = currentWalletIndex === wallets.length - 1;
    const completedSteps = currentWalletIndex;
    const totalSteps = wallets.length;
    const refresh = 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((wallet) => exportWalletCredential({
        environmentId,
        exportPrivateKey: true,
        handleAcknowledgeExportPrompt: () => { },
        iframeContainerRef: iframeContainerRef,
        isTurnkeyWallet: true,
        isWaasWallet,
        user,
        wallet,
    }), {
        onFailure: (err) => {
            logger.error('Failed to export wallet in upgrade flow', err);
            dynamicEvents.emit('embeddedWalletRevealFailed', err);
        },
    });
    const { mutate: handleUpgradeWallet, isLoading: isUpgrading, error: upgradeError, } = useMutation(() => __awaiter(void 0, void 0, void 0, function* () {
        if (!privateKeyInput.trim()) {
            throw new 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.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 (jsxs("div", { className: 'wallet-upgrade-flow-view', children: [jsx(ModalHeader, { children: jsx(Typography, { as: 'h1', variant: 'title', color: 'primary', children: t('dyn_wallet_upgrade_flow.new_wallet_title') }) }), jsx("div", { className: 'wallet-upgrade-flow-view__content', children: jsx(Typography, { children: t('dyn_wallet_upgrade_flow.new_wallet_coming_soon') }) })] }));
    }
    return (jsxs("div", { className: 'wallet-upgrade-flow-view', children: [jsx(ModalHeader, { children: totalSteps > 1 && (jsx("div", { className: 'wallet-upgrade-flow-view__header', children: jsx("div", { className: 'wallet-upgrade-flow-view__steps', children: Array.from({ length: totalSteps }, (_, index) => (jsxs("div", { className: 'wallet-upgrade-flow-view__step-container', children: [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: [jsx("div", { className: 'wallet-upgrade-flow-view__step-indicator', children: index < completedSteps ? (jsx("div", { className: 'wallet-upgrade-flow-view__step-check', children: "\u2713" })) : (jsx("div", { className: 'wallet-upgrade-flow-view__step-number', children: index + 1 })) }), jsx(Typography, { variant: 'body_small', color: index <= currentWalletIndex ? 'primary' : 'secondary', className: 'wallet-upgrade-flow-view__step-title', children: getStepTitle(index) })] }), index < totalSteps - 1 && (jsx("div", { className: 'wallet-upgrade-flow-view__step-separator' }))] }, index))) }) })) }), jsxs("div", { className: 'wallet-upgrade-flow-view__content', children: [exportError && (jsx(ErrorContainer, { className: 'wallet-upgrade-flow-view__error', children: exportError instanceof Error
                            ? exportError.message
                            : t('dyn_wallet_upgrade_flow.export_failed') })), upgradeError && (jsx(ErrorContainer, { className: 'wallet-upgrade-flow-view__error', children: upgradeError instanceof Error
                            ? upgradeError.message
                            : t('dyn_wallet_upgrade_flow.upgrade_failed') })), jsxs("div", { className: 'wallet-upgrade-flow-view__title-section', children: [jsx(Typography, { as: 'h1', variant: 'title', color: 'primary', children: t('dyn_wallet_upgrade_flow.title') }), jsx(Typography, { color: 'secondary', className: 'wallet-upgrade-flow-view__subtitle', children: t('dyn_wallet_upgrade_flow.copy_private_key_subtitle') })] }), jsxs("div", { className: 'wallet-upgrade-flow-view__export-section', children: [jsx(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') }), jsx(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}`)] }), jsx("div", { className: 'wallet-upgrade-flow-view__input-section', children: jsxs("div", { className: 'wallet-upgrade-flow-view__input-container', children: [jsxs(Typography, { variant: 'body_normal', weight: 'bold', color: 'primary', copykey: 'dyn_embedded_reveal.step_2_title', children: [jsx("span", { className: 'wallet-upgrade-flow__step-description', children: t('dyn_wallet_upgrade_flow.step_2_upgrade_description') }), ' '] }), jsx(Textarea, { id: 'paste-private-key-input', value: privateKeyInput, onChange: (e) => setPrivateKeyInput(e.target.value), variant: 'regular', className: 'wallet-upgrade-flow__paste-input', label: '' })] }) })] }), jsxs("div", { className: 'wallet-upgrade-flow-view__actions', children: [jsx(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') }), jsx(TypographyButton, { buttonVariant: 'tertiary', onClick: handleClose, disabled: isUpgrading, children: t('dyn_wallet_upgrade_flow.cancel') })] })] }));
};

export { WalletUpgradeFlowView };
