'use client'
'use strict';

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

var _tslib = require('../../../../../_virtual/_tslib.cjs');
var React = require('react');
var utils = require('@dynamic-labs/utils');
var sdkApiCore = require('@dynamic-labs/sdk-api-core');
require('../../../context/DynamicContext/DynamicContext.cjs');
require('../../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
require('react/jsx-runtime');
var ViewContext = require('../../../context/ViewContext/ViewContext.cjs');
var logger = require('../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
var localStorage = require('../../constants/localStorage.cjs');
require('../../constants/colors.cjs');
require('../../constants/values.cjs');
require('../../../shared/consts/index.cjs');
var dynamicEvents = require('../../../events/dynamicEvents.cjs');
require('../../../context/CaptchaContext/CaptchaContext.cjs');
require('../../../context/ErrorContext/ErrorContext.cjs');
var errors = require('../../constants/errors.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../store/state/nonce/nonce.cjs');
require('@dynamic-labs-sdk/client/core');
require('../../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../../config/ApiEndpoint.cjs');
var useUser = require('../../../client/extension/user/useUser/useUser.cjs');
var useProjectSettings = require('../../../client/extension/projectSettings/useProjectSettings/useProjectSettings.cjs');
require('@dynamic-labs/locale');
var dynamicContextProps = require('../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../../context/AccessDeniedContext/AccessDeniedContext.cjs');
require('../../../context/AccountExistsContext/AccountExistsContext.cjs');
var UserWalletsContext = require('../../../context/UserWalletsContext/UserWalletsContext.cjs');
require('../../../store/state/authMode/authMode.cjs');
require('../../../context/VerificationContext/VerificationContext.cjs');
require('react-dom');
require('../../functions/compareChains/compareChains.cjs');
require('../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('../../../context/ThemeContext/ThemeContext.cjs');
require('../useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
require('bs58');
require('@dynamic-labs/types');
require('../../../context/SocialRedirectContext/SocialRedirectContext.cjs');
require('../../../context/LoadingContext/LoadingContext.cjs');
require('../../../context/WalletContext/WalletContext.cjs');
require('../useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.cjs');
require('yup');
require('../../../context/MockContext/MockContext.cjs');
require('../../../views/CollectUserDataView/useFields.cjs');
require('../../../context/FieldsStateContext/FieldsStateContext.cjs');
require('../../../context/UserFieldEditorContext/UserFieldEditorContext.cjs');
require('@dynamic-labs/rpc-providers');
require('../../../store/state/walletOptions/walletOptions.cjs');
require('react-i18next');
require('../../../components/Accordion/components/AccordionItem/AccordionItem.cjs');
require('../../../components/Alert/Alert.cjs');
require('../../../components/ShadowDOM/ShadowDOM.cjs');
require('../../../components/IconButton/IconButton.cjs');
require('../../../components/InlineWidget/InlineWidget.cjs');
require('../../../components/Input/Input.cjs');
require('../../../components/IsBrowser/IsBrowser.cjs');
require('../../../components/MenuList/Dropdown/Dropdown.cjs');
require('../../../components/OverlayCard/OverlayCard.cjs');
require('../../../components/Transition/ZoomTransition/ZoomTransition.cjs');
require('../../../components/Transition/SlideInUpTransition/SlideInUpTransition.cjs');
require('../../../components/Transition/OpacityTransition/OpacityTransition.cjs');
require('../../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.cjs');
require('../../../components/Popper/Popper/Popper.cjs');
require('../../../components/Popper/PopperContext/PopperContext.cjs');
require('react-focus-lock');
require('qrcode');
require('formik');
require('../useSubdomainCheck/useSubdomainCheck.cjs');
require('../../../context/WalletGroupContext/WalletGroupContext.cjs');
require('../../../context/IpConfigurationContext/IpConfigurationContext.cjs');
require('../../../context/ConnectWithOtpContext/ConnectWithOtpContext.cjs');
require('../../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.cjs');
require('@hcaptcha/react-hcaptcha');
require('../../../widgets/DynamicWidget/context/DynamicWidgetContext.cjs');
require('../../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.cjs');
require('../../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.cjs');
require('../../../context/ErrorContext/hooks/useErrorText/useErrorText.cjs');
require('../../../context/FooterAnimationContext/index.cjs');
require('../../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.cjs');
require('../../../context/PasskeyContext/PasskeyContext.cjs');
require('../../../context/OnrampContext/OnrampContext.cjs');
var useDynamicWaas = require('../useDynamicWaas/useDynamicWaas.cjs');
var waas = require('../../../data/api/waas/waas.cjs');
var useRefreshUser = require('../useRefreshUser/useRefreshUser.cjs');
require('../../../store/state/sendBalances.cjs');
require('../../../store/state/connectorsInitializing/connectorsInitializing.cjs');
require('../../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.cjs');
require('../../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.cjs');
require('../../../views/TransactionConfirmationView/TransactionConfirmationView.cjs');
require('../../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.cjs');
require('../../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.cjs');
require('../../../../index.cjs');
require('../../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.cjs');
require('../../../store/state/tokenBalances.cjs');
require('../../../store/state/multichainBalances.cjs');
require('../../../shared/utils/functions/getInitialUrl/getInitialUrl.cjs');
var useInternalDynamicContext = require('../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');

/**
 * Gets pending wallets that are eligible for delegation.
 * If wallets are provided and not empty, converts them to WalletWithStatus[] with pending status.
 * Otherwise, returns all pending wallets from getWalletsDelegatedStatus.
 */
const getWalletsToDelegate = (wallets, getWalletsDelegatedStatus) => {
    if (wallets && wallets.length > 0) {
        // Convert Wallet[] to WalletWithStatus[] with pending status
        return wallets.map((wallet) => (Object.assign(Object.assign({}, wallet), { status: 'pending' })));
    }
    return getWalletsDelegatedStatus().filter((wallet) => wallet.status === 'pending');
};
// Hook to trigger wallet delegation modal
const useWalletDelegation = () => {
    var _a, _b, _c;
    const { setShowAuthFlow } = useInternalDynamicContext.useInternalDynamicContext();
    const { userWallets } = UserWalletsContext.useInternalUserWallets();
    const { pushView } = ViewContext.useViewContext();
    const projectSettings = useProjectSettings.useProjectSettings();
    const user = useUser.useUser();
    const environmentId = dynamicContextProps.useEnvironmentId();
    const refresh = useRefreshUser.useRefreshUser();
    const { getWaasWalletConnector } = useDynamicWaas.useDynamicWaas();
    const waasSettings = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.waas;
    const delegatedAccessEnabled = (_a = waasSettings === null || waasSettings === void 0 ? void 0 : waasSettings.delegatedAccess) === null || _a === void 0 ? void 0 : _a.enabled;
    const promptUsersOnSignIn = (_b = waasSettings === null || waasSettings === void 0 ? void 0 : waasSettings.delegatedAccess) === null || _b === void 0 ? void 0 : _b.promptUsersOnSignIn;
    const requiresDelegation = (_c = waasSettings === null || waasSettings === void 0 ? void 0 : waasSettings.delegatedAccess) === null || _c === void 0 ? void 0 : _c.requiresDelegation;
    const shouldPromptWalletDelegation = React.useCallback(() => {
        if (!delegatedAccessEnabled ||
            !promptUsersOnSignIn ||
            !(user === null || user === void 0 ? void 0 : user.verifiedCredentials)) {
            return false;
        }
        // Check session UI state
        const sessionState = utils.StorageService.getItem(localStorage.DELEGATION_STATE);
        if (sessionState === null || sessionState === void 0 ? void 0 : sessionState.dismissed) {
            return false;
        }
        // Check if any waas wallet needs delegation
        const waasCredentials = user.verifiedCredentials.filter((vc) => vc.walletName === 'dynamicwaas' &&
            vc.format === sdkApiCore.JwtVerifiedCredentialFormatEnum.Blockchain);
        const hasWalletNeedingDelegation = waasCredentials.some((vc) => {
            var _a, _b, _c, _d, _e;
            // Check if already delegated (has delegated keyShare)
            const hasDelegatedKeyShare = (_b = (_a = vc.walletProperties) === null || _a === void 0 ? void 0 : _a.keyShares) === null || _b === void 0 ? void 0 : _b.some((keyShare) => keyShare.backupLocation === 'delegated');
            // Check if denied
            const hasDeniedAccess = ((_d = (_c = vc.walletProperties) === null || _c === void 0 ? void 0 : _c.settings) === null || _d === void 0 ? void 0 : _d.hasDeniedDelegatedAccess) === true;
            // Check if dismissed this session
            const isDismissedThisSession = (_e = sessionState === null || sessionState === void 0 ? void 0 : sessionState.dismissedWallets) === null || _e === void 0 ? void 0 : _e.includes(vc.id);
            // Needs delegation if: not delegated, not denied, and not dismissed this session
            return (!hasDelegatedKeyShare && !hasDeniedAccess && !isDismissedThisSession);
        });
        return hasWalletNeedingDelegation;
    }, [user === null || user === void 0 ? void 0 : user.verifiedCredentials, delegatedAccessEnabled, promptUsersOnSignIn]);
    const initDelegationProcess = React.useCallback((options) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        if (!user) {
            throw new Error(errors.USER_NOT_LOGGED_IN);
        }
        // Show the auth flow modal
        setShowAuthFlow(true, {
            ignoreIfIsEmbeddedWidget: false,
            performMultiWalletChecks: false,
        });
        // Push the wallet delegation view with optional wallets override
        pushView('wallet-delegation-view', {
            wallets: options === null || options === void 0 ? void 0 : options.wallets,
        });
        return new Promise((resolve, reject) => {
            dynamicEvents.dynamicEvents.once('embeddedWalletDelegationCompleted', () => resolve());
            dynamicEvents.dynamicEvents.once('embeddedWalletDelegationFailed', (error) => reject(error));
        });
    }), [setShowAuthFlow, pushView, user]);
    const getWalletsDelegatedStatus = React.useCallback(() => {
        if (!(user === null || user === void 0 ? void 0 : user.verifiedCredentials)) {
            return [];
        }
        // Get session UI state
        const sessionState = utils.StorageService.getItem(localStorage.DELEGATION_STATE);
        // Get waas credentials
        const waasCredentials = user.verifiedCredentials.filter((vc) => vc.walletName === 'dynamicwaas' &&
            vc.format === sdkApiCore.JwtVerifiedCredentialFormatEnum.Blockchain);
        // Map credentials to wallets with status
        return waasCredentials
            .map((vc) => {
            var _a, _b, _c, _d, _e;
            let status = 'pending';
            // Check if wallet has delegated keyShare
            const hasDelegatedKeyShare = (_b = (_a = vc.walletProperties) === null || _a === void 0 ? void 0 : _a.keyShares) === null || _b === void 0 ? void 0 : _b.some((keyShare) => keyShare.backupLocation === 'delegated');
            // Check if user has denied delegation
            const hasDeniedAccess = ((_d = (_c = vc.walletProperties) === null || _c === void 0 ? void 0 : _c.settings) === null || _d === void 0 ? void 0 : _d.hasDeniedDelegatedAccess) === true;
            if (hasDelegatedKeyShare) {
                status = 'delegated';
            }
            else if (hasDeniedAccess) {
                status = 'denied';
            }
            // Check if dismissed this session (UI state only)
            const isDismissedThisSession = (_e = sessionState === null || sessionState === void 0 ? void 0 : sessionState.dismissedWallets) === null || _e === void 0 ? void 0 : _e.includes(vc.id);
            // Find corresponding wallet from userWallets
            const wallet = userWallets.find((w) => w.address === vc.address);
            if (!wallet) {
                logger.logger.warn('Wallet not found for verified credential', {
                    address: vc.address,
                    vcId: vc.id,
                });
                return null;
            }
            return Object.assign(Object.assign({}, wallet), { isDismissedThisSession,
                status });
        })
            .filter((wallet) => wallet !== null);
    }, [user === null || user === void 0 ? void 0 : user.verifiedCredentials, userWallets]);
    const delegateKeyShares = React.useCallback((wallets) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        // If wallets provided, use them directly; otherwise get pending wallets
        const walletsToDelegate = wallets && wallets.length > 0
            ? wallets
            : getWalletsToDelegate(undefined, getWalletsDelegatedStatus).map((wallet) => ({
                accountAddress: wallet.address,
                chainName: wallet.chain,
            }));
        for (const wallet of walletsToDelegate) {
            const walletConnector = getWaasWalletConnector(wallet.chainName);
            if (!walletConnector)
                continue;
            yield walletConnector.delegateKeyShares({
                accountAddress: wallet.accountAddress,
            });
        }
        yield refresh();
    }), [getWaasWalletConnector, refresh, getWalletsDelegatedStatus]);
    const revokeDelegation = React.useCallback((wallets) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        for (const wallet of wallets) {
            const walletConnector = getWaasWalletConnector(wallet.chainName);
            if (!walletConnector)
                continue;
            if (wallet.status !== 'delegated') {
                logger.logger.warn('Wallet is not delegated, skipping revoke');
                continue;
            }
            try {
                yield walletConnector.revokeDelegation({
                    accountAddress: wallet.accountAddress,
                });
            }
            catch (error) {
                logger.logger.error('Failed to revoke delegation:', {
                    error,
                    wallet,
                });
            }
        }
        yield refresh();
    }), [getWaasWalletConnector, refresh]);
    const denyWalletDelegation = React.useCallback((walletId) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        try {
            // Update backend - permanent denial
            yield waas.updateWaasWalletSettings(environmentId, walletId, {
                hasDeniedDelegatedAccess: true,
            });
            // Refresh user to get updated wallet properties
            yield refresh();
            // Clear any session UI state for this wallet
            const sessionState = utils.StorageService.getItem(localStorage.DELEGATION_STATE) || {};
            if (sessionState.dismissedWallets) {
                sessionState.dismissedWallets = sessionState.dismissedWallets.filter((id) => id !== walletId);
                utils.StorageService.setItem(localStorage.DELEGATION_STATE, sessionState);
            }
        }
        catch (error) {
            logger.logger.error('Failed to deny wallet delegation', error);
            throw error;
        }
    }), [environmentId, refresh]);
    const dismissDelegationPrompt = React.useCallback((walletId) => {
        const sessionState = utils.StorageService.getItem(localStorage.DELEGATION_STATE) || {};
        if (walletId) {
            // Dismiss specific wallet
            sessionState.dismissedWallets = [
                ...(sessionState.dismissedWallets || []),
                walletId,
            ];
        }
        else {
            // Dismiss all (global dismiss)
            sessionState.dismissed = true;
        }
        utils.StorageService.setItem(localStorage.DELEGATION_STATE, sessionState);
    }, []);
    const clearDelegationSessionState = React.useCallback(() => {
        utils.StorageService.removeItem(localStorage.DELEGATION_STATE);
    }, []);
    return {
        clearDelegationSessionState,
        delegateKeyShares,
        delegatedAccessEnabled,
        denyWalletDelegation,
        dismissDelegationPrompt,
        getWalletsDelegatedStatus,
        getWalletsToDelegate,
        initDelegationProcess,
        requiresDelegation,
        revokeDelegation,
        shouldPromptWalletDelegation,
    };
};

exports.getWalletsToDelegate = getWalletsToDelegate;
exports.useWalletDelegation = useWalletDelegation;
