'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { useCallback } from 'react';
import { onEvent } from '@dynamic-labs-sdk/client';
import { MFADeviceType } from '@dynamic-labs/sdk-api-core';
import { DeferredPromise } from '@dynamic-labs/utils';
import { useGetUserMfaMethods } from '../useGetUserMfaMethods/useGetUserMfaMethods.js';
import { useViewContext } from '../../../context/ViewContext/ViewContext.js';
import '../../../context/DynamicContext/DynamicContext.js';
import '../../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import 'react/jsx-runtime';
import '../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '../../constants/colors.js';
import '../../constants/values.js';
import '../../../shared/consts/index.js';
import { dynamicEvents } from '../../../events/dynamicEvents.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 { useDynamicClient } from '../../../client/client.js';
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 '../../../context/AccessDeniedContext/AccessDeniedContext.js';
import '../../../context/AccountExistsContext/AccountExistsContext.js';
import '../../../context/UserWalletsContext/UserWalletsContext.js';
import '../../../store/state/authMode/authMode.js';
import '../../../context/VerificationContext/VerificationContext.js';
import 'react-dom';
import '../../functions/compareChains/compareChains.js';
import '../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import '../../../context/ThemeContext/ThemeContext.js';
import '../useUserUpdateRequest/useUpdateUser/userFieldsSchema.js';
import 'bs58';
import '@dynamic-labs/types';
import '../../../context/SocialRedirectContext/SocialRedirectContext.js';
import '../../../context/LoadingContext/LoadingContext.js';
import '../../../context/WalletContext/WalletContext.js';
import '../useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.js';
import 'yup';
import '../../../context/MockContext/MockContext.js';
import '../../../views/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 'react-i18next';
import '../../../components/Accordion/components/AccordionItem/AccordionItem.js';
import '../../../components/Alert/Alert.js';
import '../../../components/ShadowDOM/ShadowDOM.js';
import '../../../components/IconButton/IconButton.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 '../useSubdomainCheck/useSubdomainCheck.js';
import '../../../context/WalletGroupContext/WalletGroupContext.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 '../../../widgets/DynamicWidget/context/DynamicWidgetContext.js';
import '../../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.js';
import '../../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.js';
import '../../../context/ErrorContext/hooks/useErrorText/useErrorText.js';
import '../../../context/FooterAnimationContext/index.js';
import '../../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.js';
import '../../../context/PasskeyContext/PasskeyContext.js';
import '../../../context/OnrampContext/OnrampContext.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 '../../../views/TransactionConfirmationView/TransactionConfirmationView.js';
import '../../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.js';
import '../../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.js';
import '../../../../index.js';
import '../../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.js';
import '../../../store/state/tokenBalances.js';
import '../../../store/state/multichainBalances.js';
import { useAuthenticatePasskeyMFA } from '../useAuthenticatePasskeyMFA/useAuthenticatePasskeyMFA.js';
import '../../../shared/utils/functions/getInitialUrl/getInitialUrl.js';
import { useInternalDynamicContext } from '../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';

const usePromptMfaAuth = () => {
    const { setShowAuthFlow } = useInternalDynamicContext();
    const { pushView } = useViewContext();
    const getUserMfaMethods = useGetUserMfaMethods();
    const authenticatePasskeyMFA = useAuthenticatePasskeyMFA();
    const dynamicClient = useDynamicClient();
    const promptMfaAuth = useCallback((props) => __awaiter(void 0, void 0, void 0, function* () {
        const methods = yield getUserMfaMethods();
        const allMethods = [
            ...methods.passkeys.map((passkey) => (Object.assign(Object.assign({}, passkey), { type: MFADeviceType.Passkey }))),
            ...methods.devices.map((device) => (Object.assign(Object.assign({}, device), { type: MFADeviceType.Totp }))),
        ];
        if (!methods.userHasVerifiedMfaMethods || allMethods.length === 0) {
            setShowAuthFlow(true);
            pushView('mfa-choose-device', {
                createMfaToken: props === null || props === void 0 ? void 0 : props.createMfaToken,
            });
            return;
        }
        const lastCreatedMethod = allMethods.reduce((a, b) => {
            if (a.createdAt && b.createdAt) {
                return a.createdAt >= b.createdAt ? a : b;
            }
            if (b.createdAt) {
                return b;
            }
            return a;
        });
        switch (lastCreatedMethod.type) {
            case MFADeviceType.Passkey: {
                const createMfaTokenOptions = (props === null || props === void 0 ? void 0 : props.createMfaToken)
                    ? { singleUse: true }
                    : undefined;
                // we're calling authenticatePasskeyMFA here because we don't want
                // it to be called twice by the usePromise in the confirmPasskey view
                const authenticatePasskeyPromise = authenticatePasskeyMFA({
                    createMfaToken: createMfaTokenOptions,
                });
                setShowAuthFlow(true);
                pushView('passkey-confirm', {
                    authenticatePasskeyPromise,
                    createMfaToken: props === null || props === void 0 ? void 0 : props.createMfaToken,
                });
                // Return the promise so callers can await MFA completion
                return authenticatePasskeyPromise;
            }
            case MFADeviceType.Totp: {
                if (dynamicClient === null || dynamicClient === void 0 ? void 0 : dynamicClient.mfaToken) {
                    return dynamicClient === null || dynamicClient === void 0 ? void 0 : dynamicClient.mfaToken;
                }
                // If the mfaToken is not present, we need to open the MFA UI and wait for it to be available
                const deferred = new DeferredPromise();
                // Open the MFA UI if the mfaToken is not available yet
                setShowAuthFlow(true);
                pushView('mfa-verification', {
                    createMfaToken: props === null || props === void 0 ? void 0 : props.createMfaToken,
                });
                const mfaCompletionSuccessOff = onEvent({
                    event: 'mfaCompletionSuccess',
                    listener: ({ mfaToken }) => deferred.resolve(mfaToken),
                }, dynamicClient);
                // Reject the promise if the auth flow is closed
                const onAuthFlowCloseHandler = () => deferred.reject(new Error('MFA view closed'));
                dynamicEvents.on('authFlowClose', onAuthFlowCloseHandler);
                // Cleanup the event listeners
                deferred.promise.finally(() => {
                    mfaCompletionSuccessOff();
                    dynamicEvents.off('authFlowClose', onAuthFlowCloseHandler);
                });
                return deferred.promise;
            }
            default:
                throw new Error('Error determining MFA method to use');
        }
    }), [
        authenticatePasskeyMFA,
        dynamicClient,
        getUserMfaMethods,
        pushView,
        setShowAuthFlow,
    ]);
    return promptMfaAuth;
};

export { usePromptMfaAuth };
