'use client'
'use strict';

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

var _tslib = require('../../../../../_virtual/_tslib.cjs');
var React = require('react');
var client = require('../../../client/client.cjs');
require('@dynamic-labs-sdk/client/core');
require('@dynamic-labs/sdk-api-core');
require('@dynamic-labs-sdk/client');
require('../../../config/ApiEndpoint.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');
require('@dynamic-labs/utils');
require('../../constants/colors.cjs');
require('../../constants/values.cjs');
require('../../../shared/consts/index.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../../store/state/nonce/nonce.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('../../../events/dynamicEvents.cjs');
var useOnboardingCompleteUser = require('../../../client/extension/user/useOnboardingCompleteUser/useOnboardingCompleteUser.cjs');
var useProjectSettings = require('../../../client/extension/projectSettings/useProjectSettings/useProjectSettings.cjs');
require('../../../context/DynamicContext/DynamicContext.cjs');
require('../../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
var useDynamicEvents = require('../events/useDynamicEvents/useDynamicEvents.cjs');
require('../../../context/CaptchaContext/CaptchaContext.cjs');
require('../../../context/ErrorContext/ErrorContext.cjs');
require('../../../context/AccessDeniedContext/AccessDeniedContext.cjs');
require('../../../context/AccountExistsContext/AccountExistsContext.cjs');
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');
var useMutation = require('../useMutation/useMutation.cjs');
require('bs58');
require('@dynamic-labs/types');
require('../../../context/SocialRedirectContext/SocialRedirectContext.cjs');
var LoadingContext = 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');
var walletOptions = 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 useWalletDelegation = require('../useWalletDelegation/useWalletDelegation.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');

// Validate if all required conditions are met for wallet creation
const useWalletCreationValidation = () => {
    const user = useOnboardingCompleteUser.useOnboardingCompleteUser();
    const projectSettings = useProjectSettings.useProjectSettings();
    const walletConnectorOptions = walletOptions.useWalletConnectorOptions();
    const { loading: globalLoading } = LoadingContext.useLoadingContext();
    return React.useCallback(() => {
        // Check if user is properly authenticated
        const hasUser = Boolean(user && client.getDynamicClient().user);
        if (!hasUser) {
            return { isValid: false, reason: 'User not authenticated' };
        }
        if (!projectSettings) {
            return { isValid: false, reason: 'Project settings not loaded' };
        }
        if (!walletConnectorOptions.length) {
            return { isValid: false, reason: 'No wallet connectors available' };
        }
        if (globalLoading) {
            return { isValid: false, reason: 'Authentication in progress' };
        }
        return { isValid: true };
    }, [user, projectSettings, walletConnectorOptions, globalLoading]);
};
// Manage wallet creation with proper error handling
const useWalletCreation = () => {
    const { setShowAuthFlow } = useInternalDynamicContext.useInternalDynamicContext();
    const { clearStackAndPush } = ViewContext.useViewContext();
    const { createWalletAccount } = useDynamicWaas.useDynamicWaas();
    const user = useOnboardingCompleteUser.useOnboardingCompleteUser();
    const environmentId = dynamicContextProps.useEnvironmentId();
    return useMutation.useMutation((chains) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        const startTime = Date.now();
        // Log wallet creation initiation to DataDog
        logger.logger.instrument('Auto wallet creation initiated', {
            chainCount: chains.length,
            chains: chains.join(','),
            environmentId,
            key: 'auto_wallet_creation_initiated',
            time: 0,
            userId: user === null || user === void 0 ? void 0 : user.id,
        });
        try {
            yield createWalletAccount(chains);
            const duration = Date.now() - startTime;
            // Log successful wallet creation to DataDog
            logger.logger.instrument('Auto wallet creation successful', {
                chainCount: chains.length,
                chains: chains.join(','),
                environmentId,
                key: 'auto_wallet_creation_success',
                time: duration,
                userId: user === null || user === void 0 ? void 0 : user.id,
            });
        }
        catch (error) {
            const duration = Date.now() - startTime;
            logger.logger.instrument('Auto wallet creation failed', {
                chainCount: chains.length,
                chains: chains.join(','),
                environmentId,
                error: error instanceof Error ? error.message : 'Unknown error',
                key: 'auto_wallet_creation_failed',
                time: duration,
                userId: user === null || user === void 0 ? void 0 : user.id,
            });
            throw error;
        }
    }), {
        onFailure: (error) => {
            logger.logger.error('Error creating dynamic waas wallet', error);
            setShowAuthFlow(true);
            clearStackAndPush('backup-unsuccessful');
        },
    });
};
const useWalletSettingsProcessor = () => {
    const { processSignOnWalletSettings } = useDynamicWaas.useDynamicWaas();
    return useMutation.useMutation(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        yield processSignOnWalletSettings();
    }), {
        onFailure: (error) => {
            logger.logger.error('Error processing wallet settings', error);
        },
    });
};
/**
 * Hook that synchronizes Dynamic WaaS wallet creation based on user state and configuration.
 *
 * This hook automatically creates embedded wallets for enabled chains when:
 * - User is authenticated and onboarding is complete
 * - Project settings allow automatic wallet creation
 * - Required chains don't already have wallets
 * - No authentication is currently in progress
 *
 * The hook ensures wallet creation only happens once per session until logout.
 */
const useSyncDynamicWaas = () => {
    const { needsAutoCreateWalletChains, needsSettingsProcessing, initializeWaas, shouldInitializeWaas, } = useDynamicWaas.useDynamicWaas();
    const validateWalletCreation = useWalletCreationValidation();
    const { mutate: createWallets, isLoading: isCreatingWallets } = useWalletCreation();
    const { mutate: processSettings, isLoading: isProcessingSettings } = useWalletSettingsProcessor();
    const { initDelegationProcess, shouldPromptWalletDelegation } = useWalletDelegation.useWalletDelegation();
    const user = useOnboardingCompleteUser.useOnboardingCompleteUser();
    const triggeredCreate = React.useRef(false);
    const triggeredSettingsProcessing = React.useRef(false);
    const hasWaasInitializedRef = React.useRef(false);
    const sessionIdRef = React.useRef(undefined);
    const initializingWaasRef = React.useRef(false);
    useDynamicEvents.useInternalDynamicEvents('logout', () => {
        triggeredCreate.current = false;
        triggeredSettingsProcessing.current = false;
    });
    const shouldCreateWallets = React.useCallback(() => {
        if (triggeredCreate.current || isCreatingWallets) {
            return false;
        }
        if (!(needsAutoCreateWalletChains === null || needsAutoCreateWalletChains === void 0 ? void 0 : needsAutoCreateWalletChains.length)) {
            return false;
        }
        const validation = validateWalletCreation();
        return validation.isValid;
    }, [needsAutoCreateWalletChains, validateWalletCreation, isCreatingWallets]);
    const shouldProcessSettings = React.useCallback(() => {
        if (triggeredSettingsProcessing.current || isProcessingSettings) {
            return false;
        }
        if (!needsSettingsProcessing) {
            return false;
        }
        const validation = validateWalletCreation();
        return validation.isValid;
    }, [needsSettingsProcessing, validateWalletCreation, isProcessingSettings]);
    const handleSettingsProcessing = React.useCallback(() => {
        if (!shouldProcessSettings()) {
            return;
        }
        processSettings();
        triggeredSettingsProcessing.current = true;
    }, [shouldProcessSettings, processSettings]);
    React.useEffect(() => {
        if (shouldProcessSettings()) {
            handleSettingsProcessing();
        }
    }, [shouldProcessSettings, handleSettingsProcessing]);
    const handleWalletCreation = React.useCallback(() => {
        if (!shouldCreateWallets() || !needsAutoCreateWalletChains) {
            return;
        }
        logger.logger.debug('Auto wallet creation triggered', {
            chainCount: needsAutoCreateWalletChains.length,
            chains: needsAutoCreateWalletChains,
        });
        // Call the mutation - it handles its own async logic and error handling
        createWallets(needsAutoCreateWalletChains);
        // Set the flag immediately to prevent duplicate calls
        triggeredCreate.current = true;
    }, [shouldCreateWallets, needsAutoCreateWalletChains, createWallets]);
    // Initialize waas iframe when user is authenticated
    // This handles both page reload (user already authenticated) and fresh authentication
    React.useEffect(() => {
        // handle logout case where user is logged out but session id is still valid
        if (sessionIdRef.current && !(user === null || user === void 0 ? void 0 : user.sessionId)) {
            sessionIdRef.current = undefined;
            hasWaasInitializedRef.current = false;
            initializingWaasRef.current = false;
        }
        if (shouldInitializeWaas && (user === null || user === void 0 ? void 0 : user.sessionId)) {
            const { sessionId, id: userId } = user;
            const shouldInitialize = !initializingWaasRef.current &&
                (!hasWaasInitializedRef.current || sessionIdRef.current !== sessionId);
            if (shouldInitialize) {
                const isSessionIdChanged = sessionIdRef.current !== sessionId;
                logger.logger.debug(isSessionIdChanged
                    ? '[useSyncDynamicWaas] session id changed, initializing waas'
                    : '[useSyncDynamicWaas] waas not initialized, initializing waas');
                initializingWaasRef.current = true;
                initializeWaas()
                    .then(() => {
                    logger.logger.debug('[useSyncDynamicWaas] waas initialized');
                    hasWaasInitializedRef.current = true;
                    sessionIdRef.current = sessionId;
                })
                    .catch((error) => {
                    logger.logger.warn('[useSyncDynamicWaas] Error initializing waas', {
                        error,
                        sessionId,
                        userId,
                    });
                })
                    .finally(() => {
                    initializingWaasRef.current = false;
                });
            }
        }
    }, [initializeWaas, shouldInitializeWaas, user]);
    React.useEffect(() => {
        if (shouldCreateWallets()) {
            handleWalletCreation();
        }
    }, [shouldCreateWallets, handleWalletCreation]);
    React.useEffect(() => {
        if (shouldPromptWalletDelegation()) {
            initDelegationProcess();
        }
    }, [shouldPromptWalletDelegation, initDelegationProcess]);
};

exports.useSyncDynamicWaas = useSyncDynamicWaas;
