'use client'
'use strict';

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

var _tslib = require('../../../../../../_virtual/_tslib.cjs');
var utils = require('@dynamic-labs/utils');
var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
require('react');
require('../../../../context/DynamicContext/DynamicContext.cjs');
require('../../../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('@dynamic-labs/iconic');
require('react/jsx-runtime');
var ViewContext = require('../../../../context/ViewContext/ViewContext.cjs');
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');
require('../../../../shared/consts/index.cjs');
var dynamicEvents = require('../../../../events/dynamicEvents.cjs');
require('../../../../context/CaptchaContext/CaptchaContext.cjs');
var ErrorContext = require('../../../../context/ErrorContext/ErrorContext.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../../store/state/nonce/nonce.cjs');
var requiresTwoStepAuthentication = require('../../../functions/requiresTwoStepAuthentication/requiresTwoStepAuthentication.cjs');
require('@dynamic-labs-sdk/client/core');
require('../../../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../../../config/ApiEndpoint.cjs');
require('@dynamic-labs/locale');
require('../../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../../../context/AccessDeniedContext/AccessDeniedContext.cjs');
require('../../../../context/AccountExistsContext/AccountExistsContext.cjs');
require('../../../../context/UserWalletsContext/UserWalletsContext.cjs');
var authMode = require('../../../../store/state/authMode/authMode.cjs');
require('../../../../context/VerificationContext/VerificationContext.cjs');
require('react-dom');
require('../../../functions/compareChains/compareChains.cjs');
require('../../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('../../../../context/ThemeContext/ThemeContext.cjs');
require('../../useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
require('bs58');
require('@dynamic-labs/types');
require('../../../../context/SocialRedirectContext/SocialRedirectContext.cjs');
require('../../../../context/LoadingContext/LoadingContext.cjs');
require('../../../../context/WalletContext/WalletContext.cjs');
require('../../useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.cjs');
require('yup');
var MockContext = require('../../../../context/MockContext/MockContext.cjs');
require('../../../../views/CollectUserDataView/useFields.cjs');
require('../../../../context/FieldsStateContext/FieldsStateContext.cjs');
require('../../../../context/UserFieldEditorContext/UserFieldEditorContext.cjs');
require('@dynamic-labs/rpc-providers');
require('../../../../store/state/walletOptions/walletOptions.cjs');
var isSelectedWalletAlreadyConnected = require('../../../functions/isSelectedWalletAlreadyConnected/isSelectedWalletAlreadyConnected.cjs');
require('react-i18next');
require('../../../../components/Accordion/components/AccordionItem/AccordionItem.cjs');
require('../../../../components/Alert/Alert.cjs');
require('../../../../components/ShadowDOM/ShadowDOM.cjs');
require('../../../../components/IconButton/IconButton.cjs');
require('../../../../components/InlineWidget/InlineWidget.cjs');
require('../../../../components/Input/Input.cjs');
require('../../../../components/IsBrowser/IsBrowser.cjs');
require('../../../../components/MenuList/Dropdown/Dropdown.cjs');
require('../../../../components/OverlayCard/OverlayCard.cjs');
require('../../../../components/Transition/ZoomTransition/ZoomTransition.cjs');
require('../../../../components/Transition/SlideInUpTransition/SlideInUpTransition.cjs');
require('../../../../components/Transition/OpacityTransition/OpacityTransition.cjs');
require('../../../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.cjs');
require('../../../../components/Popper/Popper/Popper.cjs');
require('../../../../components/Popper/PopperContext/PopperContext.cjs');
require('react-focus-lock');
require('qrcode');
require('formik');
require('../../useSubdomainCheck/useSubdomainCheck.cjs');
require('../../../../context/WalletGroupContext/WalletGroupContext.cjs');
require('../../../../context/IpConfigurationContext/IpConfigurationContext.cjs');
require('../../../../context/ConnectWithOtpContext/ConnectWithOtpContext.cjs');
require('../../../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.cjs');
require('@hcaptcha/react-hcaptcha');
require('../../../../widgets/DynamicWidget/context/DynamicWidgetContext.cjs');
require('../../../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.cjs');
require('../../../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.cjs');
require('../../../../context/ErrorContext/hooks/useErrorText/useErrorText.cjs');
require('../../../../context/FooterAnimationContext/index.cjs');
require('../../../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.cjs');
require('../../../../context/PasskeyContext/PasskeyContext.cjs');
require('../../../../context/OnrampContext/OnrampContext.cjs');
require('../../../../store/state/sendBalances.cjs');
require('../../../../store/state/connectorsInitializing/connectorsInitializing.cjs');
require('../../../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.cjs');
require('../../../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.cjs');
require('../../../../views/TransactionConfirmationView/TransactionConfirmationView.cjs');
require('../../../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.cjs');
require('../../../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.cjs');
require('../../../../../index.cjs');
require('../../../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.cjs');
require('../../../../store/state/tokenBalances.cjs');
require('../../../../store/state/multichainBalances.cjs');
require('../../../../shared/utils/functions/getInitialUrl/getInitialUrl.cjs');
var useInternalDynamicContext = require('../../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');

const useHandleWalletItem = ({ allowAlreadyConnectedWallet, onQrCodeConnect, onConnectOnly, onCustodialWallet, onInstalledExtension, }) => {
    const { setMultiWalletWidgetState, setShowAuthFlow, setSelectedWalletConnectorKey, walletConnectorOptions, setQrcodeUri, setDesktopUri, user, linkedWallets, setLegacyIsVerifying, } = useInternalDynamicContext.useInternalDynamicContext();
    const { mockedSDK } = MockContext.useMockContext();
    const { setError, setErrorMessage } = ErrorContext.useErrorContext();
    const { pushView, clearStackAndPushInitialView, replaceView } = ViewContext.useViewContext();
    const handleCustodialWalletClick = (walletConnector) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        logger.logger.debug('handleCustodialWalletClick', walletConnector);
        const twoStepAuthentication = requiresTwoStepAuthentication.requiresTwoStepAuthentication(walletConnector);
        logger.logger.logVerboseTroubleshootingMessage('[handleCustodialWalletClick]', {
            twoStepAuthentication,
        });
        setSelectedWalletConnectorKey({
            chain: walletConnector.connectedChain,
            key: walletConnector.key,
        });
        return onCustodialWallet({
            requiresTwoStepAuthentication: twoStepAuthentication,
            walletConnector,
        });
    });
    const handleMobileWalletClick = (walletConnector) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        var _a;
        logger.logger.debug('handleMobileWalletClick', walletConnector);
        setSelectedWalletConnectorKey({
            chain: walletConnector.connectedChain,
            key: walletConnector.key,
        });
        // We need to set to LS when about to verify phantom wallet on mobile
        // because the deeplink interrupts this code execution and then redirects back on a new tab.
        // This resets all state (except for LS obviously). When we receive the phantom signature in this new tab,
        // we can't tell whether it's supposed to be used to sign a message, verify a wallet sign in/link,
        // or conclude a wallet transfer, which is why we need this LS variable: it will indicate whether it
        // is a signature, authentication or transfer.
        // Check method handleUserResponse in file useResponseHandlers, case 'signMessage'.
        if (walletConnector.key === 'phantom') {
            const currentState = utils.StorageService.getItem(localStorage.PHANTOM_SIGNATURE_STATE);
            utils.StorageService.setItem(localStorage.PHANTOM_SIGNATURE_STATE, {
                loseOriginalAccountOnTransfer: (_a = currentState === null || currentState === void 0 ? void 0 : currentState.loseOriginalAccountOnTransfer) !== null && _a !== void 0 ? _a : false,
                submittedAtTimestamp: new Date().toString(),
                verificationType: 'awaiting_verification',
            });
        }
        const onRetry = () => {
            if (walletConnector.hasRetryDeeplinkConnection()) {
                walletConnector.retryDeeplinkConnection();
                return;
            }
            onConnectOnly({ shouldShowPendingConnectView: false, walletConnector });
        };
        pushView('mobile-wallet-redirect-view', { onRetry });
        onConnectOnly({ shouldShowPendingConnectView: false, walletConnector });
    });
    const handleInstalledExtensionClick = (walletConnector) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        logger.logger.debug('handleInstalledExtensionClick', walletConnector);
        setSelectedWalletConnectorKey({
            chain: walletConnector.connectedChain,
            key: walletConnector.key,
        });
        return onInstalledExtension({ walletConnector });
    });
    const handleUninstalledClick = (walletConnector) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        logger.logger.debug('handleUninstalledClick', walletConnector);
        setSelectedWalletConnectorKey({
            chain: walletConnector.connectedChain,
            key: walletConnector.key,
        });
        if (!walletConnector.canConnectViaQrCode) {
            replaceView('no-qr-not-installed');
        }
        else {
            onQrCodeConnect({
                getAddressOpts: {
                    onDesktopUri: (uri) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
                        dynamicEvents.dynamicEvents.emit('walletConnectionQrCodeReady', uri);
                        setDesktopUri(uri);
                    }),
                    onDisplayUri: (uri) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
                        dynamicEvents.dynamicEvents.emit('walletConnectionQrCodeReady', uri);
                        setQrcodeUri(uri);
                    }),
                },
                walletConnector,
            });
            replaceView('qr-code');
        }
        setError(undefined);
    });
    const handleAlreadyConnectedWallet = (walletConnector) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        logger.logger.debug('handleAlreadyConnectedWallet', walletConnector);
        setShowAuthFlow(false);
        const connectedAccounts = yield walletConnector.getConnectedAccounts();
        const activeAccountAlreadyLinked = linkedWallets.find((wallet) => { var _a; return wallet.address.toLowerCase() === ((_a = connectedAccounts[0]) === null || _a === void 0 ? void 0 : _a.toLowerCase()); });
        logger.logger.logVerboseTroubleshootingMessage('[handleAlreadyConnectedWallet]', {
            activeAccountAlreadyLinked,
            connectedAccounts,
            linkedWallets,
            walletConnectorKey: walletConnector.key,
        });
        setSelectedWalletConnectorKey({
            chain: walletConnector.connectedChain,
            key: walletConnector.key,
        });
        if (!activeAccountAlreadyLinked) {
            setMultiWalletWidgetState('awaiting_signature', undefined, 'linking_new_wallet');
            return;
        }
        const isTryingToUpdateUnknownWallet = activeAccountAlreadyLinked.connector.key === 'unknown';
        if (isTryingToUpdateUnknownWallet) {
            //prompt the user to connect and sign with the wallet
            dynamicEvents.dynamicEvents.emit('triggerConnectAndSign', walletConnector);
            return;
        }
        setMultiWalletWidgetState('awaiting_account_switch', 'linking_new_wallet');
    });
    const openWallet = (walletKey, handlers) => {
        var _a;
        const { openMobileWallet = handleMobileWalletClick, openCustodialWallet = handleCustodialWalletClick, openExtensionWallet = handleInstalledExtensionClick, } = handlers || {};
        const walletConnector = (_a = walletConnectorOptions.find((wallet) => wallet.key === walletKey)) === null || _a === void 0 ? void 0 : _a.walletConnector;
        if (!walletConnector)
            return;
        if (utils.isMobile()) {
            openMobileWallet(walletConnector);
        }
        else if (walletConnector.canConnectViaCustodialService) {
            openCustodialWallet(walletConnector);
        }
        else if (walletConnector.isInstalledOnBrowser()) {
            openExtensionWallet(walletConnector);
        }
    };
    const handleWalletItemClick = (wallet) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        const { walletConnector, isInstalledOnBrowser } = wallet;
        const shouldEndWalletConnectorSession = walletConnector.connectedChain === 'FLOW' ||
            walletConnectorCore.isPhantomRedirectConnector(walletConnector) ||
            // because some wallet connectors only supports one connection at a time,
            // we need to end the session (disconnect) when the user selects
            // a different wallet to connect with
            // a new connection is established a few steps further down
            !walletConnector.canHandleMultipleConnections;
        logger.logger.logVerboseTroubleshootingMessage('[handleWalletItemClick]', {
            mockedSDK,
            shouldEndWalletConnectorSession,
            wallet,
        });
        if (mockedSDK)
            return;
        if (shouldEndWalletConnectorSession) {
            yield walletConnector.endSession();
        }
        setLegacyIsVerifying(false);
        const isMetamask = walletConnector.metadata.groupKey === 'metamask';
        const authMode$1 = authMode.getAuthMode();
        // in connect only we only allow one account to be connected in the same wallet
        // also this is only a feature in MM
        if (authMode$1 !== 'connect-only' && isMetamask) {
            try {
                setSelectedWalletConnectorKey({
                    chain: walletConnector.connectedChain,
                    key: walletConnector.key,
                });
                pushView('pending-connect');
                yield walletConnector.chooseAccountsToConnect();
            }
            catch (error) {
                if (error instanceof utils.UserRejectedRequestError) {
                    setErrorMessage('connection_rejected');
                    clearStackAndPushInitialView();
                    return;
                }
            }
        }
        if (!allowAlreadyConnectedWallet &&
            isSelectedWalletAlreadyConnected.isSelectedWalletAlreadyConnected(linkedWallets, walletConnector, user) &&
            walletConnector.connectedChain !== 'FLOW' &&
            !walletConnector.isWalletConnect) {
            // wallet is already connected
            handleAlreadyConnectedWallet(walletConnector);
        }
        else if (walletConnector.canConnectViaCustodialService) {
            // providers like coinbase, blocto and dapper
            handleCustodialWalletClick(walletConnector);
        }
        else if (utils.isMobile()) {
            // mobile wallets
            if (walletConnector.key.startsWith('walletconnect')) {
                pushView('wallet-connect-mobile-wallets-list');
            }
            else {
                handleMobileWalletClick(walletConnector);
            }
        }
        else if (isInstalledOnBrowser) {
            // browser extensions or injected wallets
            handleInstalledExtensionClick(walletConnector);
        }
        else {
            // wallet requiring a qr code (wallet connect/coinbase wallet)
            handleUninstalledClick(walletConnector);
        }
    });
    return {
        handleAlreadyConnectedWallet,
        handleCustodialWalletClick,
        handleInstalledExtensionClick,
        handleMobileWalletClick,
        handleUninstalledClick,
        handleWalletItemClick,
        openWallet,
    };
};

exports.useHandleWalletItem = useHandleWalletItem;
