'use client'
'use strict';

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

var React = require('react');
var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
var multiWallet = require('@dynamic-labs/multi-wallet');
var rpcProviders = require('@dynamic-labs/rpc-providers');
var walletBook = require('@dynamic-labs/wallet-book');
var useWalletItemActions = require('../../utils/hooks/useWalletItemActions/useWalletItemActions.cjs');
require('@dynamic-labs/iconic');
require('react/jsx-runtime');
require('../../context/ViewContext/ViewContext.cjs');
var logger = require('../../shared/logger.cjs');
var createWallet = require('../../shared/utils/functions/wallet/createWallet.cjs');
require('@dynamic-labs/utils');
require('../../utils/constants/colors.cjs');
require('../../utils/constants/values.cjs');
require('@dynamic-labs/sdk-api-core');
require('../../shared/consts/index.cjs');
var walletOptions = require('../../store/state/walletOptions/walletOptions.cjs');
var connectorsInitializing = require('../../store/state/connectorsInitializing/connectorsInitializing.cjs');
require('../../context/DynamicContext/DynamicContext.cjs');
require('../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('../../events/dynamicEvents.cjs');
require('../../../../_virtual/_tslib.cjs');
require('../../context/CaptchaContext/CaptchaContext.cjs');
require('../../context/ErrorContext/ErrorContext.cjs');
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');
require('../../context/AccessDeniedContext/AccessDeniedContext.cjs');
require('../../context/AccountExistsContext/AccountExistsContext.cjs');
require('../../context/UserWalletsContext/UserWalletsContext.cjs');
require('../../store/state/authMode/authMode.cjs');
require('../../context/VerificationContext/VerificationContext.cjs');
require('react-dom');
require('../../utils/functions/compareChains/compareChains.cjs');
require('../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('../../context/ThemeContext/ThemeContext.cjs');
require('../../utils/hooks/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('../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.cjs');
require('yup');
require('../../context/MockContext/MockContext.cjs');
require('../../views/CollectUserDataView/useFields.cjs');
require('../../context/FieldsStateContext/FieldsStateContext.cjs');
require('../../context/UserFieldEditorContext/UserFieldEditorContext.cjs');
require('react-i18next');
require('../Accordion/components/AccordionItem/AccordionItem.cjs');
require('../Alert/Alert.cjs');
require('../ShadowDOM/ShadowDOM.cjs');
require('../IconButton/IconButton.cjs');
require('../InlineWidget/InlineWidget.cjs');
require('../Input/Input.cjs');
require('../IsBrowser/IsBrowser.cjs');
require('../MenuList/Dropdown/Dropdown.cjs');
require('../OverlayCard/OverlayCard.cjs');
require('../Transition/ZoomTransition/ZoomTransition.cjs');
require('../Transition/SlideInUpTransition/SlideInUpTransition.cjs');
require('../Transition/OpacityTransition/OpacityTransition.cjs');
require('../PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.cjs');
require('../Popper/Popper/Popper.cjs');
require('../Popper/PopperContext/PopperContext.cjs');
require('react-focus-lock');
require('qrcode');
require('formik');
require('../../utils/hooks/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('../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 WalletConnectorEvents = ({ connectorProps, }) => {
    const { primaryWallet } = useInternalDynamicContext.useInternalDynamicContext();
    const { handleWalletItemClick } = useWalletItemActions.useWalletItemActions();
    const pendingConstructorRef = React.useRef([]);
    const injectedDebounceTimeoutRef = React.useRef();
    const pendingReadyConnectorsRef = React.useRef([]);
    const readyDebounceTimeoutRef = React.useRef();
    // need to add the timeout to ensure the setConnectorInitializing call is
    // not made in the same tick to avoid a bad setState call error from React
    const waitAndSetState = (func) => {
        setTimeout(() => {
            func();
        }, 0);
    };
    const walletConnectorConstructorOptions = React.useMemo(() => {
        var _a, _b;
        if (!connectorProps.projectSettings ||
            !connectorProps.networkConfigurations ||
            !walletBook.isWalletBookPopulated(connectorProps.walletBook)) {
            return;
        }
        return multiWallet.getWalletConnectorConstructorOptions(Object.assign(Object.assign({}, connectorProps), { chainRpcProviders: rpcProviders.ChainRpcProviders, settings: connectorProps.projectSettings, walletConnectProjectId: (_b = (_a = connectorProps.projectSettings) === null || _a === void 0 ? void 0 : _a.sdk.walletConnect) === null || _b === void 0 ? void 0 : _b.projectId }));
    }, [connectorProps]);
    // add listener for providerInjected event
    React.useEffect(() => {
        const processPendingConstructors = () => {
            if (pendingConstructorRef.current.length === 0) {
                return;
            }
            logger.logger.debug('[WalletConnectorEvents] processPendingConstructors', {
                pendingConstructors: pendingConstructorRef.current,
            });
            pendingConstructorRef.current.forEach((injectedConnectorConstructor) => {
                if (!walletConnectorConstructorOptions)
                    return;
                const injectedConnector = new injectedConnectorConstructor(walletConnectorConstructorOptions);
                logger.logger.debug('[WalletConnectorEvents] handleProviderInjected', {
                    injectedConnector,
                });
                walletConnectorCore.walletConnectorEvents.emit('providerReady', {
                    connector: injectedConnector,
                });
            });
            pendingConstructorRef.current = [];
        };
        const handleProviderInjected = ({ injectedConnectorConstructor, }) => {
            pendingConstructorRef.current.push(injectedConnectorConstructor);
            if (injectedDebounceTimeoutRef.current) {
                clearTimeout(injectedDebounceTimeoutRef.current);
            }
            injectedDebounceTimeoutRef.current = setTimeout(() => {
                processPendingConstructors();
            }, 100); // 100ms debounce window
        };
        walletConnectorCore.walletConnectorEvents.on('providerInjected', handleProviderInjected);
        return () => {
            walletConnectorCore.walletConnectorEvents.off('providerInjected', handleProviderInjected);
            if (injectedDebounceTimeoutRef.current) {
                clearTimeout(injectedDebounceTimeoutRef.current);
            }
            // Process any remaining constructors on cleanup
            processPendingConstructors();
        };
    }, [walletConnectorConstructorOptions]);
    // add listener for providerReady event
    React.useEffect(() => {
        const processReadyConnectors = () => {
            if (pendingReadyConnectorsRef.current.length === 0) {
                return;
            }
            logger.logger.logVerboseTroubleshootingMessage('[WalletConnectorEvents] processReadyConnectors', {
                connectors: pendingReadyConnectorsRef.current,
            });
            const walletConnectorOptions = walletOptions.getWalletConnectorOptions();
            const updatedConnectors = [...walletConnectorOptions];
            let walletOptionToAutoConnect;
            pendingReadyConnectorsRef.current.forEach(({ connector, shouldAutoConnect }) => {
                let foundWallet = false;
                for (let i = 0; i < updatedConnectors.length; i++) {
                    const hasSameKey = updatedConnectors[i].key === connector.key;
                    const isReplacingNonWalletConnectWithWalletConnect = !updatedConnectors[i].walletConnector.isWalletConnect &&
                        connector.isWalletConnect;
                    if (hasSameKey && !isReplacingNonWalletConnectWithWalletConnect) {
                        updatedConnectors[i] = Object.assign(Object.assign({}, updatedConnectors[i]), { isInstalledOnBrowser: connector.isInstalledOnBrowser(), walletConnector: connector });
                    }
                    if (hasSameKey) {
                        foundWallet = true;
                        break;
                    }
                }
                if (!foundWallet) {
                    const newWalletOption = createWallet.createWallet(connectorProps.walletBook, connector);
                    updatedConnectors.push(newWalletOption);
                }
                if (shouldAutoConnect) {
                    walletOptionToAutoConnect = updatedConnectors.find((wallet) => wallet.key === connector.key &&
                        !wallet.walletConnector.isWalletConnect);
                }
            });
            walletOptions.mergeWalletConnectorOptions(updatedConnectors);
            pendingReadyConnectorsRef.current = [];
            logger.logger.logVerboseTroubleshootingMessage('[WalletConnectorEvents] processReadyConnectors', {
                walletOptionToAutoConnect,
            });
            if (walletOptionToAutoConnect && !primaryWallet) {
                handleWalletItemClick(walletOptionToAutoConnect);
            }
        };
        const handleProviderReady = (props) => {
            logger.logger.logVerboseTroubleshootingMessage('[WalletConnectorEvents] handleProviderReady', props);
            pendingReadyConnectorsRef.current.push(props);
            if (readyDebounceTimeoutRef.current) {
                clearTimeout(readyDebounceTimeoutRef.current);
            }
            readyDebounceTimeoutRef.current = setTimeout(() => {
                processReadyConnectors();
            }, 100); // 100ms debounce window
        };
        if (!walletBook.isWalletBookPopulated(connectorProps.walletBook)) {
            return;
        }
        walletConnectorCore.walletConnectorEvents.on('providerReady', handleProviderReady);
        return () => {
            walletConnectorCore.walletConnectorEvents.off('providerReady', handleProviderReady);
            if (readyDebounceTimeoutRef.current) {
                clearTimeout(readyDebounceTimeoutRef.current);
            }
            // Process any remaining connectors on cleanup
            processReadyConnectors();
        };
    }, [connectorProps.walletBook, handleWalletItemClick]);
    // add listener for connectorInitStarted and connectorInitCompleted events
    React.useEffect(() => {
        const handleConnectorInitStarted = (key) => {
            logger.logger.logVerboseTroubleshootingMessage('[WalletConnectorEvents] handleConnectorInitStarted', { key });
            waitAndSetState(() => {
                connectorsInitializing.setConnectorInitializing(key, true);
            });
        };
        const handleConnectorInitCompleted = (key) => {
            logger.logger.logVerboseTroubleshootingMessage('[WalletConnectorEvents] handleConnectorInitCompleted', { key });
            waitAndSetState(() => {
                connectorsInitializing.setConnectorInitializing(key, false);
            });
        };
        walletConnectorCore.walletConnectorEvents.on('connectorInitStarted', handleConnectorInitStarted);
        walletConnectorCore.walletConnectorEvents.on('connectorInitCompleted', handleConnectorInitCompleted);
        return () => {
            walletConnectorCore.walletConnectorEvents.off('connectorInitStarted', handleConnectorInitStarted);
            walletConnectorCore.walletConnectorEvents.off('connectorInitCompleted', handleConnectorInitCompleted);
        };
    }, []);
    return null;
};

exports.WalletConnectorEvents = WalletConnectorEvents;
