'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { useCallback, useMemo } from 'react';
import { isSameAddress } from '@dynamic-labs/wallet-connector-core';
import '@dynamic-labs/iconic';
import 'react/jsx-runtime';
import '../../../context/ViewContext/ViewContext.js';
import { logger } from '../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '@dynamic-labs/utils';
import '../../constants/colors.js';
import '../../constants/values.js';
import '@dynamic-labs/sdk-api-core';
import '../../../shared/consts/index.js';
import { useInternalDynamicEvents } from '../events/useDynamicEvents/useDynamicEvents.js';
import { useWalletConnectorEvent } from '../events/useWalletConnectorEvent/useWalletConnectorEvent.js';
import { dynamicEvents } from '../../../events/dynamicEvents.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../../store/state/nonce/nonce.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 { updatePrimaryWalletId } from '../../functions/updatePrimaryWalletId/updatePrimaryWalletId.js';
import '../../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../../store/state/primaryWalletId/primaryWalletId.js';
import '@dynamic-labs/locale';
import '../../functions/getWaasAddressTypeLabel/getWaasAddressTypeLabel.js';
import { getAuthMode } from '../../../store/state/authMode/authMode.js';

const useWalletEventListeners = ({ disconnectWallet, handleLogOutWithReason, multiWallet, multiWalletWidgetState, primaryWallet, secondaryWallets, selectedWalletConnector, selectedWalletWithAction, setSelectedWalletConnectorKey, setSelectedWalletWithAction, setMultiWalletWidgetState, user, refreshConnectedWallet, detectNewWalletsForLinking, }) => {
    const handleAccountChangeWhenAwaitingAccountSwitch = useCallback((isPrimaryWallet, newAddress) => {
        logger.debug('handleAccountChangeWhenAwaitingAccountSwitch', {
            isPrimaryWallet,
            newAddress,
        });
        const linkedSecondaryWallet = secondaryWallets.find((wallet) => isSameAddress(wallet.address, newAddress, wallet.chain));
        logger.logVerboseTroubleshootingMessage('[handleAccountChangeWhenAwaitingAccountSwitch]', { linkedSecondaryWallet });
        // this means the user is linking a new account, so we need proof of ownership...
        if (!linkedSecondaryWallet) {
            setMultiWalletWidgetState('awaiting_signature', undefined, 'linking_new_wallet');
            if (isPrimaryWallet && primaryWallet) {
                setSelectedWalletConnectorKey({
                    chain: primaryWallet.connector.connectedChain,
                    key: primaryWallet.connector.key,
                });
            }
            return;
        }
        if (!linkedSecondaryWallet.connector.isAvailable) {
            //prompt the user to connect and sign with the wallet
            dynamicEvents.emit('triggerConnectAndSign');
            return;
        }
        // ...otherwise, the user is switching primary accounts betweeen the same wallet
        setSelectedWalletWithAction(null);
        updatePrimaryWalletId(linkedSecondaryWallet.id);
        setMultiWalletWidgetState('idle');
    }, [
        setMultiWalletWidgetState,
        primaryWallet,
        secondaryWallets,
        setSelectedWalletConnectorKey,
        setSelectedWalletWithAction,
    ]);
    const calculatePrimaryWalletMultiWalletStateFromAccounts = useCallback(({ accounts }) => {
        const authMode = getAuthMode();
        logger.debug('calculatePrimaryWalletMultiWalletStateFromAccounts', {
            accounts,
            authMode,
            multiWallet,
            multiWalletWidgetState,
            primaryWallet,
        });
        // change the api here
        if (!primaryWallet)
            return;
        const [newAddress] = accounts;
        const changedAddress = !isSameAddress(newAddress, primaryWallet.address, primaryWallet.chain);
        if (!changedAddress) {
            setMultiWalletWidgetState('idle');
            return;
        }
        if (authMode === 'connect-only') {
            refreshConnectedWallet(primaryWallet.id, primaryWallet.connector);
            return;
        }
        if (!multiWallet) {
            return;
        }
        if (multiWalletWidgetState === 'awaiting_account_switch') {
            handleAccountChangeWhenAwaitingAccountSwitch(true, newAddress);
            return;
        }
        if (multiWalletWidgetState !== 'idle') {
            logger.error(`Unexpected multiWalletWidgetState (${multiWalletWidgetState}) and onAccountChange combination. Resetting state to idle.`);
            setMultiWalletWidgetState('idle');
        }
        const newWallet = secondaryWallets.find((wallet) => isSameAddress(wallet.address, newAddress, wallet.chain));
        if (newWallet) {
            updatePrimaryWalletId(newWallet.id);
            return;
        }
        if (user && detectNewWalletsForLinking) {
            setMultiWalletWidgetState('detected_new_wallet');
            setSelectedWalletConnectorKey({
                chain: primaryWallet.connector.connectedChain,
                key: primaryWallet.connector.key,
            });
        }
    }, [
        detectNewWalletsForLinking,
        handleAccountChangeWhenAwaitingAccountSwitch,
        multiWallet,
        multiWalletWidgetState,
        primaryWallet,
        refreshConnectedWallet,
        secondaryWallets,
        setMultiWalletWidgetState,
        setSelectedWalletConnectorKey,
        user,
    ]);
    useInternalDynamicEvents('triggerComputePrimaryWalletMultiWalletStateFromAccounts', calculatePrimaryWalletMultiWalletStateFromAccounts);
    useWalletConnectorEvent(primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector, 'accountChange', ({ accounts }) => {
        logger.debug('primary wallet account change', {
            accounts,
        });
        calculatePrimaryWalletMultiWalletStateFromAccounts({ accounts });
    });
    const uniqueNonPrimaryWallets = useMemo(() => {
        const primaryConnector = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector;
        const secondaryConnectors = secondaryWallets.map(({ connector }) => connector);
        const allWalletConnectors = new Set([
            ...secondaryConnectors,
            primaryConnector,
            selectedWalletConnector,
        ].filter((connector) => Boolean(connector)));
        if (primaryConnector) {
            allWalletConnectors.delete(primaryConnector);
        }
        return Array.from(allWalletConnectors);
    }, [secondaryWallets, selectedWalletConnector, primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector]);
    useWalletConnectorEvent(uniqueNonPrimaryWallets, 'accountChange', (_, changedConnector) => __awaiter(void 0, void 0, void 0, function* () {
        logger.debug('secondary wallet account change');
        const authMode = getAuthMode();
        if (authMode === 'connect-only' && secondaryWallets.length) {
            const affectedWallets = secondaryWallets.filter(({ connector }) => connector.key === changedConnector.key);
            for (const wallet of affectedWallets)
                refreshConnectedWallet(wallet.id, wallet.connector);
            return;
        }
        if (multiWalletWidgetState === 'awaiting_account_switch') {
            handleAccountChangeWhenAwaitingAccountSwitch(false, (selectedWalletWithAction === null || selectedWalletWithAction === void 0 ? void 0 : selectedWalletWithAction.wallet.address) || '');
        }
    }));
    useWalletConnectorEvent(primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector, 'disconnect', () => {
        logger.debug('primary wallet disconnect');
        const authMode = getAuthMode();
        if (authMode === 'connect-only') {
            handleLogOutWithReason('primary-wallet-disconnected');
        }
    });
    useWalletConnectorEvent(uniqueNonPrimaryWallets, 'disconnect', (affectedConnector) => {
        logger.debug('secondary wallet disconnect');
        const authMode = getAuthMode();
        if (authMode === 'connect-only') {
            // Get all wallets with this connector
            const affectedWallets = secondaryWallets.filter(({ connector }) => connector.key === affectedConnector.key);
            for (const wallet of affectedWallets) {
                disconnectWallet(wallet.id);
            }
        }
    });
    useWalletConnectorEvent(uniqueNonPrimaryWallets, 'chainChange', ({ chain }, connector) => {
        dynamicEvents.emit('nonPrimaryWalletNetworkChanged', chain, connector);
    });
};

export { useWalletEventListeners };
