'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { useCallback } from 'react';
import '@dynamic-labs/utils';
import '@dynamic-labs/sdk-api-core';
import '@dynamic-labs-sdk/client/core';
import '../../../client/client.js';
import '@dynamic-labs-sdk/client';
import '../../../config/ApiEndpoint.js';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import 'react/jsx-runtime';
import '../../../context/ViewContext/ViewContext.js';
import '../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '../../constants/colors.js';
import '../../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 { getEnvironmentId } from '../../../store/state/dynamicContextProps/dynamicContextProps.js';
import { getPrimaryWalletId, setPrimaryWalletId } from '../../../store/state/primaryWalletId/primaryWalletId.js';
import '../../../events/dynamicEvents.js';
import '@dynamic-labs/locale';
import { refreshUserJwt } from '../../../data/api/user/user.js';
import { findPrimaryWalletVCForUser } from '../../functions/findPrimaryWalletVCForUser/findPrimaryWalletVCForUser.js';

/**
 * Refresh user state
 * @returns A callback function that can be used to refresh the user state
 */
const useRefreshUser = () => useCallback(() => __awaiter(void 0, void 0, void 0, function* () {
    const user = yield refreshUserJwt({ environmentId: getEnvironmentId() });
    if (!(user === null || user === void 0 ? void 0 : user.verifiedCredentials))
        throw new Error('useRefreshUser resulted in an invalid user: no verified credentials found');
    // Check if the primary wallet is still in this user's VCs
    const primaryWalletInUserVCs = user.verifiedCredentials.some(({ id }) => id === getPrimaryWalletId());
    if (primaryWalletInUserVCs)
        return user;
    // Try to set primary wallet ID from available wallets (AA or embedded)
    const primaryWalletVC = findPrimaryWalletVCForUser(user);
    if (primaryWalletVC) {
        updatePrimaryWalletId(primaryWalletVC.id);
        return user;
    }
    // No wallet VCs found, unset the primary wallet
    setPrimaryWalletId(undefined);
    return user;
}), []);

export { useRefreshUser };
