'use client'
import { useRef, useMemo } from 'react';
import { isWalletBookPopulated } from '@dynamic-labs/wallet-book';
import { tracing } from '@dynamic-labs/utils';
import { logger } from '../../../shared/logger.js';
import { lastAuthenticatedAccount } from '../../../shared/utils/functions/lastAuthenticatedAccount/index.js';
import { shouldFetchNonce } from '../../../shared/utils/functions/shouldFetchNonce/shouldFetchNonce.js';
import { useLoadingAndLifecycle } from '../../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import { useAuthMode } from '../../../store/state/authMode/authMode.js';
import '@dynamic-labs-sdk/client/core';
import '@dynamic-labs/sdk-api-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 '../../constants/colors.js';
import '../../constants/values.js';
import '../../../shared/consts/index.js';
import '../../../../../_virtual/_tslib.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../../store/state/nonce/nonce.js';
import '@dynamic-labs/locale';
import '../../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../../store/state/primaryWalletId/primaryWalletId.js';
import '../../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../../../events/dynamicEvents.js';
import { useInitStatus } from '../../../client/extension/initStatus/useInitStatus/useInitStatus.js';

const useGlobalLoading = ({ connectedInfo, connectedWallets, projectSettings, primaryWalletId, primaryWallet, user, walletBook, enableInstrumentation, appName, environmentId, nonce, }) => {
    var _a;
    // Once we declare the SDK as loaded, we do not ever want to flip back to false
    const hasLoaded = useRef(false);
    const loadingStart = useRef(new Date().getTime());
    const didTraceSdkMountedRef = useRef(false);
    const initStatus = useInitStatus();
    if (!didTraceSdkMountedRef.current) {
        didTraceSdkMountedRef.current = true;
        tracing.logEvent('sdk-react-core.initialization', 'sdk-mounted');
    }
    const { sessionValidation } = useLoadingAndLifecycle();
    const authMode = useAuthMode();
    const isFetchingNonce = useMemo(() => shouldFetchNonce({
        authMode,
    }) && !nonce, [authMode, nonce]);
    const finishLoading = () => {
        if (hasLoaded.current)
            return;
        hasLoaded.current = true;
        logger.debug('[useGlobalLoading] SDK finished loading', {
            authMode,
            enableInstrumentation,
            primaryWallet,
            user,
        });
        tracing.logEvent('sdk-react-core.initialization', 'sdk-loaded');
        // Calculate how long loading took and emit log
        if (enableInstrumentation) {
            const loadingTime = new Date().getTime() - loadingStart.current;
            // Pass as default arg and as an object. The object value will be injected
            // in the log later on, keeping its format as a number for calculation purposes
            logger.instrument(`SDK loaded in (ms) ${loadingTime}`, {
                appName,
                environmentId,
                key: 'sdkHasLoaded',
                primaryWalletId,
                time: loadingTime,
                userId: user === null || user === void 0 ? void 0 : user.userId,
            });
        }
    };
    if (hasLoaded.current)
        return true;
    const isWalletBookLoading = !isWalletBookPopulated(walletBook);
    const isJavascriptSDKLoading = initStatus === 'uninitialized' || initStatus === 'in-progress';
    const isProjectSettingsLoading = !projectSettings;
    const shouldHavePrimaryWallet = primaryWalletId ||
        (user && ((_a = lastAuthenticatedAccount(user)) === null || _a === void 0 ? void 0 : _a.format) === 'blockchain');
    const isPrimaryWalletLoading = Boolean(shouldHavePrimaryWallet && !primaryWallet);
    const isConnectOnlyWalletsLoading = authMode === 'connect-only' &&
        connectedInfo &&
        connectedWallets.length === 0;
    const isValidatingSession = !sessionValidation;
    logger.logVerboseTroubleshootingMessage('[useGlobalLoading] SDK loading', {
        isConnectOnlyWalletsLoading,
        isFetchingNonce,
        isPrimaryWalletLoading,
        isProjectSettingsLoading,
        isValidatingSession,
        isWalletBookLoading,
        javascriptSDKInitStatus: initStatus,
    });
    if (!isWalletBookLoading &&
        !isProjectSettingsLoading &&
        !isPrimaryWalletLoading &&
        !isConnectOnlyWalletsLoading &&
        !isValidatingSession &&
        !isFetchingNonce &&
        !isJavascriptSDKLoading) {
        finishLoading();
    }
    return hasLoaded.current;
};

export { useGlobalLoading };
