'use client'
import { __awaiter } from '../../../../_virtual/_tslib.js';
import { jsx } from 'react/jsx-runtime';
import { createContext, useContext, useState, useMemo, useCallback } from 'react';
import { PlatformService, getTLD } from '@dynamic-labs/utils';
import '../../events/dynamicEvents.js';
import '../DynamicContext/DynamicContext.js';
import '../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import '../ViewContext/ViewContext.js';
import { logger } from '../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import { EMBEDDED_WALLET_SECURE_BANNER } from '../../utils/constants/localStorage.js';
import '../../utils/constants/colors.js';
import '../../utils/constants/values.js';
import '@dynamic-labs/sdk-api-core';
import { useLocalStorage } from '../../shared/utils/hooks/useLocalStorage/useLocalStorage.js';
import '../../shared/consts/index.js';
import '../../store/state/authMode/authMode.js';
import { useInternalDynamicContext } from '../DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import '../CaptchaContext/CaptchaContext.js';
import '../ErrorContext/ErrorContext.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import '../../store/state/nonce/nonce.js';
import '@dynamic-labs-sdk/client/core';
import '../../client/client.js';
import '@dynamic-labs-sdk/client';
import '../../config/ApiEndpoint.js';
import { getUserPasskeys } from '../../data/api/embeddedWallets/embeddedWallets.js';
import '@dynamic-labs/locale';
import '../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../store/state/primaryWalletId/primaryWalletId.js';
import '../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../AccessDeniedContext/AccessDeniedContext.js';
import '../AccountExistsContext/AccountExistsContext.js';
import '../UserWalletsContext/UserWalletsContext.js';
import '../VerificationContext/VerificationContext.js';
import 'react-dom';
import '../../utils/functions/compareChains/compareChains.js';
import '../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.js';
import '../ThemeContext/ThemeContext.js';
import '../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.js';
import { useIsTurnkeyWallet } from '../../utils/hooks/useIsTurnkeyWallet/useIsTurnkeyWallet.js';
import 'bs58';
import { usePromise } from '../../utils/hooks/usePromise/usePromise.js';
import '@dynamic-labs/types';
import '../SocialRedirectContext/SocialRedirectContext.js';
import '../LoadingContext/LoadingContext.js';
import { useEmbeddedWallet } from '../../utils/hooks/useEmbeddedWallet/useEmbeddedWallet.js';
import '../WalletContext/WalletContext.js';
import { EmbeddedWalletVersion } from '../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.js';
import 'yup';
import '../MockContext/MockContext.js';
import '../../views/CollectUserDataView/useFields.js';
import '../FieldsStateContext/FieldsStateContext.js';
import '../UserFieldEditorContext/UserFieldEditorContext.js';
import '@dynamic-labs/rpc-providers';
import '../../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 '../../utils/hooks/useSubdomainCheck/useSubdomainCheck.js';
import '../WalletGroupContext/WalletGroupContext.js';
import '../IpConfigurationContext/IpConfigurationContext.js';
import '../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 '../ErrorContext/hooks/useErrorText/useErrorText.js';
import '../FooterAnimationContext/index.js';
import '../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.js';
import '../OnrampContext/OnrampContext.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';

const PasskeyContext = createContext(undefined);
const PasskeyContextProviderWithBrowser = ({ children, }) => {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    const { userHasEmbeddedWallet, getWalletVersion } = useEmbeddedWallet();
    const { isSessionKeyCompatible, isTurnkeyWalletWithoutAuthenticator } = useIsTurnkeyWallet();
    const { environmentId, projectSettings, user } = useInternalDynamicContext();
    // state for when passkey list needs to re-render
    const [passkeyEdited, setPasskeyEdited] = useState(false);
    // states to pass into rename passkey popup
    const [passkey, setPasskey] = useState(undefined);
    const [passkeyIcon, setPasskeyIcon] = useState(undefined);
    const [_showSecureAccountBanner, setShowSecureAccountBanner] = useLocalStorage(EMBEDDED_WALLET_SECURE_BANNER, true);
    const showSecureAccountBanner = useMemo(() => {
        var _a, _b, _c, _d;
        const isPasskeyEnabled = Boolean((_d = (_c = (_b = (_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _a === void 0 ? void 0 : _a.embeddedWallets) === null || _b === void 0 ? void 0 : _b.supportedSecurityMethods) === null || _c === void 0 ? void 0 : _c.passkey) === null || _d === void 0 ? void 0 : _d.isEnabled);
        return (_showSecureAccountBanner !== false &&
            isTurnkeyWalletWithoutAuthenticator &&
            isPasskeyEnabled);
    }, [
        isTurnkeyWalletWithoutAuthenticator,
        _showSecureAccountBanner,
        (_d = (_c = (_b = (_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _a === void 0 ? void 0 : _a.embeddedWallets) === null || _b === void 0 ? void 0 : _b.supportedSecurityMethods) === null || _c === void 0 ? void 0 : _c.passkey) === null || _d === void 0 ? void 0 : _d.isEnabled,
    ]);
    const showAlert = useCallback(() => {
        var _a, _b, _c, _d;
        const isPasskeyEnabled = Boolean((_d = (_c = (_b = (_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _a === void 0 ? void 0 : _a.embeddedWallets) === null || _b === void 0 ? void 0 : _b.supportedSecurityMethods) === null || _c === void 0 ? void 0 : _c.passkey) === null || _d === void 0 ? void 0 : _d.isEnabled);
        const isPregeneratedWalletsWithPasskeyRequired = !showSecureAccountBanner &&
            isTurnkeyWalletWithoutAuthenticator &&
            isPasskeyEnabled;
        return !isSessionKeyCompatible && isPregeneratedWalletsWithPasskeyRequired;
    }, [
        (_h = (_g = (_f = (_e = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk) === null || _e === void 0 ? void 0 : _e.embeddedWallets) === null || _f === void 0 ? void 0 : _f.supportedSecurityMethods) === null || _g === void 0 ? void 0 : _g.passkey) === null || _h === void 0 ? void 0 : _h.isEnabled,
        showSecureAccountBanner,
        isSessionKeyCompatible,
        isTurnkeyWalletWithoutAuthenticator,
    ]);
    // It fetches user passkeys if user has embedded wallet
    const getUserPasskeysResult = usePromise(() => __awaiter(void 0, void 0, void 0, function* () {
        const walletVersion = getWalletVersion();
        const isV1Wallet = walletVersion === EmbeddedWalletVersion.V1;
        if (isV1Wallet) {
            const data = yield getUserPasskeys({
                environmentId: environmentId,
            });
            return data.passkeys;
        }
        return;
    }), {
        deps: [
            environmentId,
            user,
            userHasEmbeddedWallet(),
            passkeyEdited,
            getWalletVersion,
        ],
        enabled: Boolean(environmentId && user && userHasEmbeddedWallet()),
    });
    // Returns true if user has passkeys for current origin
    const userHasPasskeysForCurrentOrigin = useMemo(() => {
        if (typeof window === 'undefined') {
            return false;
        }
        const hostname = PlatformService.getHostname();
        if (!getUserPasskeysResult.data)
            return false;
        return getUserPasskeysResult.data.some((passkey) => {
            if (!passkey.origin)
                return false;
            try {
                const passkeyHostname = new URL(passkey.origin).hostname;
                return passkeyHostname === getTLD() || passkeyHostname === hostname;
            }
            catch (e) {
                logger.error(e);
                return false;
            }
        });
    }, [getUserPasskeysResult.data]);
    // user has passkey configured, but not for current origin
    const userNeedsCrossDomainPasskey = !isTurnkeyWalletWithoutAuthenticator && !userHasPasskeysForCurrentOrigin;
    const value = useMemo(() => {
        var _a;
        return ({
            passkey,
            passkeyEdited,
            passkeyIcon,
            setPasskey,
            setPasskeyEdited,
            setPasskeyIcon,
            setShowSecureAccountBanner,
            showAlert,
            showSecureAccountBanner,
            userHasPasskeysForCurrentOrigin,
            userNeedsCrossDomainPasskey,
            userPasskeys: (_a = getUserPasskeysResult.data) !== null && _a !== void 0 ? _a : [],
            userPasskeysLoading: getUserPasskeysResult.isLoading,
        });
    }, [
        passkey,
        passkeyEdited,
        passkeyIcon,
        userHasPasskeysForCurrentOrigin,
        getUserPasskeysResult.data,
        getUserPasskeysResult.isLoading,
        userNeedsCrossDomainPasskey,
        showAlert,
        setShowSecureAccountBanner,
        showSecureAccountBanner,
    ]);
    return (jsx(PasskeyContext.Provider, { value: value, children: children }));
};
// We need to export the context this way so it works with SSR (next.js)
const PasskeyContextProvider = ({ children, }) => (jsx(PasskeyContextProviderWithBrowser, { children: children }));
const usePasskeyContext = () => {
    const context = useContext(PasskeyContext);
    if (context === undefined) {
        throw new Error('usage of PasskeyContext not wrapped in `PasskeyContextProvider`.');
    }
    return context;
};

export { PasskeyContext, PasskeyContextProvider, usePasskeyContext };
