'use client'
'use strict';

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

var _tslib = require('../../../../_virtual/_tslib.cjs');
var React = require('react');
var utils = require('@dynamic-labs/utils');
var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
var localStorage = require('../../utils/constants/localStorage.cjs');
var getSiweStatement = require('../../utils/functions/getSiweStatement/getSiweStatement.cjs');
var dynamicEvents = require('../../events/dynamicEvents.cjs');
require('../DynamicContext/DynamicContext.cjs');
require('../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('@dynamic-labs/iconic');
require('react/jsx-runtime');
var ViewContext = require('../ViewContext/ViewContext.cjs');
require('../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('../../utils/constants/colors.cjs');
require('../../utils/constants/values.cjs');
require('@dynamic-labs/sdk-api-core');
require('../../shared/consts/index.cjs');
require('../../store/state/authMode/authMode.cjs');
var useInternalDynamicContext = require('../DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');
var CaptchaContext = require('../CaptchaContext/CaptchaContext.cjs');
var ErrorContext = require('../ErrorContext/ErrorContext.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../store/state/nonce/nonce.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');
var useVerifyWallet = require('../../utils/hooks/useVerifyWallet/useVerifyWallet.cjs');
require('../VerificationContext/VerificationContext.cjs');
require('react-dom');
require('../../utils/functions/compareChains/compareChains.cjs');
require('../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('../ThemeContext/ThemeContext.cjs');
require('../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
require('bs58');
require('@dynamic-labs/types');
require('../SocialRedirectContext/SocialRedirectContext.cjs');
require('../AccessDeniedContext/AccessDeniedContext.cjs');
require('../AccountExistsContext/AccountExistsContext.cjs');
require('../LoadingContext/LoadingContext.cjs');
require('../WalletContext/WalletContext.cjs');
require('../UserWalletsContext/UserWalletsContext.cjs');
require('../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.cjs');
require('yup');
require('../MockContext/MockContext.cjs');
require('../../views/CollectUserDataView/useFields.cjs');
require('../FieldsStateContext/FieldsStateContext.cjs');
require('../UserFieldEditorContext/UserFieldEditorContext.cjs');
require('@dynamic-labs/rpc-providers');
require('../../store/state/walletOptions/walletOptions.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('../../utils/hooks/useSubdomainCheck/useSubdomainCheck.cjs');
require('../WalletGroupContext/WalletGroupContext.cjs');
require('../IpConfigurationContext/IpConfigurationContext.cjs');
require('../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('../ErrorContext/hooks/useErrorText/useErrorText.cjs');
require('../FooterAnimationContext/index.cjs');
require('../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.cjs');
require('../PasskeyContext/PasskeyContext.cjs');
require('../OnrampContext/OnrampContext.cjs');
var useTransferWallet = require('../../utils/hooks/useTransferWallet/useTransferWallet.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');
var useFundWithWallet = require('../../utils/hooks/useFundWithWallet/useFundWithWallet.cjs');
var getPromptAmountParams = require('../../widgets/DynamicWidget/views/ChooseWalletFundingMethod/useFundingMethods/getPromptAmountParams/getPromptAmountParams.cjs');
require('../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.cjs');
require('../../../index.cjs');
require('../../store/state/tokenBalances.cjs');
require('../../store/state/multichainBalances.cjs');
require('../../shared/utils/functions/getInitialUrl/getInitialUrl.cjs');

const useResponseHandlers = () => {
    const { walletConnectorOptions, displaySiweStatement, environmentId, projectSettings, setIsSingleWalletAccount, connectWallet, setShowAuthFlow, setSelectedWalletConnectorKey, siweStatement, appName, user, } = useInternalDynamicContext.useInternalDynamicContext();
    const { pushView } = ViewContext.useViewContext();
    const { setErrorMessage } = ErrorContext.useErrorContext();
    const { getCaptchaToken } = CaptchaContext.useCaptchaContext();
    const { promptAmountAndFund } = useFundWithWallet.useInternalFundWithWallet();
    const verifyWallet = useVerifyWallet.useVerifyWallet({
        displaySiweStatement,
        environmentId,
        projectSettings,
        setIsSingleWalletAccount,
    });
    const phantomRedirectConnector = walletConnectorOptions
        .map(({ walletConnector }) => walletConnector)
        .find(walletConnectorCore.isPhantomRedirectConnector);
    const handleConnectResponse = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        if (!phantomRedirectConnector) {
            return;
        }
        // this completes the connection step
        yield phantomRedirectConnector.getSession();
        const connectResult = yield connectWallet(phantomRedirectConnector);
        // Check if we have a connection type
        const connectionType = utils.StorageService.getItem(utils.PHANTOM_REDIRECT_CONNECTION_TYPE_KEY);
        // If this is an external wallet funding connection, then we need to
        // complete the wallet transfer.
        // If connectorConsumed is false that means that the connector has not yet
        // verified this connection type and we should ignore it.
        if ((connectionType === null || connectionType === void 0 ? void 0 : connectionType.connectorConsumed) &&
            connectionType.type === 'external-wallet-funding') {
            if (!connectResult)
                return;
            const wallet = phantomRedirectConnector.createWallet({
                address: connectResult.address,
                chain: phantomRedirectConnector.connectedChain,
                connector: phantomRedirectConnector,
                id: 'external-funding-wallet',
                isAuthenticated: false,
                key: phantomRedirectConnector.key,
            });
            // If the connection was initiated by the widget we can carry on with the funding flow
            // Otherwise we simply raise an event to let the customer's code handle the wallet
            dynamicEvents.dynamicEvents.emit('walletConnectedForFunding', {
                initiatedByWidget: connectionType.initiatedByWidget,
                isPhantomRedirect: true,
                wallet,
            });
            if (!connectionType.initiatedByWidget)
                return;
            const props = getPromptAmountParams.getPromptAmountParams({ wallet });
            promptAmountAndFund(props);
            return;
        }
        // Default behavior is to link a wallet
        setShowAuthFlow(true, { ignoreIfIsEmbeddedWidget: true });
        pushView('pending-signature');
        setSelectedWalletConnectorKey('phantom');
    }), [
        phantomRedirectConnector,
        connectWallet,
        setShowAuthFlow,
        pushView,
        setSelectedWalletConnectorKey,
        promptAmountAndFund,
    ]);
    const completeWalletTransfer = useTransferWallet.useTransferWallet();
    const handleUserResponse = React.useCallback(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        if (!phantomRedirectConnector) {
            return;
        }
        setSelectedWalletConnectorKey('phantom');
        const [address] = yield phantomRedirectConnector.getConnectedAccounts();
        const method = phantomRedirectConnector.consumeMethod();
        switch (method) {
            case 'signAndSendTransaction': {
                const { signature } = phantomRedirectConnector.extractSignature();
                phantomRedirectConnector.emit('signAndSendTransaction', {
                    signature,
                });
                break;
            }
            case 'signAllTransactions':
                phantomRedirectConnector.emit('signAllTransactions', {
                    transactions: phantomRedirectConnector.extractTransactions(),
                });
                break;
            case 'signTransaction':
                phantomRedirectConnector.emit('signTransaction', {
                    transaction: phantomRedirectConnector.extractTransaction(),
                });
                break;
            case 'signMessage': {
                const { signature, message } = phantomRedirectConnector.extractSignature();
                const signatureState = utils.StorageService.getItem(localStorage.PHANTOM_SIGNATURE_STATE);
                utils.StorageService.removeItem(localStorage.PHANTOM_SIGNATURE_STATE);
                if ((signatureState === null || signatureState === void 0 ? void 0 : signatureState.verificationType) === 'awaiting_transfer') {
                    const siweStatementToUse = getSiweStatement.getSiweStatement({
                        appName,
                        siweStatement,
                    });
                    yield completeWalletTransfer({
                        messageToSignOverride: message,
                        overrideSiweStatement: siweStatementToUse,
                        publicWalletAddress: address,
                        signedMessageOverride: signature,
                        skipEmptyAccountCheck: signatureState.loseOriginalAccountOnTransfer,
                        walletConnector: phantomRedirectConnector,
                    });
                }
                else if ((signatureState === null || signatureState === void 0 ? void 0 : signatureState.verificationType) === 'awaiting_verification' ||
                    !user) {
                    pushView('wallet-redirect-view');
                    yield verifyWallet({
                        captchaToken: getCaptchaToken(),
                        messageToSignOverride: message,
                        publicWalletAddress: address,
                        signedMessageOverride: signature,
                        walletConnector: phantomRedirectConnector,
                    });
                }
                else {
                    phantomRedirectConnector.emit('signMessage', {
                        signature,
                    });
                }
                break;
            }
        }
    }), [
        phantomRedirectConnector,
        setSelectedWalletConnectorKey,
        user,
        appName,
        siweStatement,
        completeWalletTransfer,
        pushView,
        verifyWallet,
        getCaptchaToken,
    ]);
    const handleErrorResponse = React.useCallback((params) => {
        var _a;
        if (!phantomRedirectConnector)
            return;
        const errorCode = params.get('errorCode');
        const errorMessage = (_a = params.get('errorMessage')) !== null && _a !== void 0 ? _a : undefined;
        if (!errorCode)
            return;
        setErrorMessage(errorCode);
        const method = phantomRedirectConnector.consumeMethod();
        switch (method) {
            case 'signAndSendTransaction':
                phantomRedirectConnector.emit('signAndSendTransaction', {
                    errorCode,
                    errorMessage,
                });
                break;
            case 'signAllTransactions':
                phantomRedirectConnector.emit('signAllTransactions', {
                    errorCode,
                    errorMessage,
                });
                break;
            case 'signTransaction':
                phantomRedirectConnector.emit('signTransaction', {
                    errorCode,
                    errorMessage,
                });
                break;
            case 'signMessage':
                phantomRedirectConnector.emit('signMessage', {
                    errorCode,
                    errorMessage,
                });
                break;
        }
    }, [phantomRedirectConnector, setErrorMessage]);
    return {
        handleConnectResponse,
        handleErrorResponse,
        handleUserResponse,
        phantomRedirectConnector,
    };
};

exports.useResponseHandlers = useResponseHandlers;
