'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, ErrorCode, DynamicError, sleep } from '@dynamic-labs/utils';
import '@dynamic-labs-sdk/client/core';
import 'eventemitter3';
import '../../../config/ApiEndpoint.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 '../../constants/colors.js';
import '../../constants/values.js';
import { hasPendingMfaAction } from '../../../shared/utils/functions/hasPendingMfaAction/hasPendingMfaAction.js';
import { instrumentAuthLoginFailed } from '../../../shared/utils/functions/instrumentAuthLoginFailed/instrumentAuthLoginFailed.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/locale';
import '../../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../../store/state/primaryWalletId/primaryWalletId.js';
import '../../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../../functions/getWaasAddressTypeLabel/getWaasAddressTypeLabel.js';
import '../../../events/dynamicEvents.js';
import { storeTokenAndUser } from '../../../client/extension/storeTokenAndUser/storeTokenAndUser.js';
import { useProjectSettings } from '../../../client/extension/projectSettings/useProjectSettings/useProjectSettings.js';
import { useAccessDeniedContext } from '../../../context/AccessDeniedContext/AccessDeniedContext.js';
import { useAccountExistsContext } from '../../../context/AccountExistsContext/AccountExistsContext.js';
import '../../../context/DynamicContext/useDynamicContext/useDynamicContext.js';
import { useInternalDynamicContext } from '../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import { useErrorContext } from '../../../context/ErrorContext/ErrorContext.js';
import { useLoadingContext } from '../../../context/LoadingContext/LoadingContext.js';
import { useEmbeddedWallet } from '../useEmbeddedWallet/useEmbeddedWallet.js';
import '../../../context/UserWalletsContext/UserWalletsContext.js';
import '../../../context/WalletContext/WalletContext.js';
import '../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import '../../functions/compareChains/compareChains.js';
import '../../../context/VerificationContext/VerificationContext.js';
import '../useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.js';
import { useHandleAuthenticatedUser } from '../useHandleAuthenticatedUser/useHandleAuthenticatedUser.js';

const sleepToShowSuccessMessage = () => sleep(1500);
const useUserAuth = ({ authMethod, }) => {
    const { handleLogOutWithReason, 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 projectSettings = useProjectSettings();
    const isVerifyResponse = (response) => response.user;
    const cancelAuth = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
        logger.debug('cancelAuth', { authMethod });
        yield handleLogOutWithReason('auth-cancelled');
        clearStackAndPushInitialView();
    }), [authMethod, clearStackAndPushInitialView, handleLogOutWithReason]);
    const handleAuthError = useCallback((error, { options = {}, onError, }) => {
        var _a, _b;
        instrumentAuthLoginFailed(error, {
            authOrigin: 'user-auth',
            provider: authMethod,
        });
        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;
        }
        // Re-throw passkey errors so they propagate to usePromise in the UI
        // This allows error messages to be displayed in ConfirmPasskeyView
        // WebAuthnError is the specific error type thrown by @simplewebauthn/browser
        // for passkey operations (authentication/registration failures)
        // NotAllowedError is the underlying DOMException when user cancels or times out
        if ((error === null || error === void 0 ? void 0 : error.name) === 'NotAllowedError' &&
            (((_b = error === null || error === void 0 ? void 0 : error.constructor) === null || _b === void 0 ? void 0 : _b.name) === 'WebAuthnError' ||
                (error === null || error === void 0 ? void 0 : error.code) === 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY')) {
            throw error;
        }
        // Re-throw passkey registration errors so they propagate to usePromise in the UI
        // InvalidStateError with ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED occurs when
        // a user tries to register a passkey that has already been registered
        if ((error === null || error === void 0 ? void 0 : error.name) === 'InvalidStateError' &&
            (error === null || error === void 0 ? void 0 : error.code) === 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED') {
            throw error;
        }
        if (error.code === ErrorCode.CREDENTIAL_NOT_ENABLED_FOR_SIGN_IN) {
            setError(error.message, error.code);
            return;
        }
        if (onError) {
            onError === null || onError === void 0 ? void 0 : onError(error);
            return;
        }
        if (error.code) {
            setErrorMessage(error.code, error, 'user-auth');
        }
        else {
            setError(error.message);
        }
    }, [
        authMethod,
        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, _c, _d, _e, _f;
        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', '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 walletVersion = embeddedWalletSettingVersion();
            const userHasEmbeddedWallet = (_d = (_c = verifiedUser.verifiedCredentials) === null || _c === void 0 ? void 0 : _c.some((vc) => vc.walletProvider === WalletProviderEnum.EmbeddedWallet)) !== null && _d !== void 0 ? _d : false;
            const shouldKeepAuthFlowOpenForPasswordSetup = walletVersion === EmbeddedWalletVersionEnum.V3 &&
                Boolean((_f = (_e = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _e === void 0 ? void 0 : _e.waas) === null || _f === void 0 ? void 0 : _f.passcodeRequired) &&
                !userHasEmbeddedWallet;
            if (shouldKeepAuthFlowOpenForPasswordSetup) {
                // Keep auth flow open so setup-password can be shown (useSyncDynamicWaas)
            }
            else 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,
        projectSettings,
        setCallback,
        setLoading,
        setMultiWalletWidgetState,
        setShowAuthFlow,
        shouldAutoCreateEmbeddedWallet,
        shouldPromptForKeyExport,
        walletConnectorOptions,
    ]);
    const handleVerifyMissingFields = useCallback((_g) => __awaiter(void 0, [_g], 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((_h) => __awaiter(void 0, [_h], 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 };
