'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/useDynamicContext/useDynamicContext.cjs');
var useInternalDynamicContext = require('../DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');
var CaptchaContext = require('../CaptchaContext/CaptchaContext.cjs');
require('@dynamic-labs/sdk-api-core');
var ErrorContext = require('../ErrorContext/ErrorContext.cjs');
var ViewContext = require('../ViewContext/ViewContext.cjs');
require('@dynamic-labs/iconic');
require('react/jsx-runtime');
var logger = require('../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('../../utils/constants/colors.cjs');
require('../../utils/constants/values.cjs');
var instrumentAuthLoginFailed = require('../../shared/utils/functions/instrumentAuthLoginFailed/instrumentAuthLoginFailed.cjs');
require('../../shared/consts/index.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../store/state/nonce/nonce.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('@dynamic-labs/locale');
require('../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../utils/functions/getWaasAddressTypeLabel/getWaasAddressTypeLabel.cjs');
var useVerifyWallet = require('../../utils/hooks/useVerifyWallet/useVerifyWallet.cjs');
var isConnectOnly = require('../../utils/hooks/authenticationHooks/helpers/isConnectOnly.cjs');
require('../../store/state/loadingAndLifecycle/loadingAndLifecycle.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('../../store/state/authMode/authMode.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('../../widgets/DynamicWidget/context/DynamicWidgetContext.cjs');
require('../../utils/hooks/useGetMfaToken/useGetMfaToken.cjs');
require('../../utils/hooks/useWalletBackup/useWalletBackup.cjs');
require('../../utils/hooks/useWalletBackup/BackupError.cjs');
require('../../utils/hooks/useWalletBackup/types.cjs');
require('../../utils/hooks/useWalletBackup/cloudProviders.cjs');
require('@hcaptcha/react-hcaptcha');
require('@marsidev/react-turnstile');
require('../IpConfigurationContext/IpConfigurationContext.cjs');
require('../ConnectWithOtpContext/ConnectWithOtpContext.cjs');
require('../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.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');
require('../../utils/hooks/useWalletDelegation/DelegationError.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/ManagePasskeysMfaWidgetView/ManagePasskeysMfaWidgetView.cjs');
require('../../widgets/DynamicWidget/views/ManageTotpMfaWidgetView/ManageTotpMfaWidgetView.cjs');
require('../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.cjs');
require('../../../index.cjs');
require('../../store/state/tokenBalances.cjs');
require('../../store/state/multichainBalances.cjs');
require('@dynamic-labs/store');
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* () {
        logger.logger.logVerboseTroubleshootingMessage('[PhantomRedirect handleConnectResponse] called');
        if (!phantomRedirectConnector) {
            logger.logger.logVerboseTroubleshootingMessage('[PhantomRedirect handleConnectResponse] no phantomRedirectConnector');
            return;
        }
        // this completes the connection step
        logger.logger.logVerboseTroubleshootingMessage('[PhantomRedirect handleConnectResponse] calling getSession');
        yield phantomRedirectConnector.getSession();
        logger.logger.logVerboseTroubleshootingMessage('[PhantomRedirect handleConnectResponse] getSession complete, calling connectWallet');
        const connectResult = yield connectWallet(phantomRedirectConnector);
        logger.logger.logVerboseTroubleshootingMessage('[PhantomRedirect handleConnectResponse] connectWallet result', {
            connectResult,
        });
        // 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
        // In connect-only mode, skip verification and just handle the wallet connection
        if (isConnectOnly.isConnectOnly()) {
            logger.logger.logVerboseTroubleshootingMessage('[PhantomRedirect handleConnectResponse] Connect-only mode: skipping verification', {
                authMode: 'connect-only',
                connectResult,
            });
            if (connectResult === null || connectResult === void 0 ? void 0 : connectResult.address) {
                // connectWallet already added the wallet to the store in connect-only mode
                // Just set the last used wallet and close the auth flow
                utils.StorageService.setItem(localStorage.LAST_USED_WALLET, phantomRedirectConnector.key);
                setShowAuthFlow(false);
            }
            return;
        }
        logger.logger.logVerboseTroubleshootingMessage('[PhantomRedirect handleConnectResponse] Connect-and-sign mode: proceeding to verification', {
            authMode: 'connect-and-sign',
            connectResult,
        });
        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* () {
        var _a, _b, _c, _d;
        logger.logger.debug('[PhantomRedirect handleUserResponse] called');
        if (!phantomRedirectConnector) {
            logger.logger.debug('[PhantomRedirect handleUserResponse] no phantomRedirectConnector');
            return;
        }
        setSelectedWalletConnectorKey('phantom');
        const [address] = yield phantomRedirectConnector.getConnectedAccounts();
        logger.logger.debug('[PhantomRedirect handleUserResponse] got address', {
            address,
        });
        const method = phantomRedirectConnector.consumeMethod();
        logger.logger.debug('[PhantomRedirect handleUserResponse] consumed method', {
            method,
        });
        switch (method) {
            case 'signAndSendTransaction': {
                // Phantom redirect doesn't support signAndSendTransaction natively,
                // so we extract the signed transaction and send it ourselves
                const signAndSendRequestId = (_a = phantomRedirectConnector.consumeRequestId) === null || _a === void 0 ? void 0 : _a.call(phantomRedirectConnector);
                logger.logger.debug('[PhantomRedirect handleUserResponse] handling signAndSendTransaction');
                try {
                    const signature = yield phantomRedirectConnector.extractAndSendTransaction();
                    phantomRedirectConnector.emit('signAndSendTransaction', {
                        requestId: signAndSendRequestId,
                        signature,
                    });
                }
                catch (error) {
                    logger.logger.error('[PhantomRedirect handleUserResponse] Failed to send transaction', { error });
                    phantomRedirectConnector.emit('signAndSendTransaction', {
                        errorCode: 'SEND_FAILED',
                        errorMessage: error instanceof Error
                            ? error.message
                            : 'Failed to send transaction',
                        requestId: signAndSendRequestId,
                    });
                }
                break;
            }
            case 'signAllTransactions': {
                const signAllRequestId = (_b = phantomRedirectConnector.consumeRequestId) === null || _b === void 0 ? void 0 : _b.call(phantomRedirectConnector);
                logger.logger.debug('[PhantomRedirect handleUserResponse] handling signAllTransactions');
                phantomRedirectConnector.emit('signAllTransactions', {
                    requestId: signAllRequestId,
                    transactions: phantomRedirectConnector.extractTransactions(),
                });
                break;
            }
            case 'signTransaction': {
                const requestId = (_c = phantomRedirectConnector.consumeRequestId) === null || _c === void 0 ? void 0 : _c.call(phantomRedirectConnector);
                logger.logger.debug('[PhantomRedirect handleUserResponse] handling signTransaction');
                phantomRedirectConnector.emit('signTransaction', {
                    requestId,
                    transaction: phantomRedirectConnector.extractTransaction(),
                });
                break;
            }
            case 'signMessage': {
                logger.logger.debug('[PhantomRedirect handleUserResponse] handling signMessage response');
                const { signature, message } = phantomRedirectConnector.extractSignature();
                logger.logger.debug('[PhantomRedirect handleUserResponse] extracted signature and message', {
                    message,
                    messageLength: message === null || message === void 0 ? void 0 : message.length,
                    messagePreview: message === null || message === void 0 ? void 0 : message.substring(0, 200),
                    signature,
                    signatureLength: signature === null || signature === void 0 ? void 0 : signature.length,
                });
                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,
                    });
                    logger.logger.logVerboseTroubleshootingMessage('[PhantomRedirect handleUserResponse] completeWalletTransfer', {
                        messageToSignOverride: message,
                        overrideSiweStatement: siweStatementToUse,
                        publicWalletAddress: address,
                        signedMessageOverride: signature,
                    });
                    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) {
                    logger.logger.logVerboseTroubleshootingMessage('[PhantomRedirect handleUserResponse] calling verifyWallet', {
                        address,
                        captchaTokenPresent: Boolean(getCaptchaToken()),
                        message,
                        messageLength: message === null || message === void 0 ? void 0 : message.length,
                        signature,
                        signatureLength: signature === null || signature === void 0 ? void 0 : signature.length,
                        user: Boolean(user),
                        verificationType: signatureState === null || signatureState === void 0 ? void 0 : signatureState.verificationType,
                    });
                    pushView('wallet-redirect-view');
                    try {
                        yield verifyWallet({
                            captchaToken: getCaptchaToken(),
                            messageToSignOverride: message,
                            publicWalletAddress: address,
                            signedMessageOverride: signature,
                            walletConnector: phantomRedirectConnector,
                        });
                        logger.logger.logVerboseTroubleshootingMessage('[PhantomRedirect handleUserResponse] verifyWallet completed successfully');
                    }
                    catch (error) {
                        logger.logger.logVerboseTroubleshootingMessage('[PhantomRedirect handleUserResponse] verifyWallet threw error', { error });
                        throw error;
                    }
                }
                else {
                    // Post-auth sign: emit the signMessage event with the requestId and message
                    // so the listener from signMessage() can match and self-cleanup
                    const requestId = (_d = phantomRedirectConnector.consumeRequestId) === null || _d === void 0 ? void 0 : _d.call(phantomRedirectConnector);
                    logger.logger.logVerboseTroubleshootingMessage('[PhantomRedirect handleUserResponse] emitting signMessage event (post-auth sign)', {
                        message,
                        requestId,
                        signature,
                        signatureLength: signature === null || signature === void 0 ? void 0 : signature.length,
                    });
                    phantomRedirectConnector.emit('signMessage', {
                        message,
                        requestId,
                        signature,
                    });
                }
                break;
            }
        }
    }), [
        phantomRedirectConnector,
        setSelectedWalletConnectorKey,
        user,
        appName,
        siweStatement,
        completeWalletTransfer,
        pushView,
        verifyWallet,
        getCaptchaToken,
    ]);
    const handleErrorResponse = React.useCallback((params) => {
        var _a;
        logger.logger.logVerboseTroubleshootingMessage('[PhantomRedirect handleErrorResponse] called', {
            errorCode: params.get('errorCode'),
            errorMessage: params.get('errorMessage'),
        });
        if (!phantomRedirectConnector) {
            logger.logger.logVerboseTroubleshootingMessage('[PhantomRedirect handleErrorResponse] no phantomRedirectConnector');
            return;
        }
        const errorCode = params.get('errorCode');
        const errorMessage = (_a = params.get('errorMessage')) !== null && _a !== void 0 ? _a : undefined;
        if (!errorCode) {
            logger.logger.logVerboseTroubleshootingMessage('[PhantomRedirect handleErrorResponse] no errorCode');
            return;
        }
        instrumentAuthLoginFailed.instrumentAuthLoginFailed({ code: errorCode, message: errorMessage }, { authOrigin: 'phantom-redirect' });
        const method = phantomRedirectConnector.consumeMethod();
        // Phantom relays its own signing failures back through the redirect URL
        // (e.g. the active account has no usable key to sign). These come with a
        // generic, unmapped code, which would otherwise surface the default
        // "Something went wrong" message. When the failed operation was a signing
        // request, normalize unmapped codes to an actionable Phantom message.
        const isUnmappedSigningError = method !== undefined && ErrorContext.getMappedErrorMessage(errorCode) === undefined;
        const errorMessageKey = isUnmappedSigningError
            ? ErrorContext.PHANTOM_SIGNING_FAILED_ERROR_CODE
            : errorCode;
        setErrorMessage(errorMessageKey, errorMessage, 'phantom-redirect');
        logger.logger.logVerboseTroubleshootingMessage('[PhantomRedirect handleErrorResponse] consumed method, emitting error', { errorCode, errorMessage, method });
        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;
