'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { useCallback } from 'react';
import { isMobile } from '@dynamic-labs/utils';
import { isTurnkeyWalletConnector, isEmailWalletConnector } from '@dynamic-labs/wallet-connector-core';
import '../../../context/DynamicContext/useDynamicContext/useDynamicContext.js';
import { useInternalDynamicContext } from '../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import { useInternalUserWallets } from '../../../context/UserWalletsContext/UserWalletsContext.js';
import { useSmartWallets } from '../useSmartWallets/useSmartWallets.js';

/**
 * Switch wallet
 *
 * @returns Function to switch wallet
 *
 * @example
 * ```tsx
 * const App = () => {
 *   const userWallets = useUserWallets();
 *   const switchWallet = useSwitchWallet();
 *
 *   return (
 *     <div>
 *       {userWallets.map((wallet) => (
 *         <button
 *           key={wallet.address}
 *           onClick={() => switchWallet(wallet.id)}
 *         >
 *           {wallet.address}
 *         </button>
 *       ))}
 *    </div>
 *  );
 * }
 */
const useSwitchWallet = () => {
    const { setPrimaryWallet, user, primaryWallet } = useInternalDynamicContext();
    const { getEOAWallet } = useSmartWallets();
    const { userWallets } = useInternalUserWallets();
    return useCallback((walletId) => __awaiter(void 0, void 0, void 0, function* () {
        var _a, _b, _c;
        const wallet = userWallets.find((wallet) => wallet.id === walletId);
        if (!wallet) {
            throw new Error(`Wallet with id ${walletId} not found`);
        }
        if (!wallet.connector.isAvailable) {
            throw new Error("Cannot make this wallet active, since this wallet doesn't have a compatible connector on this device.");
        }
        // On mobile, an in-app-browser wallet that isn't injected on the current
        // browser (e.g. switching to a linked Phantom on mobile web) has no
        // provider to sign with. Trigger the wallet's in-app-browser redirect up
        // front so the user lands inside the wallet app, instead of the switch
        // silently succeeding and every later signature failing. The connector
        // self-gates: this is a no-op for installed, embedded, or redirect-only
        // wallets.
        if (isMobile()) {
            const didOpenInAppBrowser = wallet.connector.openInAppBrowserIfRequired();
            if (didOpenInAppBrowser) {
                return;
            }
        }
        const eoaWallet = getEOAWallet(wallet);
        if (eoaWallet && isTurnkeyWalletConnector(eoaWallet.connector)) {
            const sortedVcs = (_b = (_a = eoaWallet.connector) === null || _a === void 0 ? void 0 : _a.verifiedCredentials) === null || _b === void 0 ? void 0 : _b.reduce((acc, vc) => {
                if (vc.address === eoaWallet.address) {
                    return [vc, ...acc];
                }
                return [...acc, vc];
            }, []);
            if (sortedVcs) {
                eoaWallet.connector.setVerifiedCredentials(sortedVcs);
            }
        }
        const { connector } = wallet;
        const email = (_c = user === null || user === void 0 ? void 0 : user.verifiedCredentials.find((verifiedCredential) => verifiedCredential.format === 'email')) === null || _c === void 0 ? void 0 : _c.email;
        if (isEmailWalletConnector(connector) && email) {
            connector.setEmail(email);
        }
        if ((primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.chain) === 'flow' &&
            connector.connectedChain === 'FLOW') {
            yield connector.endSession();
        }
        // Allow connectors to perform post-selection setup.
        // This is used by connectors like ZeroDev to update their active wallet address.
        yield wallet.connector.afterWalletSelectHook(wallet.address);
        setPrimaryWallet(walletId);
    }), [
        getEOAWallet,
        primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.chain,
        setPrimaryWallet,
        user === null || user === void 0 ? void 0 : user.verifiedCredentials,
        userWallets,
    ]);
};

export { useSwitchWallet };
