'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { useRef, useCallback, useMemo } from 'react';
import { EmbeddedWalletVersionEnum, JwtVerifiedCredentialFormatEnum, WalletProviderEnum } 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 '../../../client/client.js';
import '@dynamic-labs-sdk/client';
import '../../../config/ApiEndpoint.js';
import { VerifiedCredentialNameToChainEnum } from '../../constants/values.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../constants/colors.js';
import '@dynamic-labs/iconic';
import 'react/jsx-runtime';
import '../../../context/ViewContext/ViewContext.js';
import '../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '../../../shared/consts/index.js';
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 { 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 '../../../context/DynamicContext/DynamicContext.js';
import '../../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '../../../context/CaptchaContext/CaptchaContext.js';
import '../../../context/ErrorContext/ErrorContext.js';
import '../../../context/AccessDeniedContext/AccessDeniedContext.js';
import '../../../context/AccountExistsContext/AccountExistsContext.js';
import { useInternalUserWallets } from '../../../context/UserWalletsContext/UserWalletsContext.js';
import '../../../store/state/authMode/authMode.js';
import '../../../context/VerificationContext/VerificationContext.js';
import 'react-dom';
import { findSmartWallet } from '../useWalletConnectors/utils/smartWallet/smartWallet.js';
import '../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import '../../../context/ThemeContext/ThemeContext.js';
import { compareChains } from '../../functions/compareChains/compareChains.js';
import '../useUserUpdateRequest/useUpdateUser/userFieldsSchema.js';
import 'bs58';
import '@dynamic-labs/types';
import '../../../context/SocialRedirectContext/SocialRedirectContext.js';
import '../../../context/LoadingContext/LoadingContext.js';
import '../../../context/WalletContext/WalletContext.js';
import { getNewVerifiedCredentialsFromDiff } from '../../functions/getNewVerifiedCredentialsFromDiff/getNewVerifiedCredentialsFromDiff.js';
import '../useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.js';
import 'yup';
import '../../../context/MockContext/MockContext.js';
import '../../../views/CollectUserDataView/useFields.js';
import '../../../context/FieldsStateContext/FieldsStateContext.js';
import '../../../context/UserFieldEditorContext/UserFieldEditorContext.js';
import '@dynamic-labs/rpc-providers';
import { useWalletConnectorOptions } from '../../../store/state/walletOptions/walletOptions.js';
import 'react-i18next';
import '../../../components/Accordion/components/AccordionItem/AccordionItem.js';
import '../../../components/Alert/Alert.js';
import '../../../components/ShadowDOM/ShadowDOM.js';
import '../../../components/IconButton/IconButton.js';
import '../../../components/InlineWidget/InlineWidget.js';
import '../../../components/Input/Input.js';
import '../../../components/IsBrowser/IsBrowser.js';
import '../../../components/MenuList/Dropdown/Dropdown.js';
import '../../../components/OverlayCard/OverlayCard.js';
import '../../../components/Transition/ZoomTransition/ZoomTransition.js';
import '../../../components/Transition/SlideInUpTransition/SlideInUpTransition.js';
import '../../../components/Transition/OpacityTransition/OpacityTransition.js';
import '../../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.js';
import '../../../components/Popper/Popper/Popper.js';
import '../../../components/Popper/PopperContext/PopperContext.js';
import 'react-focus-lock';
import 'qrcode';
import 'formik';
import '../useSubdomainCheck/useSubdomainCheck.js';
import '../../../context/WalletGroupContext/WalletGroupContext.js';
import '../../../context/IpConfigurationContext/IpConfigurationContext.js';
import '../../../context/ConnectWithOtpContext/ConnectWithOtpContext.js';
import '../../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.js';
import '@hcaptcha/react-hcaptcha';
import '../../../widgets/DynamicWidget/context/DynamicWidgetContext.js';
import '../../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.js';
import '../../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.js';
import '../../../context/ErrorContext/hooks/useErrorText/useErrorText.js';
import '../../../context/FooterAnimationContext/index.js';
import '../../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.js';
import '../../../context/PasskeyContext/PasskeyContext.js';
import '../../../context/OnrampContext/OnrampContext.js';
import { DEFAULT_WAAS_API_URL } from '../../constants/waas/apiUrl.js';
import { useClientSessionKeys } from '../useClientSessionKeys/useClientSessionKeys.js';
import { useGetMfaToken } from '../useGetMfaToken/useGetMfaToken.js';
import { useRefreshUser } from '../useRefreshUser/useRefreshUser.js';
import { DYNAMIC_WAAS_CONNECTOR_NOT_FOUND_ERROR, NO_ENABLED_CHAINS_ERROR, INVALID_CHAINS_ERROR, WALLET_CREATION_FAILED_ERROR } from './constants.js';
import '../../../store/state/sendBalances.js';
import '../../../store/state/connectorsInitializing/connectorsInitializing.js';
import '../../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.js';
import '../../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.js';
import '../../../views/TransactionConfirmationView/TransactionConfirmationView.js';
import '../../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.js';
import '../../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.js';
import '../../../../index.js';
import '../../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.js';
import '../../../store/state/tokenBalances.js';
import '../../../store/state/multichainBalances.js';
import '../../../shared/utils/functions/getInitialUrl/getInitialUrl.js';
import { useInternalDynamicContext } from '../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';

const dynamicWaasKey = 'dynamicwaas';
const configWaasWalletConnector = ({ walletConnector, environmentId, apiBaseUrl, relayUrl, authMode = 'header', getSignedSessionId, getMfaToken, }) => {
    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);
    return walletConnector;
};
const useDynamicWaas = () => {
    var _a, _b, _c;
    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 = useRefreshUser();
    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 embeddedWalletSettings = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.embeddedWallets;
    const enabledChains = (_c = embeddedWalletSettings === null || embeddedWalletSettings === void 0 ? void 0 : embeddedWalletSettings.chainConfigurations) === null || _c === void 0 ? void 0 : _c.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 authToken = getMinAuthToken();
    const { getSignedSessionId } = useClientSessionKeys();
    const getMfaToken = useGetMfaToken();
    const isCookieAuthEnabled = projectSettings && isCookieEnabled();
    const isUpgrading = useRef(false);
    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) &&
            option.walletConnector.connectedChain === 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',
            environmentId,
            getMfaToken,
            getSignedSessionId,
            relayUrl: relayUrl !== null && relayUrl !== void 0 ? relayUrl : '',
            walletConnector,
        });
        return configuredWalletConnector;
    }, [
        isCookieAuthEnabled,
        authToken,
        walletConnectorOptions,
        environmentId,
        apiBaseUrl,
        relayUrl,
        getSignedSessionId,
    ]);
    // 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((chainNames, password) => __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);
        }
        const invalidChains = chainNames.filter((chain) => !enabledChainNames.includes(chain));
        if (invalidChains && invalidChains.length) {
            throw new DynamicError(`${INVALID_CHAINS_ERROR}: ${invalidChains.join(', ')}`);
        }
        const previousVerifiedCredentials = (user === null || user === void 0 ? void 0 : user.verifiedCredentials) || [];
        const results = yield Promise.allSettled(chainNames.map((chain) => __awaiter(void 0, void 0, void 0, function* () {
            const walletConnector = getWaasWalletConnector(chain);
            if (!walletConnector)
                throw new Error('No connector');
            const account = yield walletConnector.createWalletAccount({
                password,
                thresholdSignatureScheme: 'TWO_OF_TWO',
            });
            return Object.assign(Object.assign({}, account), { chainName: chain });
        })));
        const failedChains = [];
        const errors = [];
        results.forEach((result, i) => {
            if (result.status === 'rejected') {
                const chainName = chainNames[i];
                failedChains.push(chainName);
                const errorMessage = result.reason instanceof Error
                    ? result.reason.message
                    : String(result.reason);
                errors.push(`${chainName}: ${errorMessage}`);
            }
        });
        if (failedChains.length > 0) {
            refresh();
            throw new DynamicError(`${WALLET_CREATION_FAILED_ERROR}: ${failedChains.join(', ')}. Errors: ${errors.join('; ')}`);
        }
        const createdWalletAccounts = results.map((r) => r.status === 'fulfilled' ? r.value : undefined);
        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);
            newWalletVerifiedCredentials.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);
                }
            });
            const newWalletIds = newWalletVerifiedCredentials.map(({ id }) => id);
            addedWalletsIds.current = addedWalletsIds.current.concat(newWalletIds);
            if (primaryWalletAccount) {
                const createdPrimaryWallet = refreshedUser.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 = primaryWalletAccount.accountAddress) === null || _c === void 0 ? void 0 : _c.toLowerCase());
                });
                if (createdPrimaryWallet) {
                    // if the user already has a blockchain wallet, don't update the primary wallet
                    if (!previousVerifiedCredentials.find((vc) => vc.format === 'blockchain')) {
                        const smartWalletAccount = findSmartWallet(createdPrimaryWallet, refreshedUser.verifiedCredentials);
                        const walletIdToUse = (smartWalletAccount === null || smartWalletAccount === void 0 ? void 0 : smartWalletAccount.id) || createdPrimaryWallet.id;
                        updatePrimaryWalletId(walletIdToUse);
                    }
                }
            }
        }
        setShowAuthFlow(false, { performMultiWalletChecks: false }); // close email otp pin modal
        return createdWalletAccounts;
    }), [getWaasWalletConnector, primaryChain, enabledChainNames, setShowAuthFlow]);
    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;
        };
        // For each enabled chain, if user does NOT have a V3 wallet and does NOT have a V1/V2 wallet, add to missing
        const missingChains = enabledChainNames === null || enabledChainNames === void 0 ? void 0 : enabledChainNames.filter((chain) => !hasEmbeddedWalletForChain(chain));
        // 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;
        return shouldCreateDynamicWaasWallet ? missingChains : [];
    }, [
        user,
        dynamicWaasIsEnabled,
        automaticEmbeddedWalletCreationEnabled,
        automaticEmbeddedWalletCreationForExternalEnabled,
        enabledChainNames,
    ]);
    const importPrivateKey = (_d) => __awaiter(void 0, [_d], void 0, function* ({ chainName, privateKey, }) {
        const walletConnector = getWaasWalletConnector(chainName);
        if (!walletConnector)
            return;
        yield walletConnector.importPrivateKey({
            chainName,
            privateKey,
        });
        yield refresh();
    });
    const upgradeToDynamicWaas = useCallback((_e) => __awaiter(void 0, [_e], void 0, function* ({ privateKey, wallet, }) {
        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,
                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]);
    const getWaasWallets = useCallback(() => userWallets.filter((w) => w.key === 'dynamicwaas'), [userWallets]);
    const processSignOnWalletSettings = useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
        var _f;
        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 = (_f = wallet.walletProperties) === null || _f === void 0 ? void 0 : _f.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]);
    const needsSettingsProcessing = useMemo(() => {
        if (!(user === null || user === void 0 ? void 0 : user.verifiedCredentials) || !dynamicWaasIsEnabled) {
            return false;
        }
        return user.verifiedCredentials.some((vc) => {
            var _a;
            return vc.walletName === 'dynamicwaas' &&
                ((_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]);
    return {
        createWalletAccount,
        dynamicWaasIsEnabled,
        getWaasWalletConnector,
        getWaasWallets,
        importPrivateKey,
        needsAutoCreateWalletChains,
        needsSettingsProcessing,
        processSignOnWalletSettings,
        upgradeToDynamicWaas,
    };
};

export { configWaasWalletConnector, useDynamicWaas };
