'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 '@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 '@dynamic-labs/utils';
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 '@dynamic-labs/locale';
import { useEnvironmentId } from '../../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../../store/state/primaryWalletId/primaryWalletId.js';
import '../../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../../functions/getWaasAddressTypeLabel/getWaasAddressTypeLabel.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/useDynamicContext/useDynamicContext.js';
import { useInternalDynamicContext } from '../../../context/DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import { useLoadingContext } from '../../../context/LoadingContext/LoadingContext.js';
import { useWalletConnectorOptions } from '../../../store/state/walletOptions/walletOptions.js';
import { useInternalDynamicEvents } from '../events/useDynamicEvents/useDynamicEvents.js';
import { useDynamicWaas } from '../useDynamicWaas/useDynamicWaas.js';
import { useMutation } from '../useMutation/useMutation.js';
import { useSetupPassword, PASSWORD_SETUP_CANCELLED_ERROR } from '../useSetupPassword/useSetupPassword.js';
import { useWalletDelegation } from '../useWalletDelegation/useWalletDelegation.js';
import '../useWalletDelegation/DelegationError.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 { setupPassword } = useSetupPassword();
    const user = useOnboardingCompleteUser();
    const environmentId = useEnvironmentId();
    return useMutation((requirements) => __awaiter(void 0, void 0, void 0, function* () {
        const startTime = Date.now();
        const chainsString = requirements.map((req) => req.chain).join(',');
        // Log wallet creation initiation to DataDog
        logger.instrument('Auto wallet creation initiated', {
            chainCount: requirements.length,
            chains: chainsString,
            environmentId,
            key: 'auto_wallet_creation_initiated',
            time: 0,
            userId: user === null || user === void 0 ? void 0 : user.id,
        });
        try {
            // If passcodeRequired is enabled, prompt user to set up password first
            const password = yield setupPassword();
            yield createWalletAccount(requirements, password, undefined, {
                skipCloseAuthFlow: Boolean(password),
            });
            const duration = Date.now() - startTime;
            // Log successful wallet creation to DataDog
            logger.instrument('Auto wallet creation successful', {
                chainCount: requirements.length,
                chains: chainsString,
                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;
            // Don't count password setup cancellations as failures — they're intentional
            // user actions, not errors. The onFailure handler already suppresses the error
            // UI for this case; the metric should be consistent with that intent.
            if (!(error instanceof Error &&
                error.message === PASSWORD_SETUP_CANCELLED_ERROR)) {
                logger.instrument('Auto wallet creation failed', {
                    chainCount: requirements.length,
                    chains: chainsString,
                    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) => {
            // Don't show error view if user cancelled password setup
            if (error.message === PASSWORD_SETUP_CANCELLED_ERROR) {
                logger.debug('Password setup cancelled by user');
                return;
            }
            logger.error('Error creating dynamic waas wallet', error);
            setShowAuthFlow(true, { ignoreIfIsEmbeddedWidget: false });
            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 { areWalletsReadyForSettings, clearRecoveredWallets, needsAutoCreateWalletChains, initializeWaas, shouldInitializeWaas, } = useDynamicWaas();
    const validateWalletCreation = useWalletCreationValidation();
    const { mutate: createWallets, isLoading: isCreatingWallets } = useWalletCreation();
    const { mutate: processSettings, isLoading: isProcessingSettings } = useWalletSettingsProcessor();
    const { initDelegationProcess, shouldPromptWalletDelegation } = useWalletDelegation();
    const user = useOnboardingCompleteUser();
    const triggeredCreate = useRef(false);
    const triggeredSettingsProcessing = useRef(false);
    const hasWaasInitializedRef = useRef(false);
    const sessionIdRef = useRef(undefined);
    const initializingWaasRef = useRef(false);
    useInternalDynamicEvents('logout', () => {
        triggeredCreate.current = false;
        triggeredSettingsProcessing.current = false;
        clearRecoveredWallets();
    });
    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;
        }
        // Settings processing requires wallets to be recovered first
        if (!areWalletsReadyForSettings()) {
            return false;
        }
        const validation = validateWalletCreation();
        return validation.isValid;
    }, [
        areWalletsReadyForSettings,
        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.map((req) => req.chain),
        });
        // 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
    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;
            clearRecoveredWallets();
        }
        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.debug(isSessionIdChanged
                    ? '[useSyncDynamicWaas] session id changed, initializing waas'
                    : '[useSyncDynamicWaas] waas not initialized, initializing waas');
                initializingWaasRef.current = true;
                initializeWaas()
                    .then(() => {
                    logger.debug('[useSyncDynamicWaas] waas initialized');
                    hasWaasInitializedRef.current = true;
                    sessionIdRef.current = sessionId;
                })
                    .catch((error) => {
                    logger.warn('[useSyncDynamicWaas] Error initializing waas', {
                        error,
                        sessionId,
                        userId,
                    });
                })
                    .finally(() => {
                    initializingWaasRef.current = false;
                });
            }
        }
    }, [initializeWaas, shouldInitializeWaas, user]);
    useEffect(() => {
        if (shouldCreateWallets()) {
            handleWalletCreation();
        }
    }, [shouldCreateWallets, handleWalletCreation]);
    useEffect(() => {
        if (shouldPromptWalletDelegation()) {
            initDelegationProcess();
        }
    }, [shouldPromptWalletDelegation, initDelegationProcess]);
};

export { useSyncDynamicWaas };
