'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { useRef, useState, useCallback, useMemo } from 'react';
import { EmbeddedWalletVersionEnum, JwtVerifiedCredentialFormatEnum, WalletProviderEnum, ChainEnum } from '@dynamic-labs/sdk-api-core';
import { DynamicError } from '@dynamic-labs/utils';
import { logger } from '@dynamic-labs/wallet-connector-core';
import { dynamicEvents } from '../../../events/dynamicEvents.js';
import '@dynamic-labs-sdk/client/core';
import 'eventemitter3';
import '@dynamic-labs-sdk/client';
import '../../../config/ApiEndpoint.js';
import '@dynamic-labs/iconic';
import 'react/jsx-runtime';
import '../../../context/ViewContext/ViewContext.js';
import '../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '../../constants/colors.js';
import { VerifiedCredentialNameToChainEnum } from '../../constants/values.js';
import '../../../shared/consts/index.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../../store/state/nonce/nonce.js';
import { updatePrimaryWalletId } from '../../functions/updatePrimaryWalletId/updatePrimaryWalletId.js';
import '../../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import { useApiBaseUrl, useEnvironmentId } from '../../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../../store/state/primaryWalletId/primaryWalletId.js';
import '@dynamic-labs/locale';
import { softDeleteEmbeddedWallet, restoreEmbeddedWallet } from '../../../data/api/wallets/wallets.js';
import '../../functions/getWaasAddressTypeLabel/getWaasAddressTypeLabel.js';
import { convertSdkUserToUserProfile } from '../../../client/extension/user/convertSdkUserToUserProfile/convertSdkUserToUserProfile.js';
import { useUser } from '../../../client/extension/user/useUser/useUser.js';
import { useProjectSettings } from '../../../client/extension/projectSettings/useProjectSettings/useProjectSettings.js';
import { isCookieEnabled } from '../../../client/extension/functions/isCookieEnabled/isCookieEnabled.js';
import { getMinAuthToken } from '../../../client/extension/functions/getMinAuthToken/getMinAuthToken.js';
import { generateChainingSignature } from '../../../client/extension/functions/generateChainingSignature/generateChainingSignature.js';
import '../../../context/DynamicContext/useDynamicContext/useDynamicContext.js';
import { useInternalDynamicContext } from '../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import { useInternalUserWallets } from '../../../context/UserWalletsContext/UserWalletsContext.js';
import { useWalletConnectorOptions } from '../../../store/state/walletOptions/walletOptions.js';
import { DEFAULT_WAAS_API_URL } from '../../constants/waas/apiUrl.js';
import { compareChains } from '../../functions/compareChains/compareChains.js';
import { getNewVerifiedCredentialsFromDiff } from '../../functions/getNewVerifiedCredentialsFromDiff/getNewVerifiedCredentialsFromDiff.js';
import { useGetMfaToken } from '../useGetMfaToken/useGetMfaToken.js';
import { useGetWalletPassword } from '../useGetWalletPassword/useGetWalletPassword.js';
import { useRefreshAuth } from '../useRefreshAuth/useRefreshAuth.js';
import { findSmartWallet } from '../useWalletConnectors/utils/smartWallet/smartWallet.js';
import { useGetElevatedAccessToken } from '../useGetElevatedAccessToken/useGetElevatedAccessToken.js';
import { DYNAMIC_WAAS_CONNECTOR_NOT_FOUND_ERROR, NO_ENABLED_CHAINS_ERROR, INVALID_CHAINS_ERROR, WALLET_CREATION_FAILED_ERROR } from './constants.js';
import { normalizeWaasChainName } from './normalizeWaasChainName.js';
import { normalizeWalletRequirements } from './normalizeWalletRequirements.js';

const dynamicWaasKey = 'dynamicwaas';
const configWaasWalletConnector = ({ walletConnector, environmentId, apiBaseUrl, relayUrl, baseClientKeysharesRelayApiUrl, authMode = 'header', getSignedSessionId, getMfaToken, getWalletPassword, getSvmGasSponsorshipEnabled = () => false, getElevatedAccessToken, }) => {
    var _a;
    walletConnector.setEnvironmentId(environmentId);
    walletConnector.setBaseApiUrl((_a = (apiBaseUrl || DEFAULT_WAAS_API_URL)) === null || _a === void 0 ? void 0 : _a.replace('/api/v0', ''));
    if (authMode === 'cookie') {
        walletConnector.setWaasAuthMode('cookie');
        walletConnector.setGetAuthTokenFunction(() => '');
    }
    else {
        walletConnector.setWaasAuthMode('header');
        walletConnector.setGetAuthTokenFunction(getMinAuthToken);
    }
    walletConnector.setGetSignedSessionIdFunction(getSignedSessionId);
    walletConnector.setRelayUrl(relayUrl);
    walletConnector.setGetMfaTokenFunction(getMfaToken);
    walletConnector.setBaseClientKeysharesRelayApiUrl(baseClientKeysharesRelayApiUrl);
    // Set elevated access token provider
    if (getElevatedAccessToken) {
        walletConnector.setGetElevatedAccessTokenFunction(getElevatedAccessToken);
    }
    // Set password provider for locked wallets
    if (getWalletPassword) {
        walletConnector.setGetWalletPasswordFunction(getWalletPassword);
    }
    // Sync SVM gas sponsorship setting for SOL connectors
    const isSolConnector = walletConnector.connectedChain === 'SOL';
    const supportsSponsorshipSetting = 'setSvmGasSponsorshipEnabled' in walletConnector;
    if (isSolConnector && supportsSponsorshipSetting) {
        walletConnector.setSvmGasSponsorshipEnabled(getSvmGasSponsorshipEnabled);
    }
    return walletConnector;
};
const useDynamicWaas = () => {
    var _a, _b, _c, _d, _e, _f, _g;
    const { setShowAuthFlow, primaryWallet } = useInternalDynamicContext();
    const { addedWalletsIds, userWallets } = useInternalUserWallets();
    const user = useUser();
    const apiBaseUrl = useApiBaseUrl();
    const projectSettings = useProjectSettings();
    const environmentId = useEnvironmentId();
    const walletConnectorOptions = useWalletConnectorOptions();
    const refresh = useRefreshAuth();
    const relayUrl = (_b = (_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _a === void 0 ? void 0 : _a.waas) === null || _b === void 0 ? void 0 : _b.relayUrl;
    const baseClientKeysharesRelayApiUrl = (_d = (_c = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _c === void 0 ? void 0 : _c.waas) === null || _d === void 0 ? void 0 : _d.customKeyshareRelayBaseUrl;
    const embeddedWalletSettings = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.embeddedWallets;
    const enabledChains = (_e = embeddedWalletSettings === null || embeddedWalletSettings === void 0 ? void 0 : embeddedWalletSettings.chainConfigurations) === null || _e === void 0 ? void 0 : _e.filter((c) => c.enabled);
    const primaryChain = enabledChains === null || enabledChains === void 0 ? void 0 : enabledChains.find((chain) => chain.primary);
    const enabledChainNames = enabledChains === null || enabledChains === void 0 ? void 0 : enabledChains.map((chain) => chain.name);
    const automaticEmbeddedWalletCreationEnabled = embeddedWalletSettings === null || embeddedWalletSettings === void 0 ? void 0 : embeddedWalletSettings.automaticEmbeddedWalletCreation;
    const automaticEmbeddedWalletCreationForExternalEnabled = embeddedWalletSettings === null || embeddedWalletSettings === void 0 ? void 0 : embeddedWalletSettings.automaticEmbeddedWalletCreationForExternal;
    const defaultWalletVersion = embeddedWalletSettings === null || embeddedWalletSettings === void 0 ? void 0 : embeddedWalletSettings.defaultWalletVersion;
    const dynamicWaasIsEnabled = defaultWalletVersion === EmbeddedWalletVersionEnum.V3;
    const svmGasSponsorshipEnabled = (_f = embeddedWalletSettings === null || embeddedWalletSettings === void 0 ? void 0 : embeddedWalletSettings.svmGasSponsorshipEnabled) !== null && _f !== void 0 ? _f : false;
    const svmGasSponsorshipEnabledRef = useRef(svmGasSponsorshipEnabled);
    svmGasSponsorshipEnabledRef.current = svmGasSponsorshipEnabled;
    const authToken = getMinAuthToken();
    const getMfaToken = useGetMfaToken();
    const getWalletPassword = useGetWalletPassword();
    const getElevatedAccessToken = useGetElevatedAccessToken();
    const isCookieAuthEnabled = projectSettings && isCookieEnabled();
    const isUpgrading = useRef(false);
    const [recoveredWallets, setRecoveredWallets] = useState(() => new Set());
    const getWaasWalletConnector = useCallback((chainName) => {
        var _a;
        if (!isCookieAuthEnabled && !authToken) {
            return undefined;
        }
        if (!walletConnectorOptions.length || !environmentId)
            return undefined;
        const walletConnector = (_a = walletConnectorOptions.find((option) => option.key.includes(dynamicWaasKey) &&
            normalizeWaasChainName(option.walletConnector.connectedChain) ===
                normalizeWaasChainName(chainName))) === null || _a === void 0 ? void 0 : _a.walletConnector;
        if (!walletConnector) {
            throw new DynamicError(DYNAMIC_WAAS_CONNECTOR_NOT_FOUND_ERROR);
        }
        const configuredWalletConnector = configWaasWalletConnector({
            apiBaseUrl: apiBaseUrl || DEFAULT_WAAS_API_URL,
            authMode: isCookieAuthEnabled ? 'cookie' : 'header',
            baseClientKeysharesRelayApiUrl,
            environmentId,
            getElevatedAccessToken,
            getMfaToken,
            getSignedSessionId: generateChainingSignature,
            getSvmGasSponsorshipEnabled: () => svmGasSponsorshipEnabledRef.current,
            getWalletPassword,
            relayUrl: relayUrl !== null && relayUrl !== void 0 ? relayUrl : '',
            walletConnector,
        });
        return configuredWalletConnector;
    }, [
        isCookieAuthEnabled,
        authToken,
        walletConnectorOptions,
        environmentId,
        apiBaseUrl,
        getElevatedAccessToken,
        getMfaToken,
        getWalletPassword,
        relayUrl,
        baseClientKeysharesRelayApiUrl,
    ]);
    const shouldInitializeWaas = useMemo(() => {
        var _a;
        const isUserAuthenticated = Boolean((user === null || user === void 0 ? void 0 : user.id) && (user === null || user === void 0 ? void 0 : user.sessionId));
        const userHasVerifiedCredentials = Boolean((_a = user === null || user === void 0 ? void 0 : user.verifiedCredentials) === null || _a === void 0 ? void 0 : _a.length);
        const isChainsEnabled = Boolean(enabledChainNames === null || enabledChainNames === void 0 ? void 0 : enabledChainNames.length);
        const isWalletConnectorOptionsEnabled = Boolean(walletConnectorOptions.length);
        return (isUserAuthenticated &&
            userHasVerifiedCredentials &&
            dynamicWaasIsEnabled &&
            isChainsEnabled &&
            isWalletConnectorOptionsEnabled);
    }, [
        user === null || user === void 0 ? void 0 : user.id,
        user === null || user === void 0 ? void 0 : user.sessionId,
        (_g = user === null || user === void 0 ? void 0 : user.verifiedCredentials) === null || _g === void 0 ? void 0 : _g.length,
        dynamicWaasIsEnabled,
        enabledChainNames === null || enabledChainNames === void 0 ? void 0 : enabledChainNames.length,
        walletConnectorOptions.length,
    ]);
    const initializeWaas = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
        if (!shouldInitializeWaas || !user)
            return;
        try {
            const initializationStart = new Date().getTime();
            const userWaasWallets = user.verifiedCredentials.filter((vc) => vc.walletName === dynamicWaasKey && vc.address && vc.chain);
            const chainsWithWallets = [
                ...new Set(userWaasWallets.map((vc) => { var _a; return VerifiedCredentialNameToChainEnum[(_a = vc.chain) !== null && _a !== void 0 ? _a : '']; })),
            ].filter(Boolean);
            // Combine enabled chains with chains that have wallets
            // This ensures we initialize clients for enabled chains AND recover wallets from any other chains
            const allChainsToProcess = [
                ...new Set([...(enabledChainNames || []), ...chainsWithWallets]),
            ];
            yield Promise.all(allChainsToProcess.map((chain) => __awaiter(void 0, void 0, void 0, function* () {
                const walletConnector = getWaasWalletConnector(chain);
                if (!walletConnector)
                    return;
                // Filter for waas wallets on this chain
                const waasWallets = user.verifiedCredentials.filter((credential) => {
                    var _a;
                    return credential.walletName === dynamicWaasKey &&
                        credential.address &&
                        VerifiedCredentialNameToChainEnum[(_a = credential.chain) !== null && _a !== void 0 ? _a : ''] ===
                            walletConnector.connectedChain;
                });
                try {
                    // Initialize waas iframe
                    const client = yield walletConnector.getWaasWalletClient();
                    logger.debug('[useDynamicWaas] initialized waas iframe');
                    const iframeInitializationEnd = new Date().getTime();
                    const iframeLoadingTime = iframeInitializationEnd - initializationStart;
                    logger.instrument('Waas iframe initialized', {
                        chain,
                        end: iframeInitializationEnd,
                        environmentId: user.projectEnvironmentId,
                        key: 'waasIframeInitialized',
                        start: initializationStart,
                        time: iframeLoadingTime,
                        userId: user === null || user === void 0 ? void 0 : user.id,
                    });
                    // If user has waas wallets, restore keyshares to the iframe
                    if (waasWallets.length > 0) {
                        yield Promise.all(waasWallets
                            .filter((wallet) => wallet.address)
                            .map((wallet) => __awaiter(void 0, void 0, void 0, function* () {
                            try {
                                logger.debug('[useDynamicWaas] restoring wallet keyshare', {
                                    chain: wallet.chain,
                                    sessionId: user.sessionId,
                                    userId: user.id,
                                    walletAddress: wallet.address,
                                });
                                const keyshareRestorationStart = new Date().getTime();
                                const signedSessionId = yield generateChainingSignature();
                                yield client.getWallet({
                                    accountAddress: wallet.address,
                                    authToken: getMinAuthToken(),
                                    signedSessionId,
                                    walletOperation: 'RECOVER',
                                });
                                const keyshareRestorationEnd = new Date().getTime();
                                const keyshareRestorationTime = keyshareRestorationEnd - keyshareRestorationStart;
                                const totalElapsedTime = keyshareRestorationEnd - initializationStart;
                                logger.instrument('Waas wallet keyshare restored', {
                                    accountAddress: wallet.address,
                                    chain,
                                    end: keyshareRestorationEnd,
                                    environmentId: user.projectEnvironmentId,
                                    key: 'waasWalletKeyshareRestored',
                                    keyshareRestorationTime: keyshareRestorationTime,
                                    start: initializationStart,
                                    time: totalElapsedTime,
                                    userId: user === null || user === void 0 ? void 0 : user.id,
                                });
                                // Track successfully recovered wallet
                                setRecoveredWallets((prev) => {
                                    var _a;
                                    const next = new Set(prev);
                                    next.add((_a = wallet.address) === null || _a === void 0 ? void 0 : _a.toLowerCase());
                                    return next;
                                });
                            }
                            catch (error) {
                                logger.warn('[useDynamicWaas] Error restoring wallet keyshare', {
                                    chain,
                                    error,
                                    sessionId: user.sessionId,
                                    userId: user.id,
                                    walletAddress: wallet.address,
                                });
                            }
                        })));
                    }
                }
                catch (error) {
                    logger.error('Error initializing waas wallet client', {
                        chain,
                        error,
                        sessionId: user.sessionId,
                        userId: user.id,
                    });
                }
            })));
        }
        catch (error) {
            logger.error('Error initializing waas', {
                error,
                sessionId: user.sessionId,
                userId: user.id,
            });
        }
    }), [enabledChainNames, getWaasWalletConnector, shouldInitializeWaas, user]);
    // If no chain names are provided, filter out chains that already have a wallet
    // and make a wallet for each enabled chain
    const createWalletAccount = useCallback((requirementsOrChainNames, password, bitcoinConfig, options) => __awaiter(void 0, void 0, void 0, function* () {
        if (isUpgrading.current) {
            return;
        }
        if (!(enabledChainNames === null || enabledChainNames === void 0 ? void 0 : enabledChainNames.length)) {
            throw new DynamicError(NO_ENABLED_CHAINS_ERROR);
        }
        // Convert legacy ChainEnum[] format to WalletCreationRequirement[]
        const requirements = normalizeWalletRequirements(requirementsOrChainNames, bitcoinConfig);
        // Validate all chains are enabled
        const validateChains = (reqs) => {
            const allChains = reqs.map((req) => req.chain);
            const invalidChains = allChains.filter((chain) => !enabledChainNames.includes(chain));
            if (invalidChains.length > 0) {
                throw new DynamicError(`${INVALID_CHAINS_ERROR}: ${invalidChains.join(', ')}`);
            }
        };
        validateChains(requirements);
        const previousVerifiedCredentials = (user === null || user === void 0 ? void 0 : user.verifiedCredentials) || [];
        const results = yield Promise.allSettled(requirements.map((requirement) => __awaiter(void 0, void 0, void 0, function* () {
            const walletConnector = getWaasWalletConnector(requirement.chain);
            if (!walletConnector)
                throw new Error('No connector');
            const requirementBitcoinConfig = requirement.chain === ChainEnum.Btc
                ? requirement.bitcoinConfig
                : undefined;
            const createWalletAccountParams = Object.assign({ password, thresholdSignatureScheme: 'TWO_OF_TWO' }, (requirementBitcoinConfig && {
                bitcoinConfig: requirementBitcoinConfig,
            }));
            const account = yield walletConnector.createWalletAccount(createWalletAccountParams);
            return Object.assign(Object.assign({}, account), { chainName: requirement.chain });
        })));
        const processCreationResults = (settledResults, reqs) => {
            const failedChains = [];
            const errors = [];
            settledResults.forEach((result, i) => {
                if (result.status === 'rejected') {
                    const requirement = reqs[i];
                    failedChains.push(requirement.chain);
                    const errorMessage = result.reason instanceof Error
                        ? result.reason.message
                        : String(result.reason);
                    errors.push(`${requirement.chain}: ${errorMessage}`);
                }
            });
            if (failedChains.length > 0) {
                refresh();
                throw new DynamicError(`${WALLET_CREATION_FAILED_ERROR}: ${failedChains.join(', ')}. Errors: ${errors.join('; ')}`);
            }
            return settledResults.map((r) => r.status === 'fulfilled' ? r.value : undefined);
        };
        const createdWalletAccounts = processCreationResults(results, requirements);
        const primaryWalletAccount = createdWalletAccounts === null || createdWalletAccounts === void 0 ? void 0 : createdWalletAccounts.find((wallet) => (wallet === null || wallet === void 0 ? void 0 : wallet.chainName) === (primaryChain === null || primaryChain === void 0 ? void 0 : primaryChain.name));
        const refreshedUser = yield refresh();
        if (refreshedUser) {
            // Add new wallet IDs to trigger walletAdded events
            const newWalletVerifiedCredentials = getNewVerifiedCredentialsFromDiff(previousVerifiedCredentials, refreshedUser.verifiedCredentials).filter(({ format }) => format === JwtVerifiedCredentialFormatEnum.Blockchain);
            const emitWalletCreatedEvents = (walletCredentials) => {
                walletCredentials.forEach((walletVerifiedCredential) => {
                    var _a, _b, _c;
                    try {
                        const chain = VerifiedCredentialNameToChainEnum[(_a = walletVerifiedCredential === null || walletVerifiedCredential === void 0 ? void 0 : walletVerifiedCredential.chain) !== null && _a !== void 0 ? _a : ''];
                        const walletConnector = getWaasWalletConnector(chain);
                        if (!walletConnector)
                            return;
                        const wallet = walletConnector.createWallet({
                            address: (_b = walletVerifiedCredential.address) !== null && _b !== void 0 ? _b : '',
                            chain,
                            connector: walletConnector,
                            id: walletVerifiedCredential.id,
                            isAuthenticated: true,
                            key: (_c = walletVerifiedCredential.walletName) !== null && _c !== void 0 ? _c : '',
                        });
                        dynamicEvents.emit('embeddedWalletCreated', wallet, walletVerifiedCredential, user ? convertSdkUserToUserProfile(user) : undefined);
                    }
                    catch (error) {
                        logger.error(error);
                    }
                });
            };
            emitWalletCreatedEvents(newWalletVerifiedCredentials);
            const newWalletIds = newWalletVerifiedCredentials.map(({ id }) => id);
            addedWalletsIds.current = addedWalletsIds.current.concat(newWalletIds);
            const updatePrimaryWalletIfNeeded = (primaryAccount, refreshed) => {
                if (!primaryAccount)
                    return;
                const createdPrimaryWallet = refreshed.verifiedCredentials.find((wallet) => {
                    var _a, _b, _c;
                    return ((_a = wallet.walletName) === null || _a === void 0 ? void 0 : _a.includes(dynamicWaasKey)) &&
                        ((_b = wallet.address) === null || _b === void 0 ? void 0 : _b.toLowerCase()) ===
                            ((_c = primaryAccount.accountAddress) === null || _c === void 0 ? void 0 : _c.toLowerCase());
                });
                if (!createdPrimaryWallet)
                    return;
                const hasExistingBlockchainWallet = previousVerifiedCredentials.find((vc) => vc.format === 'blockchain');
                if (hasExistingBlockchainWallet)
                    return;
                const smartWalletAccount = findSmartWallet(createdPrimaryWallet, refreshed.verifiedCredentials);
                const walletIdToUse = (smartWalletAccount === null || smartWalletAccount === void 0 ? void 0 : smartWalletAccount.id) || createdPrimaryWallet.id;
                updatePrimaryWalletId(walletIdToUse);
            };
            updatePrimaryWalletIfNeeded(primaryWalletAccount, refreshedUser);
        }
        // close email otp pin modal; skipped in password setup flow (done screen handles close)
        if (!(options === null || options === void 0 ? void 0 : options.skipCloseAuthFlow)) {
            setShowAuthFlow(false, { performMultiWalletChecks: false });
        }
        return createdWalletAccounts;
    }), [
        getWaasWalletConnector,
        primaryChain,
        enabledChainNames,
        setShowAuthFlow,
        user,
        refresh,
        addedWalletsIds,
    ]);
    const needsAutoCreateWalletChains = useMemo(() => {
        var _a;
        if (!user ||
            !dynamicWaasIsEnabled ||
            !automaticEmbeddedWalletCreationEnabled) {
            return [];
        }
        // check if user have any wallet (V1, V2, or V3/dynamicwaas) for this chain
        const hasEmbeddedWalletForChain = (chain) => {
            var _a, _b;
            return (_b = (_a = user === null || user === void 0 ? void 0 : user.verifiedCredentials) === null || _a === void 0 ? void 0 : _a.some((wallet) => wallet.chain &&
                compareChains(wallet.chain, chain) &&
                wallet.walletProvider === WalletProviderEnum.EmbeddedWallet)) !== null && _b !== void 0 ? _b : false;
        };
        // If user has an external wallet, only create if automaticEmbeddedWalletCreationForExternalEnabled is true
        const hasExternalWallet = (_a = user === null || user === void 0 ? void 0 : user.verifiedCredentials) === null || _a === void 0 ? void 0 : _a.some((vc) => vc.format === JwtVerifiedCredentialFormatEnum.Blockchain &&
            vc.walletProvider !== WalletProviderEnum.EmbeddedWallet);
        const shouldCreateDynamicWaasWallet = hasExternalWallet
            ? automaticEmbeddedWalletCreationForExternalEnabled
            : true;
        if (!shouldCreateDynamicWaasWallet) {
            return [];
        }
        const requirements = [];
        // Handle BTC separately - only create native_segwit wallet if BTC is enabled and user doesn't have a BTC wallet
        if (enabledChainNames === null || enabledChainNames === void 0 ? void 0 : enabledChainNames.includes(ChainEnum.Btc)) {
            if (!hasEmbeddedWalletForChain(ChainEnum.Btc)) {
                requirements.push({
                    bitcoinConfig: { addressType: 'native_segwit' },
                    chain: ChainEnum.Btc,
                });
            }
        }
        // For other chains, check if user does NOT have a V3 wallet and does NOT have a V1/V2 wallet
        const otherMissingChains = enabledChainNames === null || enabledChainNames === void 0 ? void 0 : enabledChainNames.filter((chain) => chain !== ChainEnum.Btc && !hasEmbeddedWalletForChain(chain));
        // Add other missing chains without address type requirements
        otherMissingChains === null || otherMissingChains === void 0 ? void 0 : otherMissingChains.forEach((chain) => {
            requirements.push({ chain: chain });
        });
        return requirements;
    }, [
        user,
        dynamicWaasIsEnabled,
        automaticEmbeddedWalletCreationEnabled,
        automaticEmbeddedWalletCreationForExternalEnabled,
        enabledChainNames,
    ]);
    const importPrivateKey = (_h) => __awaiter(void 0, [_h], void 0, function* ({ chainName, privateKey, addressType, legacyWalletId, password, }) {
        const walletConnector = getWaasWalletConnector(chainName);
        if (!walletConnector)
            return;
        yield walletConnector.importPrivateKey({
            addressType,
            chainName,
            legacyWalletId,
            password,
            privateKey,
        });
        yield refresh();
    });
    const upgradeToDynamicWaas = useCallback((_j) => __awaiter(void 0, [_j], void 0, function* ({ privateKey, wallet, password, }) {
        isUpgrading.current = true;
        if (!primaryWallet) {
            throw new DynamicError('Primary wallet not found');
        }
        const chainName = wallet.chain;
        const walletId = wallet.id;
        const walletConnector = getWaasWalletConnector(chainName);
        if (!walletConnector) {
            throw new DynamicError('Wallet connector not found');
        }
        let softDeleteSucceeded = false;
        // 7702 wallets have a -zerodev suffix because it's a credential created on the fly
        const normalizedWalletId = (walletId === null || walletId === void 0 ? void 0 : walletId.replace('-zerodev', '')) || walletId;
        try {
            yield softDeleteEmbeddedWallet({
                environmentId,
                walletId: normalizedWalletId,
            });
            softDeleteSucceeded = true;
            yield walletConnector.importPrivateKey({
                chainName,
                legacyWalletId: normalizedWalletId,
                password,
                privateKey,
                publicAddressCheck: wallet.address,
            });
            isUpgrading.current = false;
        }
        catch (error) {
            // If soft delete succeeded but import failed, try to restore the wallet
            if (softDeleteSucceeded) {
                yield restoreEmbeddedWallet({
                    environmentId,
                    walletId: normalizedWalletId,
                });
                yield refresh();
            }
            isUpgrading.current = false;
            if (error instanceof DynamicError) {
                throw error;
            }
            const errorMessage = (error === null || error === void 0 ? void 0 : error.message) || '';
            if (errorMessage.includes('Public address mismatch')) {
                throw new DynamicError('Public address mismatch. Ensure the private key is copied correctly.');
            }
            throw new DynamicError('Upgrade failed, please try again.');
        }
    }), [environmentId, getWaasWalletConnector, primaryWallet, refresh]);
    /**
     * Returns WaaS wallet instances from `userWallets` filtered by `key === 'dynamicwaas'`.
     *
     * Note: This returns runtime wallet instances which may not include all WaaS wallets.
     * For example, an EVM WaaS wallet used as a signer for a smart wallet (e.g., ZeroDev)
     * may appear in `userWallets` with a different key (e.g., 'zerodev') rather than 'dynamicwaas'.
     *
     * Use `getWaasWalletsByCredentials` if you need to identify all WaaS wallets regardless
     * of how they're represented at runtime.
     */
    const getWaasWallets = useCallback(() => userWallets.filter((w) => w.key === 'dynamicwaas'), [userWallets]);
    /**
     * Returns all WaaS wallet credentials based on `verifiedCredentials` (the backend source of truth).
     *
     * Unlike `getWaasWallets`, this method identifies WaaS wallets by their credential's
     * `walletName === 'dynamicwaas'`, which is reliable regardless of how the wallet is
     * instantiated at runtime. This is useful for operations like backup and key share export
     * where you need to identify all WaaS wallets, including those used as signers for
     * smart wallets (e.g., ZeroDev, EIP-7702).
     *
     * @returns Array of WaaS wallet credentials with valid address and chain.
     */
    const getWaasWalletsByCredentials = useCallback(() => {
        if (!(user === null || user === void 0 ? void 0 : user.verifiedCredentials))
            return [];
        return user.verifiedCredentials.filter((cred) => cred.walletName === 'dynamicwaas' &&
            cred.address &&
            cred.chain &&
            VerifiedCredentialNameToChainEnum[cred.chain]);
    }, [user === null || user === void 0 ? void 0 : user.verifiedCredentials]);
    const processSignOnWalletSettings = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
        var _k;
        if (!(user === null || user === void 0 ? void 0 : user.verifiedCredentials)) {
            return;
        }
        const waasWallets = user.verifiedCredentials.filter((vc) => { var _a; return vc.walletName === 'dynamicwaas' && ((_a = vc.walletProperties) === null || _a === void 0 ? void 0 : _a.settings); });
        for (const wallet of waasWallets) {
            try {
                const settings = (_k = wallet.walletProperties) === null || _k === void 0 ? void 0 : _k.settings;
                const { address, chain } = wallet;
                if (!settings || !address || !chain) {
                    continue;
                }
                const { shouldRefreshOnNextSignOn, reshareOnNextSignOn, revokeOnNextSignOn, } = settings;
                const chainName = VerifiedCredentialNameToChainEnum[chain];
                const walletConnector = getWaasWalletConnector(chainName);
                if (!walletConnector) {
                    continue;
                }
                if (revokeOnNextSignOn) {
                    yield walletConnector.revokeDelegation({
                        accountAddress: address,
                    });
                }
                if (shouldRefreshOnNextSignOn) {
                    yield walletConnector.refreshWalletAccountShares({
                        accountAddress: address,
                    });
                }
                if (reshareOnNextSignOn) {
                    yield walletConnector.reshareWalletAccountShares({
                        accountAddress: address,
                        thresholdSignatureScheme: reshareOnNextSignOn,
                    });
                }
            }
            catch (error) {
                logger.error('Failed to process wallet settings:', {
                    error,
                    wallet,
                });
            }
        }
        yield refresh();
    }), [user, getWaasWalletConnector, refresh]);
    // Get wallets that need settings processing
    const walletsNeedingSettings = useMemo(() => {
        if (!(user === null || user === void 0 ? void 0 : user.verifiedCredentials) || !dynamicWaasIsEnabled) {
            return [];
        }
        return user.verifiedCredentials.filter((vc) => {
            var _a;
            return vc.walletName === 'dynamicwaas' &&
                vc.address &&
                ((_a = vc.walletProperties) === null || _a === void 0 ? void 0 : _a.settings) &&
                (vc.walletProperties.settings.shouldRefreshOnNextSignOn ||
                    vc.walletProperties.settings.reshareOnNextSignOn ||
                    vc.walletProperties.settings.revokeOnNextSignOn);
        });
    }, [user, dynamicWaasIsEnabled]);
    // Derived from walletsNeedingSettings for backward compatibility
    const needsSettingsProcessing = walletsNeedingSettings.length > 0;
    // Check if all wallets needing settings have been recovered
    const areWalletsReadyForSettings = useCallback(() => {
        if (walletsNeedingSettings.length === 0) {
            return false;
        }
        return walletsNeedingSettings.every((wallet) => { var _a; return recoveredWallets.has((_a = wallet.address) === null || _a === void 0 ? void 0 : _a.toLowerCase()); });
    }, [walletsNeedingSettings, recoveredWallets]);
    // Clear recovered wallets tracking (call on logout)
    const clearRecoveredWallets = useCallback(() => {
        setRecoveredWallets(new Set());
    }, []);
    return {
        areWalletsReadyForSettings,
        clearRecoveredWallets,
        createWalletAccount,
        dynamicWaasIsEnabled,
        getWaasWalletConnector,
        getWaasWallets,
        getWaasWalletsByCredentials,
        importPrivateKey,
        initializeWaas,
        needsAutoCreateWalletChains,
        needsSettingsProcessing,
        processSignOnWalletSettings,
        shouldInitializeWaas,
        upgradeToDynamicWaas,
    };
};

export { configWaasWalletConnector, useDynamicWaas };
