'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { useCallback } from 'react';
import { MfaInvalidOtpError, MfaRateLimitedError, SandboxMaximumThresholdReachedError as SandboxMaximumThresholdReachedError$1 } from '@dynamic-labs-sdk/client';
import { WalletProviderEnum, EmbeddedWalletVersionEnum, MfaBackupCodeAcknowledgement } from '@dynamic-labs/sdk-api-core';
import { EmailAlreadyExistsError, CustomFieldNotUniqueError, UsernameAlreadyExistsError, TooManyEmailVerificationsError, InvalidPhoneNumberError, NoAccessError, AccountExistsError, SandboxMaximumThresholdReachedError, UserHasAccountWithEmailError, DynamicError, sleep } from '@dynamic-labs/utils';
import '@dynamic-labs-sdk/client/core';
import '../../../client/client.js';
import '../../../config/ApiEndpoint.js';
import { VerifiedCredentialNameToChainEnum } from '../../constants/values.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../constants/colors.js';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import 'react/jsx-runtime';
import { useViewContext } from '../../../context/ViewContext/ViewContext.js';
import { logger } from '../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import { hasPendingMfaAction } from '../../../shared/utils/functions/hasPendingMfaAction/hasPendingMfaAction.js';
import '../../../shared/consts/index.js';
import '../../../store/state/nonce/nonce.js';
import '@dynamic-labs/locale';
import '../../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../../store/state/primaryWalletId/primaryWalletId.js';
import '../../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import { getClientSessionSignature } from '../../functions/clientSessionKeys/getClientSessionKeys.js';
import '../../../events/dynamicEvents.js';
import { storeTokenAndUser } from '../../../client/extension/storeTokenAndUser/storeTokenAndUser.js';
import { useAccessDeniedContext } from '../../../context/AccessDeniedContext/AccessDeniedContext.js';
import { useAccountExistsContext } from '../../../context/AccountExistsContext/AccountExistsContext.js';
import '../../../context/DynamicContext/DynamicContext.js';
import '../../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '../../../context/CaptchaContext/CaptchaContext.js';
import { useErrorContext } from '../../../context/ErrorContext/ErrorContext.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 { useLoadingContext } from '../../../context/LoadingContext/LoadingContext.js';
import { useEmbeddedWallet } from '../useEmbeddedWallet/useEmbeddedWallet.js';
import '../../../context/WalletContext/WalletContext.js';
import '../useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.js';
import { useHandleAuthenticatedUser } from '../useHandleAuthenticatedUser/useHandleAuthenticatedUser.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 '../../../shared/utils/functions/getInitialUrl/getInitialUrl.js';
import { useInternalDynamicContext } from '../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';

const sleepToShowSuccessMessage = () => sleep(1500);
const useUserAuth = ({ authMethod, }) => {
    const { handleLogOut, setShowAuthFlow, setCallback, setMultiWalletWidgetState, walletConnectorOptions, } = useInternalDynamicContext();
    const { setDeniedOauthUsername, setDeniedOauthProvider } = useAccessDeniedContext();
    const { view, pushView, clearStackAndPushInitialView } = useViewContext();
    const { setLoading } = useLoadingContext();
    const { setErrorMessage, setError } = useErrorContext();
    const { setExistentAccountData } = useAccountExistsContext();
    const handleAuthenticatedUser = useHandleAuthenticatedUser();
    const { shouldAutoCreateEmbeddedWallet, shouldPromptForKeyExport, embeddedWalletSettingVersion, } = useEmbeddedWallet();
    const isVerifyResponse = (response) => response.user;
    const handleWaasInitialization = useCallback((verifiedUser) => __awaiter(void 0, void 0, void 0, function* () {
        const sessionSignatureResult = yield getClientSessionSignature({
            sessionId: verifiedUser === null || verifiedUser === void 0 ? void 0 : verifiedUser.sessionId,
        });
        const dynamicWaasConnectors = walletConnectorOptions.filter((walletOption) => walletOption.walletConnector.key === 'dynamicwaas');
        dynamicWaasConnectors.forEach((walletOption) => {
            var _a;
            const walletAddress = (_a = verifiedUser.verifiedCredentials.find((credential) => {
                var _a;
                return VerifiedCredentialNameToChainEnum[(_a = credential.chain) !== null && _a !== void 0 ? _a : ''] ===
                    walletOption.walletConnector.connectedChain;
            })) === null || _a === void 0 ? void 0 : _a.address;
            if (walletAddress) {
                // Create the waas iframe
                walletOption.walletConnector
                    .getWaasWalletClient()
                    .then((client) => {
                    // Restore the wallet keyshare to the iframe
                    client
                        .getWallet({
                        accountAddress: walletAddress,
                        signedSessionId: sessionSignatureResult.sessionSignature,
                        walletOperation: 'SIGN_MESSAGE',
                    })
                        .catch((error) => {
                        logger.error('Error restoring wallet keyshare', {
                            error,
                            sessionId: verifiedUser.sessionId,
                            userId: verifiedUser.userId,
                            walletAddress,
                        });
                    });
                })
                    .catch((error) => {
                    logger.error('Error initializing waas wallet client', {
                        error,
                        sessionId: verifiedUser.sessionId,
                        userId: verifiedUser.userId,
                        walletAddress,
                    });
                });
            }
        });
    }), [walletConnectorOptions]);
    const cancelAuth = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
        logger.debug('cancelAuth', { authMethod });
        yield handleLogOut();
        clearStackAndPushInitialView();
    }), [authMethod, clearStackAndPushInitialView, handleLogOut]);
    const handleAuthError = useCallback((error, { options = {}, onError, }) => {
        var _a;
        if (error instanceof MfaInvalidOtpError ||
            error instanceof MfaRateLimitedError) {
            throw error;
        }
        // these get caught in onboarding form and handled there
        if (error instanceof EmailAlreadyExistsError ||
            error instanceof CustomFieldNotUniqueError ||
            error instanceof UsernameAlreadyExistsError ||
            error instanceof TooManyEmailVerificationsError ||
            error instanceof InvalidPhoneNumberError)
            throw error;
        if (error instanceof NoAccessError) {
            setDeniedOauthProvider(error === null || error === void 0 ? void 0 : error.socialProvider);
            setDeniedOauthUsername((_a = error === null || error === void 0 ? void 0 : error.socialUsername) !== null && _a !== void 0 ? _a : '');
            pushView('no-access');
            return;
        }
        if (error instanceof AccountExistsError) {
            setExistentAccountData(error.errorPayload);
            pushView('account-exists');
            return;
        }
        if (error instanceof SandboxMaximumThresholdReachedError ||
            error instanceof SandboxMaximumThresholdReachedError$1) {
            pushView('sandbox-maximum-threshold-reached');
            return;
        }
        // Handle the case where the user has already an account with the email
        if (error instanceof UserHasAccountWithEmailError) {
            pushView('merge-user-accounts-with-same-email', {
                returnToView: 'isEmailRecoveryFlow' in options && options.isEmailRecoveryFlow
                    ? 'passkey-recovery-add-email'
                    : undefined,
            });
            return;
        }
        if (onError) {
            onError === null || onError === void 0 ? void 0 : onError(error);
            return;
        }
        if (error.code) {
            setErrorMessage(error.code);
        }
        else {
            setError(error.message);
        }
    }, [
        pushView,
        setDeniedOauthProvider,
        setDeniedOauthUsername,
        setError,
        setErrorMessage,
        setExistentAccountData,
    ]);
    const initAuth = useCallback((_a) => __awaiter(void 0, [_a], void 0, function* ({ isSignIn = true, verifyFunction, onVerifySuccess, onSettled, onError, showSuccessMessage = false, skipDefaultErrorHandling = false, }) {
        var _b;
        logger.debug('initAuth', { authMethod, isSignIn });
        try {
            // TODO: change this logic to const verifiedUser = await verifyFunction();
            // once all verify functions are updated to return UserProfile instead of VerifyResponse
            const verifyResponse = yield verifyFunction();
            if (!verifyResponse) {
                yield cancelAuth();
                throw new DynamicError('No user returned from verify function');
            }
            let verifiedUser;
            if (isVerifyResponse(verifyResponse)) {
                verifiedUser = storeTokenAndUser(verifyResponse);
            }
            else {
                verifiedUser = verifyResponse;
            }
            onVerifySuccess === null || onVerifySuccess === void 0 ? void 0 : onVerifySuccess(verifiedUser);
            walletConnectorOptions.forEach((walletOption) => {
                walletOption.walletConnector.setVerifiedCredentials(verifiedUser.verifiedCredentials);
            });
            if (hasPendingMfaAction(verifiedUser)) {
                // handled in SyncAuthFlow
                return;
            }
            if (isSignIn && ((_b = verifiedUser.missingFields) === null || _b === void 0 ? void 0 : _b.length)) {
                //onboarding will be handled in the onboarding flow
                return;
            }
            setMultiWalletWidgetState('idle');
            yield handleAuthenticatedUser(verifiedUser);
            // we should only close auth flow if no wallet is going to be created or there is no key export
            // otherwise there will be a glitch with auth flow closing and then reopening for passkeys or export
            const shouldCreateWallet = shouldAutoCreateEmbeddedWallet();
            // only support export prompt on v2 and higher
            const shouldPromptExport = shouldPromptForKeyExport();
            if (showSuccessMessage) {
                // this timeout is set to make sure that the user will see success message
                yield sleepToShowSuccessMessage();
            }
            if (isSignIn) {
                setCallback('authSuccess');
                const hasWaasWallets = verifiedUser.verifiedCredentials.some((vc) => vc.walletProvider === WalletProviderEnum.EmbeddedWallet &&
                    vc.walletName === 'dynamicwaas');
                if (hasWaasWallets) {
                    // Eagerly initialize waas wallets
                    yield handleWaasInitialization(verifiedUser);
                }
            }
            const walletVersion = embeddedWalletSettingVersion();
            if (walletVersion === EmbeddedWalletVersionEnum.V1 &&
                shouldCreateWallet) {
                setShowAuthFlow(true);
            }
            else if (!shouldCreateWallet || !shouldPromptExport) {
                setShowAuthFlow(false);
            }
            onSettled === null || onSettled === void 0 ? void 0 : onSettled();
        }
        catch (error) {
            logger.debug(error);
            if (skipDefaultErrorHandling) {
                onError === null || onError === void 0 ? void 0 : onError(error);
                return;
            }
            handleAuthError(error, { onError });
        }
        finally {
            setLoading(false);
            onSettled === null || onSettled === void 0 ? void 0 : onSettled();
        }
    }), [
        authMethod,
        cancelAuth,
        embeddedWalletSettingVersion,
        handleAuthError,
        handleAuthenticatedUser,
        handleWaasInitialization,
        setCallback,
        setLoading,
        setMultiWalletWidgetState,
        setShowAuthFlow,
        shouldAutoCreateEmbeddedWallet,
        shouldPromptForKeyExport,
        walletConnectorOptions,
    ]);
    const handleVerifyMissingFields = useCallback((_c) => __awaiter(void 0, [_c], void 0, function* ({ missingFields, isEmailVerificationRequired, isSmsVerificationRequired, }) {
        if (isEmailVerificationRequired &&
            missingFields.find((field) => field.name === 'email')) {
            pushView('verify-email');
            return;
        }
        if (isSmsVerificationRequired &&
            missingFields.find((field) => field.name === 'phoneNumber')) {
            pushView('verify-sms');
            return;
        }
        pushView(view.type);
    }), [pushView, view === null || view === void 0 ? void 0 : view.type]);
    const completeAuth = useCallback((_d) => __awaiter(void 0, [_d], void 0, function* ({ completeSignInFlow, updateJwtFunction, onValidUpdatedJwt, options = {}, }) {
        logger.debug('completeAuth', { authMethod });
        try {
            const { updateUserProfileResponse, isSmsVerificationRequired, isEmailVerificationRequired, missingFields, } = yield updateJwtFunction();
            onValidUpdatedJwt === null || onValidUpdatedJwt === void 0 ? void 0 : onValidUpdatedJwt();
            const updatedUser = storeTokenAndUser({
                expiresAt: updateUserProfileResponse.expiresAt,
                jwt: updateUserProfileResponse.jwt,
                minifiedJwt: updateUserProfileResponse.minifiedJwt,
                user: updateUserProfileResponse.user,
            });
            if (missingFields.length > 0) {
                yield handleVerifyMissingFields({
                    isEmailVerificationRequired,
                    isSmsVerificationRequired,
                    missingFields,
                });
                return;
            }
            yield handleAuthenticatedUser(updatedUser);
            setCallback('authSuccess');
            if (completeSignInFlow) {
                const shouldReturn = yield completeSignInFlow(updateUserProfileResponse);
                if (shouldReturn) {
                    return;
                }
            }
            // we should only close auth flow if no wallet is going to be created,
            // otherwise there will be a glitch with auth flow closing and then reopening for passkeys
            const shouldCreateWallet = shouldAutoCreateEmbeddedWallet();
            if (!shouldCreateWallet &&
                updatedUser.mfaBackupCodeAcknowledgement !==
                    MfaBackupCodeAcknowledgement.Pending) {
                setShowAuthFlow(false);
            }
        }
        catch (error) {
            logger.debug(error);
            handleAuthError(error, { options });
        }
        finally {
            setLoading(false);
        }
    }), [
        authMethod,
        handleAuthError,
        handleAuthenticatedUser,
        handleVerifyMissingFields,
        setCallback,
        setLoading,
        setShowAuthFlow,
        shouldAutoCreateEmbeddedWallet,
    ]);
    return {
        cancelAuth,
        completeAuth,
        handleAuthError,
        initAuth,
    };
};

export { useUserAuth };
