'use client'
'use strict';

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

var _tslib = require('../../../../../_virtual/_tslib.cjs');
var React = require('react');
var utils = require('@dynamic-labs/utils');
var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
var UserWalletsContext = require('../../../context/UserWalletsContext/UserWalletsContext.cjs');
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('../../constants/colors.cjs');
require('../../constants/values.cjs');
require('@dynamic-labs/sdk-api-core');
require('../../../shared/consts/index.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 createLinkedWalletsFromWalletOptions = require('./utils/createLinkedWalletsFromWalletOptions/createLinkedWalletsFromWalletOptions.cjs');
var updateUserWalletsFromLinkedWallets = require('./utils/updateUserWalletsFromLinkedWallets/updateUserWalletsFromLinkedWallets.cjs');

const useWalletConnectors = ({ connectedWallets, walletConnectorOptions, setMultiWalletWidgetState, primaryWalletId, user, canHaveMultipleWalletsConnected, separateSmartWalletAndSigner = false, }) => {
    const [showQrcodeModal, setShowQrcodeModal] = React.useState(false);
    // keeps track of the last primary wallet id to avoid emitting the same event multiple times
    const lastPrimaryWalletId = React.useRef(primaryWalletId);
    const linkedWallets = React.useMemo(() => {
        if (!user) {
            return [];
        }
        return createLinkedWalletsFromWalletOptions.createLinkedWalletsFromWalletOptions({
            primaryWalletId,
            separateSmartWalletAndSigner,
            user,
            walletConnectorOptions,
        });
    }, [
        user,
        primaryWalletId,
        walletConnectorOptions,
        separateSmartWalletAndSigner,
    ]);
    logger.logger.logVerboseTroubleshootingMessage('linkedWallets', linkedWallets);
    const wallets = React.useMemo(() => {
        if (user) {
            return linkedWallets;
        }
        // This is to handle users in connect-only who have not yet connected a wallet
        return connectedWallets !== null && connectedWallets !== void 0 ? connectedWallets : [];
    }, [connectedWallets, linkedWallets, user]);
    logger.logger.logVerboseTroubleshootingMessage('wallets', wallets);
    /**
     * This useEffect is temporary.
     * While the wallet connectors don't use the event emitter, we need to manually
     * initialize the bridge between the old event listeners and the new event emitter.
     * When the wallet connectors are migrated to the new event emitter, there will be no
     * need to initialize or teardown event listeners, then we can remove this useEffect.
     */
    React.useEffect(() => wallets.forEach((wallet) => {
        wallet.connector.initEventListener();
    }), [wallets]);
    const { setUserWallets } = UserWalletsContext.useInternalUserWallets();
    // Keep userWallets in sync whenever linkedWallets changes
    React.useEffect(() => {
        logger.logger.logVerboseTroubleshootingMessage('[useWalletConnectors] will call setUserWallets', wallets);
        setUserWallets((userWallets) => updateUserWalletsFromLinkedWallets.updateUserWalletsFromLinkedWallets(userWallets, wallets));
    }, [setUserWallets, wallets]);
    const primaryWallet = React.useMemo(() => { var _a; return (_a = wallets.find((wallet) => wallet.id === primaryWalletId)) !== null && _a !== void 0 ? _a : null; }, [primaryWalletId, wallets]);
    // emit primaryWalletChanged event if the primary wallet changes
    React.useEffect(() => {
        if (primaryWallet && primaryWallet.id !== lastPrimaryWalletId.current) {
            dynamicEvents.dynamicEvents.emit('primaryWalletChanged', primaryWallet);
        }
        lastPrimaryWalletId.current = primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.id;
    }, [primaryWallet]);
    const secondaryWallets = React.useMemo(() => canHaveMultipleWalletsConnected
        ? wallets.filter((wallet) => wallet.id !== primaryWalletId)
        : [], [primaryWalletId, wallets, canHaveMultipleWalletsConnected]);
    const getSelectedWallet = React.useCallback((walletId) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        const newWallet = wallets.find(({ id }) => id === walletId);
        if (!newWallet) {
            throw new utils.DynamicError(`Wallet with id: ${walletId} not found`, 'wallet_with_id_not_found');
        }
        return newWallet;
    }), [wallets]);
    const setPrimaryWallet = React.useCallback((walletId) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        const newPrimaryWallet = yield getSelectedWallet(walletId);
        if (!primaryWalletId) {
            updatePrimaryWalletId.updatePrimaryWalletId(walletId);
            return;
        }
        if (primaryWalletId === walletId)
            return;
        if (walletConnectorCore.isEmailWalletConnector(newPrimaryWallet.connector)) {
            const emailConnector = newPrimaryWallet.connector;
            const email = localStorage.getItem('magic-link-email');
            if (email) {
                emailConnector.setEmail(email);
            }
        }
        updatePrimaryWalletId.updatePrimaryWalletId(walletId);
        setMultiWalletWidgetState('idle');
    }), [getSelectedWallet, primaryWalletId, setMultiWalletWidgetState]);
    return {
        primaryWallet,
        secondaryWallets,
        setPrimaryWallet,
        setShowQrcodeModal,
        showQrcodeModal,
        wallets,
    };
};

exports.useWalletConnectors = useWalletConnectors;
