'use client'
import { HardwareWalletEnum, WalletProviderEnum } from '@dynamic-labs/sdk-api-core';
import { WAAS_AUTH_SCOPE_PENDING_CODE } from '@dynamic-labs/utils';
import { isHardwareWalletConnector } from '@dynamic-labs/wallet-connector-core';
import '@dynamic-labs/iconic';
import 'react';
import 'react/jsx-runtime';
import '../../../../../context/ViewContext/ViewContext.js';
import { logger } from '../../../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '../../../../constants/colors.js';
import { VerifiedCredentialNameToChainEnum } from '../../../../constants/values.js';
import { hasUserBasicScope } from '../../../../../shared/utils/functions/hasUserBasicScope/hasUserBasicScope.js';
import '../../../../../shared/consts/index.js';
import { findWalletOptionFor } from '../../../../functions/findWalletOptionFor/findWalletOptionFor.js';
import { shouldManuallyReconnectOnRefresh } from '../../../../functions/shouldManuallyReconnectOnRefresh/shouldManuallyReconnectOnRefresh.js';
import { convertLegacyPhantomLedgerConnector } from '../convertLegacyPhantomLedgerConnector/convertLegacyPhantomLedgerConnector.js';
import { isOwnerOfASmartWallet, initializeSmartWallet } from '../smartWallet/smartWallet.js';

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(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(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) ===
            HardwareWalletEnum.Ledger &&
            isHardwareWalletConnector(wallet.walletConnector)) {
            wallet.walletConnector.isHardwareWalletEnabled = true;
        }
        // this account is the owner of a smart wallet, and should not be surfaced
        if (!separateSmartWalletAndSigner &&
            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 === WalletProviderEnum.SmartContractWallet &&
                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 initializeSmartWallet({
                    account,
                    primaryWalletId,
                    verifiedCredentials: user.verifiedCredentials,
                    walletConnectorOptions,
                }).catch((error) => {
                    if (error instanceof Error &&
                        error.code === WAAS_AUTH_SCOPE_PENDING_CODE) {
                        logger.debug('[createLinkedWalletsFromWalletOptions] Swallowed WaaS scope-pending error during smart-wallet init');
                        return;
                    }
                    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
                ? 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(account);
    }
    return account;
};

export { createLinkedWalletsFromWalletOptions };
