'use client'
import { __awaiter } from '../../../../../_virtual/_tslib.js';
import { DynamicError } from '@dynamic-labs/utils';
import '@dynamic-labs/sdk-api-core';
import '@dynamic-labs-sdk/client/core';
import '../../../client/client.js';
import 'react';
import '@dynamic-labs-sdk/client';
import '../../../config/ApiEndpoint.js';
import '../../../utils/constants/values.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../../utils/constants/colors.js';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import 'react/jsx-runtime';
import '../../../context/ViewContext/ViewContext.js';
import { logger } from '../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '../../../shared/consts/index.js';
import { useEnvironmentId, getEnvironmentId } from '../dynamicContextProps/dynamicContextProps.js';
import '../primaryWalletId/primaryWalletId.js';
import '../connectedWalletsInfo/connectedWalletsInfo.js';
import '../../../events/dynamicEvents.js';
import { getNonce as getNonce$1 } from '../../../data/api/utils.js';
import '@dynamic-labs/locale';
import { useDynamicEvents } from '../../../utils/hooks/events/useDynamicEvents/useDynamicEvents.js';
import '../../../context/DynamicContext/DynamicContext.js';
import '../loadingAndLifecycle/loadingAndLifecycle.js';
import '../authMode/authMode.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 '../../../context/VerificationContext/VerificationContext.js';
import 'react-dom';
import '../../../utils/functions/compareChains/compareChains.js';
import '../../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import '../../../context/ThemeContext/ThemeContext.js';
import '../../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.js';
import 'bs58';
import { usePromise } from '../../../utils/hooks/usePromise/usePromise.js';
import '@dynamic-labs/types';
import '../../../context/SocialRedirectContext/SocialRedirectContext.js';
import '../../../context/LoadingContext/LoadingContext.js';
import '../../../context/WalletContext/WalletContext.js';
import '../../../utils/hooks/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 '../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 '../../../utils/hooks/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 '../sendBalances.js';
import '../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 '../tokenBalances.js';
import '../multichainBalances.js';
import '../../../shared/utils/functions/getInitialUrl/getInitialUrl.js';
import { createStoreState } from '../../internalImplementation/utils/createStoreState/createStoreState.js';

const { getNonce: getNonceRaw, setNonce, useNonce: useNonceRaw, } = createStoreState('nonce');
const getNonce = () => getNonceRaw().nonce;
const useNonce = () => useNonceRaw().nonce;
const storeNewNonce = (newNonce) => {
    const expiry = new Date().getTime() + 60000 * 60 * 24;
    setNonce({
        expiresAt: expiry,
        nonce: newNonce,
    });
};
let nonceExpiryTimeout;
const checkAndExpireNonceWhenRequired = () => {
    const nonce = getNonceRaw();
    if (!(nonce === null || nonce === void 0 ? void 0 : nonce.expiresAt)) {
        return;
    }
    if (nonceExpiryTimeout) {
        clearTimeout(nonceExpiryTimeout);
    }
    const timeToExpire = nonce.expiresAt - new Date().getTime();
    const timeout = timeToExpire > 0 ? timeToExpire : 0;
    nonceExpiryTimeout = setTimeout(() => {
        logger.debug('[Nonce] Expiring nonce', {
            expiresAt: nonce.expiresAt,
            nonce: nonce.nonce,
        });
        setNonce({
            expiresAt: undefined,
            nonce: undefined,
        });
    }, timeout);
};
const useFetchNonce = ({ shouldFetch = true, retries = 2, } = {}) => {
    const nonce = useNonce();
    const environmentId = useEnvironmentId();
    checkAndExpireNonceWhenRequired();
    const { retrigger } = usePromise(() => __awaiter(void 0, void 0, void 0, function* () { return getNonce$1(environmentId); }), {
        deps: [environmentId],
        enabled: shouldFetch && !nonce,
        onResolve: (newNonce) => {
            storeNewNonce(newNonce);
            checkAndExpireNonceWhenRequired();
        },
        retries,
    });
    useDynamicEvents('logout', retrigger);
    return nonce;
};
const consumeNonce = () => {
    const nonce = getNonce();
    if (!nonce) {
        throw new DynamicError('Nonce is not defined');
    }
    setNonce({
        expiresAt: undefined,
        nonce: undefined,
    });
    return nonce;
};
const fetchAndStoreNonce = () => __awaiter(void 0, void 0, void 0, function* () {
    const existingNonce = getNonce();
    if (existingNonce) {
        return;
    }
    const environmentId = getEnvironmentId();
    const nonce = yield getNonce$1(environmentId);
    storeNewNonce(nonce);
});

export { consumeNonce, fetchAndStoreNonce, getNonce, setNonce, useFetchNonce, useNonce };
