'use client'
import { __awaiter } from '../../../../../../_virtual/_tslib.js';
import { StorageService, MissingPublicAddressError, isMobile } from '@dynamic-labs/utils';
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 '@dynamic-labs/wallet-connector-core';
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 { useHandleWalletsToConnect } from '../../useHandleWalletsToConnect/useHandleWalletsToConnect.js';
import { useVerifyWallet } from '../../useVerifyWallet/useVerifyWallet.js';
import { showPendingConnectView } from '../helpers/showPendingConnectView.js';
import { isConnectOnly } from '../helpers/isConnectOnly.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 '../../../../events/dynamicEvents.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';

const useConnectAndSignSplitSteps = () => {
    const { pushView, clearStackAndPushInitialView } = useViewContext();
    const { setErrorMessage } = useErrorContext();
    const { getCaptchaToken, engageCaptcha } = useCaptchaContext();
    const { connectWallet, displaySiweStatement, projectSettings, environmentId, networkValidationMode, setIsSingleWalletAccount, setShowAuthFlow, } = useInternalDynamicContext();
    const { handleWalletsToConnect } = useHandleWalletsToConnect();
    const verifyWallet = useVerifyWallet({
        displaySiweStatement,
        environmentId,
        projectSettings,
        setIsSingleWalletAccount,
    });
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const onErrorHandler = (err) => {
        var _a;
        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 MissingPublicAddressError && isMobile())
            return;
        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) => __awaiter(void 0, [_a], void 0, function* ({ walletConnector, getAddressOpts = undefined, shouldShowPendingConnectView = true, }) {
        if (shouldShowPendingConnectView)
            yield showPendingConnectView(walletConnector, pushView);
        try {
            yield connectWallet(walletConnector, getAddressOpts);
            if (isConnectOnly()) {
                StorageService.setItem(LAST_USED_WALLET, walletConnector.key);
                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* () {
                        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) => __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({
                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');
            }
            yield verifyWallet({
                captchaToken: getCaptchaToken(),
                publicWalletAddress: connectionResult.address,
                walletConnector,
            });
        }
        catch (err) {
            onErrorHandler(err);
            return;
        }
    });
    return {
        onlyConnectUser,
        signAlreadyConnectedUser,
    };
};

export { useConnectAndSignSplitSteps };
