'use client'
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _tslib = require('../../../../../../_virtual/_tslib.cjs');
var utils = require('@dynamic-labs/utils');
var CaptchaContext = require('../../../../context/CaptchaContext/CaptchaContext.cjs');
var captcha = require('../../../captcha.cjs');
require('../../../../context/DynamicContext/useDynamicContext/useDynamicContext.cjs');
var useInternalDynamicContext = require('../../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');
var ErrorContext = require('../../../../context/ErrorContext/ErrorContext.cjs');
var ViewContext = require('../../../../context/ViewContext/ViewContext.cjs');
require('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
require('react');
require('react/jsx-runtime');
var logger = require('../../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
var localStorage = require('../../../constants/localStorage.cjs');
require('../../../constants/colors.cjs');
require('../../../constants/values.cjs');
require('@dynamic-labs/sdk-api-core');
var instrumentAuthLoginFailed = require('../../../../shared/utils/functions/instrumentAuthLoginFailed/instrumentAuthLoginFailed.cjs');
require('../../../../shared/consts/index.cjs');
var useHandleWalletsToConnect = require('../../useHandleWalletsToConnect/useHandleWalletsToConnect.cjs');
var useVerifyWallet = require('../../useVerifyWallet/useVerifyWallet.cjs');
var showPendingConnectView = require('../helpers/showPendingConnectView.cjs');
var isConnectOnly = require('../helpers/isConnectOnly.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../../store/state/nonce/nonce.cjs');
var isProgrammableNetworkSwitchSupported = require('../../../functions/isProgrammableNetworkSwitchSupported/isProgrammableNetworkSwitchSupported.cjs');
var isSupportedNetwork = require('../../../functions/isSupportedNetwork/isSupportedNetwork.cjs');
require('@dynamic-labs-wallet/browser-wallet-client');
require('@dynamic-labs-sdk/client/core');
require('eventemitter3');
require('@dynamic-labs-sdk/client');
require('../../../../config/ApiEndpoint.cjs');
require('../../../../events/dynamicEvents.cjs');
require('@dynamic-labs/locale');
require('../../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../../functions/getWaasAddressTypeLabel/getWaasAddressTypeLabel.cjs');

const useConnectAndSignSplitSteps = () => {
    const { pushView, clearStackAndPushInitialView } = ViewContext.useViewContext();
    const { setErrorMessage } = ErrorContext.useErrorContext();
    const { getCaptchaToken, engageCaptcha } = CaptchaContext.useCaptchaContext();
    const { connectWallet, displaySiweStatement, projectSettings, environmentId, networkValidationMode, setIsSingleWalletAccount, setShowAuthFlow, } = useInternalDynamicContext.useInternalDynamicContext();
    const { handleWalletsToConnect } = useHandleWalletsToConnect.useHandleWalletsToConnect();
    const verifyWallet = useVerifyWallet.useVerifyWallet({
        displaySiweStatement,
        environmentId,
        projectSettings,
        setIsSingleWalletAccount,
    });
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const onErrorHandler = (err) => {
        var _a;
        logger.logger.debug(err);
        /**
         * On mobile, when the user is redirected to the wallet mobile app, this error is thrown.
         * We want to stay in whichever view we currently are, most likely mobile-wallet-redirect-view
         */
        if (err instanceof utils.MissingPublicAddressError && utils.isMobile())
            return;
        instrumentAuthLoginFailed.instrumentAuthLoginFailed(err, {
            authOrigin: 'connect-and-sign-split-steps',
        });
        clearStackAndPushInitialView();
        setErrorMessage((_a = err.code) !== null && _a !== void 0 ? _a : err.toString(), err, 'connect-and-sign-split-steps');
    };
    // This method is similar to useConnectAndSign, but it skips signing for now
    // It's used when we want to connect and sign in two separate steps
    // For example on mobile when we want to sign on button click
    // or in Dapper
    const onlyConnectUser = (_a) => _tslib.__awaiter(void 0, [_a], void 0, function* ({ walletConnector, getAddressOpts = undefined, shouldShowPendingConnectView = true, }) {
        if (shouldShowPendingConnectView)
            yield showPendingConnectView.showPendingConnectView(walletConnector, pushView);
        try {
            yield connectWallet(walletConnector, getAddressOpts);
            if (isConnectOnly.isConnectOnly()) {
                utils.StorageService.setItem(localStorage.LAST_USED_WALLET, walletConnector.key);
                handleWalletsToConnect({ walletConnector });
                return;
            }
            if (captcha.isCaptchaEnabled(projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.security)) {
                engageCaptcha({
                    authMethod: 'wallet',
                    onCaptchaSuccess: (_captchaToken) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
                        setShowAuthFlow(true);
                        pushView('pending-signature');
                    }),
                });
                return;
            }
            setShowAuthFlow(true);
            pushView('pending-signature');
        }
        catch (err) {
            onErrorHandler(err);
            return;
        }
    });
    // This method is similar to useConnectAndSign, but it does not call showPendingConnectView
    // This is because we already called it in onlyConnectUser and now we just want to sign
    const signAlreadyConnectedUser = (_b) => _tslib.__awaiter(void 0, [_b], void 0, function* ({ walletConnector, getAddressOpts = undefined, }) {
        try {
            const connectionResult = yield connectWallet(walletConnector, getAddressOpts);
            if (!(connectionResult === null || connectionResult === void 0 ? void 0 : connectionResult.address)) {
                return;
            }
            const walletNetwork = yield walletConnector.getNetwork(true);
            const usesSupportedNetwork = isSupportedNetwork.isSupportedNetwork({
                network: walletNetwork,
                walletConnector,
            });
            const isNetworkValidationEnabledForSignIn = networkValidationMode === 'always' ||
                networkValidationMode === 'sign-in';
            if (!usesSupportedNetwork && isNetworkValidationEnabledForSignIn) {
                if (!isProgrammableNetworkSwitchSupported.isProgrammableNetworkSwitchSupported(walletConnector)) {
                    return pushView('network-not-supported-manual');
                }
                return pushView('network-not-supported');
            }
            yield verifyWallet({
                captchaToken: getCaptchaToken(),
                publicWalletAddress: connectionResult.address,
                walletConnector,
            });
        }
        catch (err) {
            onErrorHandler(err);
            return;
        }
    });
    return {
        onlyConnectUser,
        signAlreadyConnectedUser,
    };
};

exports.useConnectAndSignSplitSteps = useConnectAndSignSplitSteps;
