'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { jsx } from 'react/jsx-runtime';
import { useRef, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import '@dynamic-labs/utils';
import '../../../components/Accordion/components/AccordionItem/AccordionItem.js';
import '@dynamic-labs/iconic';
import '../../../context/ViewContext/ViewContext.js';
import '@dynamic-labs/wallet-connector-core';
import '../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '../../constants/colors.js';
import '../../constants/values.js';
import '@dynamic-labs/sdk-api-core';
import '../../../shared/consts/index.js';
import '../../../components/Alert/Alert.js';
import '../../../events/dynamicEvents.js';
import '../../../context/DynamicContext/DynamicContext.js';
import '../../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '../../../store/state/authMode/authMode.js';
import '../../../context/CaptchaContext/CaptchaContext.js';
import '../../../context/ErrorContext/ErrorContext.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../../store/state/nonce/nonce.js';
import '@dynamic-labs-sdk/client/core';
import '../../../client/client.js';
import '@dynamic-labs-sdk/client';
import '../../../config/ApiEndpoint.js';
import '@dynamic-labs/locale';
import '../../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../../store/state/primaryWalletId/primaryWalletId.js';
import '../../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../../../context/AccessDeniedContext/AccessDeniedContext.js';
import '../../../context/AccountExistsContext/AccountExistsContext.js';
import '../../../context/UserWalletsContext/UserWalletsContext.js';
import '../../../context/VerificationContext/VerificationContext.js';
import { useConfirmationModal } from '../useConfirmationModal/useConfirmationModal.js';
import '../../functions/compareChains/compareChains.js';
import '../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import '../../../context/ThemeContext/ThemeContext.js';
import '../useUserUpdateRequest/useUpdateUser/userFieldsSchema.js';
import 'bs58';
import '@dynamic-labs/types';
import '../../../context/SocialRedirectContext/SocialRedirectContext.js';
import '../../../context/LoadingContext/LoadingContext.js';
import '../../../context/WalletContext/WalletContext.js';
import '../useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.js';
import 'yup';
import '../../../context/MockContext/MockContext.js';
import '../../../views/CollectUserDataView/useFields.js';
import '../../../context/FieldsStateContext/FieldsStateContext.js';
import '../../../context/UserFieldEditorContext/UserFieldEditorContext.js';
import '@dynamic-labs/rpc-providers';
import '../../../store/state/walletOptions/walletOptions.js';
import '../../../store/state/connectorsInitializing/connectorsInitializing.js';
import '../../../widgets/DynamicWidget/context/DynamicWidgetContext.js';
import '../../../store/state/tokenBalances.js';
import '../../../store/state/multichainBalances.js';
import '../../../context/WalletGroupContext/WalletGroupContext.js';
import '../../../shared/utils/functions/getInitialUrl/getInitialUrl.js';
import '../../../context/OnrampContext/OnrampContext.js';
import '../../../../index.js';
import 'react-dom';
import '../../../components/ShadowDOM/ShadowDOM.js';
import '../../../components/IconButton/IconButton.js';
import '../../../components/InlineWidget/InlineWidget.js';
import '../../../components/Input/Input.js';
import '../../../components/IsBrowser/IsBrowser.js';
import '../../../components/MenuList/Dropdown/Dropdown.js';
import '../../../components/OverlayCard/OverlayCard.js';
import '../../../components/Transition/ZoomTransition/ZoomTransition.js';
import '../../../components/Transition/SlideInUpTransition/SlideInUpTransition.js';
import '../../../components/Transition/OpacityTransition/OpacityTransition.js';
import '../../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.js';
import '../../../components/Popper/Popper/Popper.js';
import '../../../components/Popper/PopperContext/PopperContext.js';
import 'react-focus-lock';
import 'qrcode';
import 'formik';
import '../useSubdomainCheck/useSubdomainCheck.js';
import '../../../context/IpConfigurationContext/IpConfigurationContext.js';
import '../../../context/ConnectWithOtpContext/ConnectWithOtpContext.js';
import '../../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.js';
import '@hcaptcha/react-hcaptcha';
import '../../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.js';
import '../../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.js';
import '../../../context/ErrorContext/hooks/useErrorText/useErrorText.js';
import '../../../context/FooterAnimationContext/index.js';
import '../../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.js';
import '../../../context/PasskeyContext/PasskeyContext.js';
import '../../../store/state/sendBalances.js';
import '../../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.js';
import '../../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.js';
import '../../../views/TransactionConfirmationView/TransactionConfirmationView.js';
import '../../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.js';
import '../../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.js';
import '../../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.js';
import { SignMessageConfirmationModal } from '../../../modals/SignMessageConfirmationModal/SignMessageConfirmationModal.js';
import { SyncWalletPromptModal } from '../../../modals/SyncWalletPromptModal/SyncWalletPromptModal.js';
import { TransactionConfirmationModal } from '../../../modals/TransactionConfirmationModal/TransactionConfirmationModal.js';
import { AddNetworkModal } from '../../../modals/AddNetworkModal/AddNetworkModal.js';
import { ZkSyncApprovalModal } from '../../../modals/ZkSyncApprovalModal/ZkSyncApprovalModal.js';

const useWalletUiUtils = ({ hideEmbeddedWalletTransactionUIs = false, }) => {
    const confirmationStateRef = useRef('enabled');
    const { t } = useTranslation();
    const { modal: sendTransactionModal, open: openSendTransaction } = useConfirmationModal({
        elementId: 'dynamic-send-transaction',
    });
    const { modal: signMessageModal, open: openSignMessage } = useConfirmationModal({
        elementId: 'dynamic-sign-message',
    });
    const { modal: syncWalletPromptModal, open: openSyncWalletPrompt } = useConfirmationModal({
        elementId: 'dynamic-sync-wallet',
    });
    const { modal: addNetworkModal, open: openAddNetwork } = useConfirmationModal({
        elementId: 'dynamic-prompt-to-add-network',
    });
    const { modal: zkSyncCreateSessionModal, open: openZkSyncCreateSession } = useConfirmationModal({
        elementId: 'dynamic-zksync-approval',
    });
    const shouldConfirmAction = useCallback(({ walletConnector }) => {
        // For Dynamic Waas connector, we disable confirmation if hideEmbeddedWalletTransactionUIs is true
        // V2 wallets require the UI component to be rendered even if the confirmation is disabled
        // Waas does not require the UI component to be rendered so it can be skipped
        if ((walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.overrideKey) === 'dynamicwaas' &&
            hideEmbeddedWalletTransactionUIs) {
            return false;
        }
        if (confirmationStateRef.current === 'disabled') {
            confirmationStateRef.current = 'enabled';
            return false;
        }
        return true;
    }, [hideEmbeddedWalletTransactionUIs, confirmationStateRef]);
    const signMessage = useCallback((_a) => __awaiter(void 0, [_a], void 0, function* ({ walletConnector, message, handler }) {
        // prevent the modal from opening itself again
        if (!shouldConfirmAction({ walletConnector }))
            return handler();
        return openSignMessage((resolve, reject) => (jsx(SignMessageConfirmationModal, { message: message, handler: handler, onSignMessage: resolve, onReject: reject, hideModal: hideEmbeddedWalletTransactionUIs &&
                !(walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.isGlobalTransaction) }))).then((signedMessage) => __awaiter(void 0, void 0, void 0, function* () {
            if (signedMessage === 'callHandlerOutsideModal')
                return handler();
            else
                return signedMessage;
        }));
    }), [hideEmbeddedWalletTransactionUIs, openSignMessage, shouldConfirmAction]);
    const sendTransaction = useCallback((walletConnector, transaction) => __awaiter(void 0, void 0, void 0, function* () {
        // prevent the modal from opening itself again
        if (!shouldConfirmAction({ walletConnector }))
            return transaction.submit();
        return openSendTransaction((resolve, reject) => (jsx(TransactionConfirmationModal, { copykey: 'dyn_send_transaction.confirmation.title', title: t('dyn_send_transaction.confirmation.title'), transaction: transaction, onTransactionResponseSuccess: resolve, onReject: reject, walletConnector: walletConnector, hideModal: hideEmbeddedWalletTransactionUIs &&
                !(walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.isGlobalTransaction) }))).then((signedTransaction) => __awaiter(void 0, void 0, void 0, function* () {
            if (signedTransaction === 'callHandlerOutsideModal')
                return transaction.submit();
            else
                return signedTransaction;
        }));
    }), [
        hideEmbeddedWalletTransactionUIs,
        openSendTransaction,
        shouldConfirmAction,
        t,
    ]);
    // Solana only
    const signTransaction = useCallback((walletConnector, transaction) => __awaiter(void 0, void 0, void 0, function* () {
        // prevent the modal from opening itself again
        if (!shouldConfirmAction({ walletConnector }))
            return transaction.submit();
        return openSendTransaction((resolve, reject) => (jsx(TransactionConfirmationModal, { copykey: 'dyn_send_transaction.confirmation.title', title: t('dyn_send_transaction.confirmation.title'), transaction: transaction, onTransactionResponseSuccess: resolve, onReject: reject, walletConnector: walletConnector, hideModal: hideEmbeddedWalletTransactionUIs &&
                !(walletConnector === null || walletConnector === void 0 ? void 0 : walletConnector.isGlobalTransaction) }))).then((signedTransaction) => __awaiter(void 0, void 0, void 0, function* () {
            if (signedTransaction === 'callHandlerOutsideModal')
                return transaction.submit();
            else
                return signedTransaction;
        }));
    }), [
        hideEmbeddedWalletTransactionUIs,
        openSendTransaction,
        shouldConfirmAction,
        t,
    ]);
    const syncWallet = useCallback((_b) => __awaiter(void 0, [_b], void 0, function* ({ walletConnector, activeAddress, expectedAddress }) {
        yield openSyncWalletPrompt((resolve, reject) => (jsx(SyncWalletPromptModal, { onResolve: resolve, onReject: reject, connector: walletConnector, expectedAddress: expectedAddress, activeAddress: activeAddress })));
    }), [openSyncWalletPrompt]);
    const addNetwork = useCallback((_c) => __awaiter(void 0, [_c], void 0, function* ({ handler, network, walletConnector }) {
        yield openAddNetwork((resolve) => (jsx(AddNetworkModal, { network: network, walletConnector: walletConnector, onCancel: resolve, onNetworkAdded: resolve, addNetworkMutation: handler })));
    }), [openAddNetwork]);
    const zkSyncCreateSession = useCallback((_d) => __awaiter(void 0, [_d], void 0, function* ({ session: sessionConfig }) {
        return yield openZkSyncCreateSession((resolve, reject) => (jsx(ZkSyncApprovalModal, { session: sessionConfig, onCancel: reject, onApproved: () => resolve(true) })));
    }), [openZkSyncCreateSession]);
    const disabledConfirmationOnce = useCallback(() => {
        confirmationStateRef.current = 'disabled';
    }, []);
    const walletUiUtils = useMemo(() => ({
        addNetwork,
        disabledConfirmationOnce,
        sendTransaction,
        signMessage,
        signTransaction,
        syncWallet,
        zkSyncCreateSession,
    }), [
        signMessage,
        signTransaction,
        disabledConfirmationOnce,
        sendTransaction,
        syncWallet,
        addNetwork,
        zkSyncCreateSession,
    ]);
    return useMemo(() => [
        signMessageModal ||
            sendTransactionModal ||
            syncWalletPromptModal ||
            addNetworkModal ||
            zkSyncCreateSessionModal,
        walletUiUtils,
    ], [
        signMessageModal,
        sendTransactionModal,
        syncWalletPromptModal,
        addNetworkModal,
        zkSyncCreateSessionModal,
        walletUiUtils,
    ]);
};

export { useWalletUiUtils };
