'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { useCallback } from 'react';
import { StorageService } from '@dynamic-labs/utils';
import { JwtVerifiedCredentialFormatEnum } from '@dynamic-labs/sdk-api-core';
import '../../../context/DynamicContext/DynamicContext.js';
import '../../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import 'react/jsx-runtime';
import { useViewContext } from '../../../context/ViewContext/ViewContext.js';
import { logger } from '../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import { DELEGATION_STATE } from '../../constants/localStorage.js';
import '../../constants/colors.js';
import '../../constants/values.js';
import '../../../shared/consts/index.js';
import { dynamicEvents } from '../../../events/dynamicEvents.js';
import '../../../context/CaptchaContext/CaptchaContext.js';
import '../../../context/ErrorContext/ErrorContext.js';
import { USER_NOT_LOGGED_IN } from '../../constants/errors.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../../store/state/nonce/nonce.js';
import '@dynamic-labs-sdk/client/core';
import '../../../client/client.js';
import '@dynamic-labs-sdk/client';
import '../../../config/ApiEndpoint.js';
import { useUser } from '../../../client/extension/user/useUser/useUser.js';
import { useProjectSettings } from '../../../client/extension/projectSettings/useProjectSettings/useProjectSettings.js';
import '@dynamic-labs/locale';
import { useEnvironmentId } from '../../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../../store/state/primaryWalletId/primaryWalletId.js';
import '../../../store/state/connectedWalletsInfo/connectedWalletsInfo.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 '../../functions/compareChains/compareChains.js';
import '../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import '../../../context/ThemeContext/ThemeContext.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 '../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 '../../../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 { useDynamicWaas } from '../useDynamicWaas/useDynamicWaas.js';
import { updateWaasWalletSettings } from '../../../data/api/waas/waas.js';
import { useRefreshUser } from '../useRefreshUser/useRefreshUser.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';

/**
 * 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();
    const { userWallets } = useInternalUserWallets();
    const { pushView } = useViewContext();
    const projectSettings = useProjectSettings();
    const user = useUser();
    const environmentId = useEnvironmentId();
    const refresh = useRefreshUser();
    const { getWaasWalletConnector } = 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 = useCallback(() => {
        if (!delegatedAccessEnabled ||
            !promptUsersOnSignIn ||
            !(user === null || user === void 0 ? void 0 : user.verifiedCredentials)) {
            return false;
        }
        // Check session UI state
        const sessionState = StorageService.getItem(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 === 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 = useCallback((options) => __awaiter(void 0, void 0, void 0, function* () {
        if (!user) {
            throw new Error(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.once('embeddedWalletDelegationCompleted', () => resolve());
            dynamicEvents.once('embeddedWalletDelegationFailed', (error) => reject(error));
        });
    }), [setShowAuthFlow, pushView, user]);
    const getWalletsDelegatedStatus = useCallback(() => {
        if (!(user === null || user === void 0 ? void 0 : user.verifiedCredentials)) {
            return [];
        }
        // Get session UI state
        const sessionState = StorageService.getItem(DELEGATION_STATE);
        // Get waas credentials
        const waasCredentials = user.verifiedCredentials.filter((vc) => vc.walletName === 'dynamicwaas' &&
            vc.format === 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.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 = useCallback((wallets) => __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 = useCallback((wallets) => __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.warn('Wallet is not delegated, skipping revoke');
                continue;
            }
            try {
                yield walletConnector.revokeDelegation({
                    accountAddress: wallet.accountAddress,
                });
            }
            catch (error) {
                logger.error('Failed to revoke delegation:', {
                    error,
                    wallet,
                });
            }
        }
        yield refresh();
    }), [getWaasWalletConnector, refresh]);
    const denyWalletDelegation = useCallback((walletId) => __awaiter(void 0, void 0, void 0, function* () {
        try {
            // Update backend - permanent denial
            yield updateWaasWalletSettings(environmentId, walletId, {
                hasDeniedDelegatedAccess: true,
            });
            // Refresh user to get updated wallet properties
            yield refresh();
            // Clear any session UI state for this wallet
            const sessionState = StorageService.getItem(DELEGATION_STATE) || {};
            if (sessionState.dismissedWallets) {
                sessionState.dismissedWallets = sessionState.dismissedWallets.filter((id) => id !== walletId);
                StorageService.setItem(DELEGATION_STATE, sessionState);
            }
        }
        catch (error) {
            logger.error('Failed to deny wallet delegation', error);
            throw error;
        }
    }), [environmentId, refresh]);
    const dismissDelegationPrompt = useCallback((walletId) => {
        const sessionState = StorageService.getItem(DELEGATION_STATE) || {};
        if (walletId) {
            // Dismiss specific wallet
            sessionState.dismissedWallets = [
                ...(sessionState.dismissedWallets || []),
                walletId,
            ];
        }
        else {
            // Dismiss all (global dismiss)
            sessionState.dismissed = true;
        }
        StorageService.setItem(DELEGATION_STATE, sessionState);
    }, []);
    const clearDelegationSessionState = useCallback(() => {
        StorageService.removeItem(DELEGATION_STATE);
    }, []);
    return {
        clearDelegationSessionState,
        delegateKeyShares,
        delegatedAccessEnabled,
        denyWalletDelegation,
        dismissDelegationPrompt,
        getWalletsDelegatedStatus,
        getWalletsToDelegate,
        initDelegationProcess,
        requiresDelegation,
        revokeDelegation,
        shouldPromptWalletDelegation,
    };
};

export { getWalletsToDelegate, useWalletDelegation };
