'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { useRef, useCallback, useEffect } from 'react';
import { getDynamicClient } from '../../../client/client.js';
import '@dynamic-labs-sdk/client/core';
import '@dynamic-labs/sdk-api-core';
import '@dynamic-labs-sdk/client';
import '../../../config/ApiEndpoint.js';
import '../../constants/values.js';
import '@dynamic-labs/utils';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../constants/colors.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 '../../../shared/consts/index.js';
import '../../../store/state/nonce/nonce.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 '../../../events/dynamicEvents.js';
import { useOnboardingCompleteUser } from '../../../client/extension/user/useOnboardingCompleteUser/useOnboardingCompleteUser.js';
import { useProjectSettings } from '../../../client/extension/projectSettings/useProjectSettings/useProjectSettings.js';
import '../../../context/DynamicContext/DynamicContext.js';
import '../../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import { useInternalDynamicEvents } from '../events/useDynamicEvents/useDynamicEvents.js';
import '../../../context/CaptchaContext/CaptchaContext.js';
import '../../../context/ErrorContext/ErrorContext.js';
import '../../../context/AccessDeniedContext/AccessDeniedContext.js';
import '../../../context/AccountExistsContext/AccountExistsContext.js';
import '../../../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 { useMutation } from '../useMutation/useMutation.js';
import 'bs58';
import '@dynamic-labs/types';
import '../../../context/SocialRedirectContext/SocialRedirectContext.js';
import { useLoadingContext } from '../../../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 { 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 { useDynamicWaas } from '../useDynamicWaas/useDynamicWaas.js';
import { useWalletDelegation } from '../useWalletDelegation/useWalletDelegation.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';

// Validate if all required conditions are met for wallet creation
const useWalletCreationValidation = () => {
    const user = useOnboardingCompleteUser();
    const projectSettings = useProjectSettings();
    const walletConnectorOptions = useWalletConnectorOptions();
    const { loading: globalLoading } = useLoadingContext();
    return useCallback(() => {
        // Check if user is properly authenticated
        const hasUser = Boolean(user && 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();
    const { clearStackAndPush } = useViewContext();
    const { createWalletAccount } = useDynamicWaas();
    const user = useOnboardingCompleteUser();
    const environmentId = useEnvironmentId();
    return useMutation((chains) => __awaiter(void 0, void 0, void 0, function* () {
        const startTime = Date.now();
        // Log wallet creation initiation to DataDog
        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.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.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.error('Error creating dynamic waas wallet', error);
            setShowAuthFlow(true);
            clearStackAndPush('backup-unsuccessful');
        },
    });
};
const useWalletSettingsProcessor = () => {
    const { processSignOnWalletSettings } = useDynamicWaas();
    return useMutation(() => __awaiter(void 0, void 0, void 0, function* () {
        yield processSignOnWalletSettings();
    }), {
        onFailure: (error) => {
            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 } = useDynamicWaas();
    const validateWalletCreation = useWalletCreationValidation();
    const { mutate: createWallets, isLoading: isCreatingWallets } = useWalletCreation();
    const { mutate: processSettings, isLoading: isProcessingSettings } = useWalletSettingsProcessor();
    const { initDelegationProcess, shouldPromptWalletDelegation } = useWalletDelegation();
    const triggeredCreate = useRef(false);
    const triggeredSettingsProcessing = useRef(false);
    useInternalDynamicEvents('logout', () => {
        triggeredCreate.current = false;
        triggeredSettingsProcessing.current = false;
    });
    const shouldCreateWallets = 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 = useCallback(() => {
        if (triggeredSettingsProcessing.current || isProcessingSettings) {
            return false;
        }
        if (!needsSettingsProcessing) {
            return false;
        }
        const validation = validateWalletCreation();
        return validation.isValid;
    }, [needsSettingsProcessing, validateWalletCreation, isProcessingSettings]);
    const handleSettingsProcessing = useCallback(() => {
        if (!shouldProcessSettings()) {
            return;
        }
        processSettings();
        triggeredSettingsProcessing.current = true;
    }, [shouldProcessSettings, processSettings]);
    useEffect(() => {
        if (shouldProcessSettings()) {
            handleSettingsProcessing();
        }
    }, [shouldProcessSettings, handleSettingsProcessing]);
    const handleWalletCreation = useCallback(() => {
        if (!shouldCreateWallets() || !needsAutoCreateWalletChains) {
            return;
        }
        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]);
    useEffect(() => {
        if (shouldCreateWallets()) {
            handleWalletCreation();
        }
    }, [shouldCreateWallets, handleWalletCreation]);
    useEffect(() => {
        if (shouldPromptWalletDelegation()) {
            initDelegationProcess();
        }
    }, [shouldPromptWalletDelegation, initDelegationProcess]);
};

export { useSyncDynamicWaas };
