'use client'
import { __awaiter } from '../../../../../../_virtual/_tslib.js';
import { DeferredPromise, StorageService, SdkErrorCode, CustomError, GetAddressCancelledError } from '@dynamic-labs/utils';
import { isEmailWalletConnector, isEmailOTPWalletConnector, isBloctoConnector, getWalletProvider, isSameAddress } from '@dynamic-labs/wallet-connector-core';
import { useCaptchaContext } from '../../../../context/CaptchaContext/CaptchaContext.js';
import { isCaptchaEnabled } from '../../../captcha.js';
import '../../../../context/DynamicContext/useDynamicContext/useDynamicContext.js';
import { useInternalDynamicContext } from '../../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import { useErrorContext } from '../../../../context/ErrorContext/ErrorContext.js';
import { useViewContext } from '../../../../context/ViewContext/ViewContext.js';
import '@dynamic-labs/iconic';
import 'react';
import 'react/jsx-runtime';
import { logger } from '../../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import { LAST_USED_WALLET } from '../../../constants/localStorage.js';
import '../../../constants/colors.js';
import '../../../constants/values.js';
import '@dynamic-labs/sdk-api-core';
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 { isProgrammableNetworkSwitchSupported } from '../../../functions/isProgrammableNetworkSwitchSupported/isProgrammableNetworkSwitchSupported.js';
import { isSupportedNetwork } from '../../../functions/isSupportedNetwork/isSupportedNetwork.js';
import '@dynamic-labs-wallet/browser-wallet-client';
import '@dynamic-labs-sdk/client/core';
import 'eventemitter3';
import '@dynamic-labs-sdk/client';
import '../../../../config/ApiEndpoint.js';
import { dynamicEvents } from '../../../../events/dynamicEvents.js';
import { getUserProfile } from '../../../../client/extension/user/getUserProfile/getUserProfile.js';
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 { useHandleWalletsToConnect } from '../../useHandleWalletsToConnect/useHandleWalletsToConnect.js';
import { useVerifyWallet } from '../../useVerifyWallet/useVerifyWallet.js';
import { showPendingConnectView } from '../helpers/showPendingConnectView.js';
import { isConnectOnly } from '../helpers/isConnectOnly.js';
import { setIsInitialWalletVerificationInProgress } from '../../../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import { unsetInitialWalletVerificationFlag, unsetInitialWalletVerificationFlagWithTimeout } from './unsetInitialWalletVerificationFlag/unsetInitialWalletVerificationFlag.js';

const useConnectAndSign = ({ shouldUpdateWallets = true, shouldCallCallback = true, } = {}) => {
    const { pushView, clearStackAndPushInitialView, replaceView } = useViewContext();
    const { engageCaptcha, getCaptchaToken } = useCaptchaContext();
    const { setErrorMessage, setError, setDefaultError } = useErrorContext();
    const { connectWallet, displaySiweStatement, environmentId, projectSettings, networkValidationMode, setIsSingleWalletAccount, setShowAuthFlow, walletUiUtils, } = useInternalDynamicContext();
    const { handleWalletsToConnect } = useHandleWalletsToConnect();
    const verifyWallet = useVerifyWallet({
        displaySiweStatement,
        environmentId,
        projectSettings,
        setIsSingleWalletAccount,
    });
    const handleWalletVerify = (walletConnector, publicWalletAddress, captchaToken, requestedScopes) => __awaiter(void 0, void 0, void 0, function* () {
        if (!isEmailWalletConnector(walletConnector) ||
            isBloctoConnector(walletConnector)) {
            replaceView('pending-signature');
            setShowAuthFlow(true);
        }
        else {
            walletUiUtils.disabledConfirmationOnce();
        }
        return verifyWallet({
            captchaToken,
            publicWalletAddress,
            requestedScopes,
            walletConnector,
        });
    });
    const handleWalletVerifyError = (err) => {
        var _a;
        const userCancelled = (err === null || err === void 0 ? void 0 : err.code) === SdkErrorCode.USER_CANCELLED;
        if (!userCancelled)
            logger.debug(err);
        instrumentAuthLoginFailed(err, {
            authOrigin: 'connect-and-sign',
            stage: 'verify',
        });
        clearStackAndPushInitialView();
        if (err instanceof CustomError) {
            setError(err.message, err.code);
        }
        else {
            setErrorMessage((_a = err === null || err === void 0 ? void 0 : err.code) === null || _a === void 0 ? void 0 : _a.toString(), err, 'connect-and-sign:verify');
        }
    };
    const handleWalletConnectionError = (error) => {
        if (error instanceof GetAddressCancelledError) {
            return;
        }
        instrumentAuthLoginFailed(error, {
            authOrigin: 'connect-and-sign',
            stage: 'connect',
        });
        clearStackAndPushInitialView();
        if (error instanceof CustomError) {
            setError(error.message, error.code);
        }
        else {
            setDefaultError(error);
        }
    };
    return (_a) => __awaiter(void 0, [_a], void 0, function* ({ walletConnector, getAddressOpts = undefined, requestedScopes, }) {
        const connectionCancelPromise = new DeferredPromise();
        const onGoBack = () => __awaiter(void 0, void 0, void 0, function* () {
            setIsInitialWalletVerificationInProgress(false);
            connectionCancelPromise.reject(new GetAddressCancelledError());
        });
        try {
            dynamicEvents.on('goBack', onGoBack);
            dynamicEvents.on('authFlowClose', onGoBack);
            dynamicEvents.once('walletAdded', unsetInitialWalletVerificationFlag);
            // Lock the variable that indicates that the login wallet verification is in progress
            // Read UserWalletsContext.tsx explanation for more context
            setIsInitialWalletVerificationInProgress(true);
            yield showPendingConnectView(walletConnector, pushView);
            if (isEmailWalletConnector(walletConnector)) {
                if (isEmailOTPWalletConnector(walletConnector)) {
                    pushView('email-wallet-otp-verification-view');
                }
                else if (!isBloctoConnector(walletConnector)) {
                    pushView('wait-for-email-confirmation-view');
                }
            }
            const connectionPromise = connectWallet(walletConnector, getAddressOpts, {
                applyHandleConnectedWallet: shouldCallCallback,
            });
            try {
                yield Promise.race([
                    connectionPromise,
                    connectionCancelPromise.promise,
                ]);
            }
            catch (error) {
                handleWalletConnectionError(error);
                return;
            }
            const connectionResult = yield connectionPromise;
            // Fallback to catch any errors that were missed.
            if (!(connectionResult === null || connectionResult === void 0 ? void 0 : connectionResult.address)) {
                handleWalletConnectionError();
                return;
            }
            const { address } = connectionResult;
            logger.logVerboseTroubleshootingMessage('[useConnectAndSign] connection result', {
                address,
                walletConnectorKey: walletConnector.key,
            });
            const walletNetwork = yield walletConnector.getNetwork(true);
            const usesSupportedNetwork = isSupportedNetwork({
                network: walletNetwork,
                walletConnector,
            });
            const isNetworkValidationEnabledForSignIn = networkValidationMode === 'always' ||
                networkValidationMode === 'sign-in';
            if (!usesSupportedNetwork && isNetworkValidationEnabledForSignIn) {
                if (!isProgrammableNetworkSwitchSupported(walletConnector)) {
                    return pushView('network-not-supported-manual');
                }
                return pushView('network-not-supported');
            }
            const user = getUserProfile();
            const isAlreadyVerified = Boolean(user === null || user === void 0 ? void 0 : user.verifiedCredentials.find((vc) => vc.walletProvider === getWalletProvider(walletConnector) &&
                vc.walletName === walletConnector.key &&
                vc.address &&
                isSameAddress(vc.address, address, walletConnector.connectedChain)));
            logger.logVerboseTroubleshootingMessage('[useConnectAndSign] isAlreadyVerified', {
                isAlreadyVerified,
                userVerifiedCredentials: user === null || user === void 0 ? void 0 : user.verifiedCredentials,
            });
            // this is in case the user is trying to link a wallet that is already verified/linked
            // this flow mainly happens when trying to link a WalletConnect or MM wallet through qr code
            // skip this check when requestedScopes is present, as that indicates a step-up auth flow
            // where the user must re-sign with an already-verified wallet to authorize a sensitive action
            if (isAlreadyVerified && !(requestedScopes === null || requestedScopes === void 0 ? void 0 : requestedScopes.length)) {
                setShowAuthFlow(false);
                return;
            }
            if (isConnectOnly()) {
                StorageService.setItem(LAST_USED_WALLET, walletConnector.key);
                if (shouldUpdateWallets) {
                    handleWalletsToConnect({ walletConnector });
                }
                return;
            }
            if (isCaptchaEnabled(projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.security)) {
                engageCaptcha({
                    authMethod: 'wallet',
                    onCaptchaSuccess: (captchaToken) => __awaiter(void 0, void 0, void 0, function* () {
                        try {
                            yield handleWalletVerify(walletConnector, address, captchaToken, requestedScopes);
                        }
                        catch (e) {
                            handleWalletVerifyError(e);
                        }
                    }),
                });
                return;
            }
            yield handleWalletVerify(walletConnector, address, getCaptchaToken(), requestedScopes);
        }
        catch (err) {
            handleWalletVerifyError(err);
        }
        finally {
            // Read UserWalletsContext.tsx explanation for more context
            // This will unlock the variable that indicates "verification in progress"
            // by calling setIsInitialWalletVerificationInProgress(false).
            // However, we do not want to do so immediately, as some routines of wallet verification process
            // are still ongoing.
            // This method sets up a listener and a timeout to ensure the unlock will happen, but only after
            // verification is finally complete.
            // In order to debug why this is necessary, try:
            // 1. Remove the setIsInitialWalletVerificationInProgress calls
            // 2. Add a useEffect somewhere that does primaryWallet.switchNetwork() and depends on primaryWallet
            // 3. The SDK will enter a broken state. Try signing a message with wagmi.
            // You can also add a "pause on exception" breakpoint in the debugger and see what happens during verification.
            unsetInitialWalletVerificationFlagWithTimeout();
            dynamicEvents.removeListener('goBack', onGoBack);
            dynamicEvents.removeListener('authFlowClose', onGoBack);
        }
    });
};

export { useConnectAndSign };
