'use client'
'use strict';

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

var sdkApiCore = require('@dynamic-labs/sdk-api-core');
var utils = require('@dynamic-labs/utils');
var walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
require('@dynamic-labs/iconic');
require('react');
require('react/jsx-runtime');
require('../../../../../context/ViewContext/ViewContext.cjs');
var logger = require('../../../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('../../../../constants/colors.cjs');
var values = require('../../../../constants/values.cjs');
var hasUserBasicScope = require('../../../../../shared/utils/functions/hasUserBasicScope/hasUserBasicScope.cjs');
require('../../../../../shared/consts/index.cjs');
var findWalletOptionFor = require('../../../../functions/findWalletOptionFor/findWalletOptionFor.cjs');
var shouldManuallyReconnectOnRefresh = require('../../../../functions/shouldManuallyReconnectOnRefresh/shouldManuallyReconnectOnRefresh.cjs');
var convertLegacyPhantomLedgerConnector = require('../convertLegacyPhantomLedgerConnector/convertLegacyPhantomLedgerConnector.cjs');
var smartWallet = require('../smartWallet/smartWallet.cjs');

const createLinkedWalletsFromWalletOptions = ({ user, walletConnectorOptions, primaryWalletId, separateSmartWalletAndSigner, }) => {
    // wallet state should be null while loading all the wallets or when there is no user
    if (!walletConnectorOptions || !user) {
        return [];
    }
    return user.verifiedCredentials
        .map(convertLegacyPhantomLedger)
        .map((account) => {
        var _a, _b;
        const wallet = findWalletOptionFor.findWalletOptionFor(account, walletConnectorOptions);
        // this probably shouldn't happen. this would mean that the user has an account linked
        // with wallet W, but the customer has toggled off wallet W or the chain that
        // supports wallet W
        /* istanbul ignore next */
        if (!wallet)
            return null;
        if (account.id === primaryWalletId &&
            shouldManuallyReconnectOnRefresh.shouldManuallyReconnectOnRefresh(wallet.walletConnector)) {
            wallet.walletConnector.connect();
        }
        // only checking for ledger hardware wallets since we only specify ledger as a hardware wallet
        if (((_a = account.walletProperties) === null || _a === void 0 ? void 0 : _a.hardwareWallet) ===
            sdkApiCore.HardwareWalletEnum.Ledger &&
            walletConnectorCore.isHardwareWalletConnector(wallet.walletConnector)) {
            wallet.walletConnector.isHardwareWalletEnabled = true;
        }
        // this account is the owner of a smart wallet, and should not be surfaced
        if (!separateSmartWalletAndSigner &&
            smartWallet.isOwnerOfASmartWallet(account, user.verifiedCredentials)) {
            return null;
        }
        if (account.address && account.chain) {
            // Only initialize the smart wallet once the JWT has upgraded to
            // user:basic. Smart-wallet init reaches the embedded WaaS connector
            // (validateActiveWallet → getWaasWalletClient), which during the
            // pending-auth window (MFA/KYC/device) would build + initialize the
            // iframe client; its init-time createRooms pre-warm then fires with the
            // construction-time pre-user:basic token, 401s, and forces a logout.
            // This re-runs on credential changes, so it retries naturally once the
            // token clears.
            if (account.walletProvider === sdkApiCore.WalletProviderEnum.SmartContractWallet &&
                hasUserBasicScope.hasUserBasicScope(user)) {
                // Fire-and-forget. The user:basic gate above already prevents the
                // common pre-MFA case, but as defense in depth swallow the WaaS
                // "scope still pending" error specifically (recognizable via its
                // stable code) so a late token regression doesn't spam the console.
                // Anything else is surfaced as before.
                void smartWallet.initializeSmartWallet({
                    account,
                    primaryWalletId,
                    verifiedCredentials: user.verifiedCredentials,
                    walletConnectorOptions,
                }).catch((error) => {
                    if (error instanceof Error &&
                        error.code === utils.WAAS_AUTH_SCOPE_PENDING_CODE) {
                        logger.logger.debug('[createLinkedWalletsFromWalletOptions] Swallowed WaaS scope-pending error during smart-wallet init');
                        return;
                    }
                    logger.logger.error('[createLinkedWalletsFromWalletOptions] Unexpected error during smart-wallet init', error);
                });
            }
            // Prefer the chain from the account's verified credential over the
            // connector's connectedChain. When a wallet falls back to a connector
            // for a different chain (e.g. FallbackSolanaConnector for a SUI
            // wallet), the connector's chain would be wrong.
            const accountChain = account.chain
                ? values.VerifiedCredentialNameToChainEnum[account.chain]
                : undefined;
            return wallet.walletConnector.createWallet({
                additionalAddresses: account.walletAdditionalAddresses,
                address: account.address,
                chain: accountChain !== null && accountChain !== void 0 ? accountChain : wallet.walletConnector.connectedChain,
                connector: wallet.walletConnector,
                id: account.id,
                isAuthenticated: true,
                key: (_b = account.walletName) !== null && _b !== void 0 ? _b : wallet.walletConnector.key,
            });
        }
        return null;
    })
        .filter((wc) => wc !== null);
};
const convertLegacyPhantomLedger = (account) => {
    if (account.walletName === 'phantomledger') {
        return convertLegacyPhantomLedgerConnector.convertLegacyPhantomLedgerConnector(account);
    }
    return account;
};

exports.createLinkedWalletsFromWalletOptions = createLinkedWalletsFromWalletOptions;
