'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { useCallback, useMemo, useEffect } from 'react';
import '../../../context/DynamicContext/useDynamicContext/useDynamicContext.js';
import { useInternalDynamicContext } from '../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import { useViewContext } from '../../../context/ViewContext/ViewContext.js';
import '@dynamic-labs/sdk-api-core';
import '../../constants/values.js';
import '@dynamic-labs/utils';
import '@dynamic-labs/multi-wallet';
import '../../../shared/logger.js';
import 'react-international-phone';
import '../../constants/colors.js';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import 'react/jsx-runtime';
import '@dynamic-labs/wallet-book';
import '../../../shared/consts/index.js';
import '../../../store/state/nonce/nonce.js';
import { isProgrammableNetworkSwitchSupported } from '../../functions/isProgrammableNetworkSwitchSupported/isProgrammableNetworkSwitchSupported.js';
import { isSupportedNetwork } from '../../functions/isSupportedNetwork/isSupportedNetwork.js';
import '@dynamic-labs-wallet/browser-wallet-client';
import '@dynamic-labs-sdk/client/core';
import 'eventemitter3';
import '@dynamic-labs-sdk/client';
import '../../../config/ApiEndpoint.js';
import '../../../events/dynamicEvents.js';
import '@dynamic-labs/locale';
import '../../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../../store/state/primaryWalletId/primaryWalletId.js';
import '../../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../../functions/getWaasAddressTypeLabel/getWaasAddressTypeLabel.js';
import { useIsLoggedIn } from '../useIsLoggedIn/useIsLoggedIn.js';
import { useWalletConnectorEvent } from '../events/useWalletConnectorEvent/useWalletConnectorEvent.js';

const useConnectedWalletsNetworkValidation = () => {
    const { connectedWallets, selectedWalletConnector, setSelectedWalletConnectorKey, setShowAuthFlow, bridgeChainsToConnect, sdkHasLoaded, } = useInternalDynamicContext();
    const { pushView } = useViewContext();
    const isLoggedIn = useIsLoggedIn();
    const getConnectedWalletsWithInvalidNetwork = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
        const connectedWalletsWithInvalidNetwork = [];
        for (const connectedWallet of connectedWallets) {
            const isChainInWalletsToConnect = bridgeChainsToConnect === null || bridgeChainsToConnect === void 0 ? void 0 : bridgeChainsToConnect.some((walletToConnectByChain) => walletToConnectByChain.chain === connectedWallet.chain);
            const network = yield connectedWallet.connector.getNetwork(true);
            const isSupported = isSupportedNetwork({
                network,
                walletConnector: connectedWallet.connector,
            });
            if (!isChainInWalletsToConnect && !isSupported) {
                connectedWalletsWithInvalidNetwork.push(connectedWallet);
            }
        }
        return connectedWalletsWithInvalidNetwork;
    }), [bridgeChainsToConnect, connectedWallets]);
    const validateNetwork = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
        const connectedWalletsWithInvalidNetwork = yield getConnectedWalletsWithInvalidNetwork();
        if (!connectedWalletsWithInvalidNetwork.length) {
            return;
        }
        // If we found wallets that require a change of network
        // then, one by one, in the first one we require a change of network.
        const [connectedWalletWithInvalidNetwork] = connectedWalletsWithInvalidNetwork;
        // Keeps the first wallet connectedWallet in setSelectedWalletConnectorKey
        // This is required because NetworkNotSupported uses walletConnector to display wallet icon, address etc.
        if (connectedWalletWithInvalidNetwork.connector.key !==
            (selectedWalletConnector === null || selectedWalletConnector === void 0 ? void 0 : selectedWalletConnector.key)) {
            setSelectedWalletConnectorKey({
                chain: connectedWalletWithInvalidNetwork.connector.connectedChain,
                key: connectedWalletWithInvalidNetwork.connector.key,
            });
        }
        const networkNotSupportedView = isProgrammableNetworkSwitchSupported(connectedWalletWithInvalidNetwork.connector)
            ? 'network-not-supported'
            : 'network-not-supported-manual';
        // Doesn't rerender if it's already true
        setShowAuthFlow(true);
        pushView(networkNotSupportedView);
    }), [
        getConnectedWalletsWithInvalidNetwork,
        selectedWalletConnector === null || selectedWalletConnector === void 0 ? void 0 : selectedWalletConnector.key,
        setSelectedWalletConnectorKey,
        setShowAuthFlow,
        pushView,
    ]);
    const uniqueConnectors = useMemo(() => {
        const connectors = connectedWallets.map(({ connector }) => connector);
        const allWalletConnectors = new Set([...connectors].filter((connector) => Boolean(connector)));
        return Array.from(allWalletConnectors);
    }, [connectedWallets]);
    useWalletConnectorEvent(uniqueConnectors, 'chainChange', ({ chain }) => {
        validateNetwork();
    });
    useEffect(() => {
        /**
         * This check was added to prevent the "wrong network" modal from appearing
         * after logging out. It seems like on log out, there is a render where the
         * connectedWallets hasn't been cleared out yet, so the logic in this hook
         * runs and ends up showing the "wrong network" modal if the connected wallet
         * is on an unsupported network. by checking sdkHasLoaded, we prevent this
         * extra popup because handleLogOut flips sdkHasLoaded to false, so on the
         * next render it will already be false.
         */
        if (!sdkHasLoaded || !isLoggedIn) {
            return;
        }
        validateNetwork();
    }, [sdkHasLoaded, isLoggedIn, validateNetwork]);
};

export { useConnectedWalletsNetworkValidation };
