'use client'
import { useRef, useMemo, useEffect } from 'react';
import { walletConnectorEvents } from '@dynamic-labs/wallet-connector-core';
import { getWalletConnectorConstructorOptions } from '@dynamic-labs/multi-wallet';
import { ChainRpcProviders } from '@dynamic-labs/rpc-providers';
import { isWalletBookPopulated } from '@dynamic-labs/wallet-book';
import { useWalletItemActions } from '../../utils/hooks/useWalletItemActions/useWalletItemActions.js';
import '@dynamic-labs/iconic';
import 'react/jsx-runtime';
import '../../context/ViewContext/ViewContext.js';
import { logger } from '../../shared/logger.js';
import { createWallet } from '../../shared/utils/functions/wallet/createWallet.js';
import '@dynamic-labs/utils';
import '../../utils/constants/colors.js';
import '../../utils/constants/values.js';
import '@dynamic-labs/sdk-api-core';
import '../../shared/consts/index.js';
import { getWalletConnectorOptions, mergeWalletConnectorOptions } from '../../store/state/walletOptions/walletOptions.js';
import { setConnectorInitializing } from '../../store/state/connectorsInitializing/connectorsInitializing.js';
import '../../context/DynamicContext/DynamicContext.js';
import '../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '../../events/dynamicEvents.js';
import '../../../../_virtual/_tslib.js';
import '../../context/CaptchaContext/CaptchaContext.js';
import '../../context/ErrorContext/ErrorContext.js';
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 '../../store/state/authMode/authMode.js';
import '../../context/VerificationContext/VerificationContext.js';
import 'react-dom';
import '../../utils/functions/compareChains/compareChains.js';
import '../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import '../../context/ThemeContext/ThemeContext.js';
import '../../utils/hooks/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 '../../utils/hooks/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 'react-i18next';
import '../Accordion/components/AccordionItem/AccordionItem.js';
import '../Alert/Alert.js';
import '../ShadowDOM/ShadowDOM.js';
import '../IconButton/IconButton.js';
import '../InlineWidget/InlineWidget.js';
import '../Input/Input.js';
import '../IsBrowser/IsBrowser.js';
import '../MenuList/Dropdown/Dropdown.js';
import '../OverlayCard/OverlayCard.js';
import '../Transition/ZoomTransition/ZoomTransition.js';
import '../Transition/SlideInUpTransition/SlideInUpTransition.js';
import '../Transition/OpacityTransition/OpacityTransition.js';
import '../PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.js';
import '../Popper/Popper/Popper.js';
import '../Popper/PopperContext/PopperContext.js';
import 'react-focus-lock';
import 'qrcode';
import 'formik';
import '../../utils/hooks/useSubdomainCheck/useSubdomainCheck.js';
import '../../context/WalletGroupContext/WalletGroupContext.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/context/DynamicWidgetContext.js';
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 '../../context/OnrampContext/OnrampContext.js';
import '../../store/state/sendBalances.js';
import '../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 '../../../index.js';
import '../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.js';
import '../../store/state/tokenBalances.js';
import '../../store/state/multichainBalances.js';
import '../../shared/utils/functions/getInitialUrl/getInitialUrl.js';
import { useInternalDynamicContext } from '../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';

const WalletConnectorEvents = ({ connectorProps, }) => {
    const { primaryWallet } = useInternalDynamicContext();
    const { handleWalletItemClick } = useWalletItemActions();
    const pendingConstructorRef = useRef([]);
    const injectedDebounceTimeoutRef = useRef();
    const pendingReadyConnectorsRef = useRef([]);
    const readyDebounceTimeoutRef = 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 = useMemo(() => {
        var _a, _b;
        if (!connectorProps.projectSettings ||
            !connectorProps.networkConfigurations ||
            !isWalletBookPopulated(connectorProps.walletBook)) {
            return;
        }
        return getWalletConnectorConstructorOptions(Object.assign(Object.assign({}, connectorProps), { chainRpcProviders: 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
    useEffect(() => {
        const processPendingConstructors = () => {
            if (pendingConstructorRef.current.length === 0) {
                return;
            }
            logger.debug('[WalletConnectorEvents] processPendingConstructors', {
                pendingConstructors: pendingConstructorRef.current,
            });
            pendingConstructorRef.current.forEach((injectedConnectorConstructor) => {
                if (!walletConnectorConstructorOptions)
                    return;
                const injectedConnector = new injectedConnectorConstructor(walletConnectorConstructorOptions);
                logger.debug('[WalletConnectorEvents] handleProviderInjected', {
                    injectedConnector,
                });
                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
        };
        walletConnectorEvents.on('providerInjected', handleProviderInjected);
        return () => {
            walletConnectorEvents.off('providerInjected', handleProviderInjected);
            if (injectedDebounceTimeoutRef.current) {
                clearTimeout(injectedDebounceTimeoutRef.current);
            }
            // Process any remaining constructors on cleanup
            processPendingConstructors();
        };
    }, [walletConnectorConstructorOptions]);
    // add listener for providerReady event
    useEffect(() => {
        const processReadyConnectors = () => {
            if (pendingReadyConnectorsRef.current.length === 0) {
                return;
            }
            logger.logVerboseTroubleshootingMessage('[WalletConnectorEvents] processReadyConnectors', {
                connectors: pendingReadyConnectorsRef.current,
            });
            const walletConnectorOptions = 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(connectorProps.walletBook, connector);
                    updatedConnectors.push(newWalletOption);
                }
                if (shouldAutoConnect) {
                    walletOptionToAutoConnect = updatedConnectors.find((wallet) => wallet.key === connector.key &&
                        !wallet.walletConnector.isWalletConnect);
                }
            });
            mergeWalletConnectorOptions(updatedConnectors);
            pendingReadyConnectorsRef.current = [];
            logger.logVerboseTroubleshootingMessage('[WalletConnectorEvents] processReadyConnectors', {
                walletOptionToAutoConnect,
            });
            if (walletOptionToAutoConnect && !primaryWallet) {
                handleWalletItemClick(walletOptionToAutoConnect);
            }
        };
        const handleProviderReady = (props) => {
            logger.logVerboseTroubleshootingMessage('[WalletConnectorEvents] handleProviderReady', props);
            pendingReadyConnectorsRef.current.push(props);
            if (readyDebounceTimeoutRef.current) {
                clearTimeout(readyDebounceTimeoutRef.current);
            }
            readyDebounceTimeoutRef.current = setTimeout(() => {
                processReadyConnectors();
            }, 100); // 100ms debounce window
        };
        if (!isWalletBookPopulated(connectorProps.walletBook)) {
            return;
        }
        walletConnectorEvents.on('providerReady', handleProviderReady);
        return () => {
            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
    useEffect(() => {
        const handleConnectorInitStarted = (key) => {
            logger.logVerboseTroubleshootingMessage('[WalletConnectorEvents] handleConnectorInitStarted', { key });
            waitAndSetState(() => {
                setConnectorInitializing(key, true);
            });
        };
        const handleConnectorInitCompleted = (key) => {
            logger.logVerboseTroubleshootingMessage('[WalletConnectorEvents] handleConnectorInitCompleted', { key });
            waitAndSetState(() => {
                setConnectorInitializing(key, false);
            });
        };
        walletConnectorEvents.on('connectorInitStarted', handleConnectorInitStarted);
        walletConnectorEvents.on('connectorInitCompleted', handleConnectorInitCompleted);
        return () => {
            walletConnectorEvents.off('connectorInitStarted', handleConnectorInitStarted);
            walletConnectorEvents.off('connectorInitCompleted', handleConnectorInitCompleted);
        };
    }, []);
    return null;
};

export { WalletConnectorEvents };
