'use client'
'use strict';

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

var _tslib = require('../../../../../_virtual/_tslib.cjs');
var React = require('react');
var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
require('@dynamic-labs/iconic');
require('react/jsx-runtime');
require('../../../context/ViewContext/ViewContext.cjs');
var logger = require('../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('@dynamic-labs/utils');
require('../../constants/colors.cjs');
require('../../constants/values.cjs');
require('@dynamic-labs/sdk-api-core');
require('../../../shared/consts/index.cjs');
var useDynamicEvents = require('../events/useDynamicEvents/useDynamicEvents.cjs');
var useWalletConnectorEvent = require('../events/useWalletConnectorEvent/useWalletConnectorEvent.cjs');
var dynamicEvents = require('../../../events/dynamicEvents.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../store/state/nonce/nonce.cjs');
require('@dynamic-labs-wallet/browser-wallet-client');
require('@dynamic-labs-sdk/client/core');
require('eventemitter3');
require('@dynamic-labs-sdk/client');
require('../../../config/ApiEndpoint.cjs');
var updatePrimaryWalletId = require('../../functions/updatePrimaryWalletId/updatePrimaryWalletId.cjs');
require('../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('@dynamic-labs/locale');
require('../../functions/getWaasAddressTypeLabel/getWaasAddressTypeLabel.cjs');
var authMode = require('../../../store/state/authMode/authMode.cjs');

const useWalletEventListeners = ({ disconnectWallet, handleLogOutWithReason, multiWallet, multiWalletWidgetState, primaryWallet, secondaryWallets, selectedWalletConnector, selectedWalletWithAction, setSelectedWalletConnectorKey, setSelectedWalletWithAction, setMultiWalletWidgetState, user, refreshConnectedWallet, detectNewWalletsForLinking, }) => {
    const handleAccountChangeWhenAwaitingAccountSwitch = React.useCallback((isPrimaryWallet, newAddress) => {
        logger.logger.debug('handleAccountChangeWhenAwaitingAccountSwitch', {
            isPrimaryWallet,
            newAddress,
        });
        const linkedSecondaryWallet = secondaryWallets.find((wallet) => walletConnectorCore.isSameAddress(wallet.address, newAddress, wallet.chain));
        logger.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.dynamicEvents.emit('triggerConnectAndSign');
            return;
        }
        // ...otherwise, the user is switching primary accounts betweeen the same wallet
        setSelectedWalletWithAction(null);
        updatePrimaryWalletId.updatePrimaryWalletId(linkedSecondaryWallet.id);
        setMultiWalletWidgetState('idle');
    }, [
        setMultiWalletWidgetState,
        primaryWallet,
        secondaryWallets,
        setSelectedWalletConnectorKey,
        setSelectedWalletWithAction,
    ]);
    const calculatePrimaryWalletMultiWalletStateFromAccounts = React.useCallback(({ accounts }) => {
        const authMode$1 = authMode.getAuthMode();
        logger.logger.debug('calculatePrimaryWalletMultiWalletStateFromAccounts', {
            accounts,
            authMode: authMode$1,
            multiWallet,
            multiWalletWidgetState,
            primaryWallet,
        });
        // change the api here
        if (!primaryWallet)
            return;
        const [newAddress] = accounts;
        const changedAddress = !walletConnectorCore.isSameAddress(newAddress, primaryWallet.address, primaryWallet.chain);
        if (!changedAddress) {
            setMultiWalletWidgetState('idle');
            return;
        }
        if (authMode$1 === 'connect-only') {
            refreshConnectedWallet(primaryWallet.id, primaryWallet.connector);
            return;
        }
        if (!multiWallet) {
            return;
        }
        if (multiWalletWidgetState === 'awaiting_account_switch') {
            handleAccountChangeWhenAwaitingAccountSwitch(true, newAddress);
            return;
        }
        if (multiWalletWidgetState !== 'idle') {
            logger.logger.error(`Unexpected multiWalletWidgetState (${multiWalletWidgetState}) and onAccountChange combination. Resetting state to idle.`);
            setMultiWalletWidgetState('idle');
        }
        const newWallet = secondaryWallets.find((wallet) => walletConnectorCore.isSameAddress(wallet.address, newAddress, wallet.chain));
        if (newWallet) {
            updatePrimaryWalletId.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,
    ]);
    useDynamicEvents.useInternalDynamicEvents('triggerComputePrimaryWalletMultiWalletStateFromAccounts', calculatePrimaryWalletMultiWalletStateFromAccounts);
    useWalletConnectorEvent.useWalletConnectorEvent(primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector, 'accountChange', ({ accounts }) => {
        logger.logger.debug('primary wallet account change', {
            accounts,
        });
        calculatePrimaryWalletMultiWalletStateFromAccounts({ accounts });
    });
    const uniqueNonPrimaryWallets = React.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.useWalletConnectorEvent(uniqueNonPrimaryWallets, 'accountChange', (_, changedConnector) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        logger.logger.debug('secondary wallet account change');
        const authMode$1 = authMode.getAuthMode();
        if (authMode$1 === '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.useWalletConnectorEvent(primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.connector, 'disconnect', () => {
        logger.logger.debug('primary wallet disconnect');
        const authMode$1 = authMode.getAuthMode();
        if (authMode$1 === 'connect-only') {
            handleLogOutWithReason('primary-wallet-disconnected');
        }
    });
    useWalletConnectorEvent.useWalletConnectorEvent(uniqueNonPrimaryWallets, 'disconnect', (affectedConnector) => {
        logger.logger.debug('secondary wallet disconnect');
        const authMode$1 = authMode.getAuthMode();
        if (authMode$1 === '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.useWalletConnectorEvent(uniqueNonPrimaryWallets, 'chainChange', ({ chain }, connector) => {
        dynamicEvents.dynamicEvents.emit('nonPrimaryWalletNetworkChanged', chain, connector);
    });
};

exports.useWalletEventListeners = useWalletEventListeners;
