'use client'
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _tslib = require('../../../../_virtual/_tslib.cjs');
var jsxRuntime = require('react/jsx-runtime');
var React = require('react');
var utils = require('@dynamic-labs/utils');
require('../../events/dynamicEvents.cjs');
require('../DynamicContext/DynamicContext.cjs');
require('../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
require('../ViewContext/ViewContext.cjs');
var logger = require('../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
var localStorage = require('../../utils/constants/localStorage.cjs');
require('../../utils/constants/colors.cjs');
require('../../utils/constants/values.cjs');
require('@dynamic-labs/sdk-api-core');
var useLocalStorage = require('../../shared/utils/hooks/useLocalStorage/useLocalStorage.cjs');
require('../../shared/consts/index.cjs');
require('../../store/state/authMode/authMode.cjs');
var useInternalDynamicContext = require('../DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');
require('../CaptchaContext/CaptchaContext.cjs');
require('../ErrorContext/ErrorContext.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
require('../../store/state/nonce/nonce.cjs');
require('@dynamic-labs-sdk/client/core');
require('../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../config/ApiEndpoint.cjs');
var embeddedWallets = require('../../data/api/embeddedWallets/embeddedWallets.cjs');
require('@dynamic-labs/locale');
require('../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../AccessDeniedContext/AccessDeniedContext.cjs');
require('../AccountExistsContext/AccountExistsContext.cjs');
require('../UserWalletsContext/UserWalletsContext.cjs');
require('../VerificationContext/VerificationContext.cjs');
require('react-dom');
require('../../utils/functions/compareChains/compareChains.cjs');
require('../../views/Passkey/utils/findPrimaryEmbeddedChain/findPrimaryEmbeddedChain.cjs');
require('../ThemeContext/ThemeContext.cjs');
require('../../utils/hooks/useUserUpdateRequest/useUpdateUser/userFieldsSchema.cjs');
var useIsTurnkeyWallet = require('../../utils/hooks/useIsTurnkeyWallet/useIsTurnkeyWallet.cjs');
require('bs58');
var usePromise = require('../../utils/hooks/usePromise/usePromise.cjs');
require('@dynamic-labs/types');
require('../SocialRedirectContext/SocialRedirectContext.cjs');
require('../LoadingContext/LoadingContext.cjs');
var useEmbeddedWallet = require('../../utils/hooks/useEmbeddedWallet/useEmbeddedWallet.cjs');
require('../WalletContext/WalletContext.cjs');
var constants = require('../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.cjs');
require('yup');
require('../MockContext/MockContext.cjs');
require('../../views/CollectUserDataView/useFields.cjs');
require('../FieldsStateContext/FieldsStateContext.cjs');
require('../UserFieldEditorContext/UserFieldEditorContext.cjs');
require('@dynamic-labs/rpc-providers');
require('../../store/state/walletOptions/walletOptions.cjs');
require('react-i18next');
require('../../components/Accordion/components/AccordionItem/AccordionItem.cjs');
require('../../components/Alert/Alert.cjs');
require('../../components/ShadowDOM/ShadowDOM.cjs');
require('../../components/IconButton/IconButton.cjs');
require('../../components/InlineWidget/InlineWidget.cjs');
require('../../components/Input/Input.cjs');
require('../../components/IsBrowser/IsBrowser.cjs');
require('../../components/MenuList/Dropdown/Dropdown.cjs');
require('../../components/OverlayCard/OverlayCard.cjs');
require('../../components/Transition/ZoomTransition/ZoomTransition.cjs');
require('../../components/Transition/SlideInUpTransition/SlideInUpTransition.cjs');
require('../../components/Transition/OpacityTransition/OpacityTransition.cjs');
require('../../components/PasskeyCreatedSuccessBanner/PasskeyCreatedSuccessBanner.cjs');
require('../../components/Popper/Popper/Popper.cjs');
require('../../components/Popper/PopperContext/PopperContext.cjs');
require('react-focus-lock');
require('qrcode');
require('formik');
require('../../utils/hooks/useSubdomainCheck/useSubdomainCheck.cjs');
require('../WalletGroupContext/WalletGroupContext.cjs');
require('../IpConfigurationContext/IpConfigurationContext.cjs');
require('../ConnectWithOtpContext/ConnectWithOtpContext.cjs');
require('../../widgets/DynamicBridgeWidget/views/WalletsView/components/SecondaryWallets/SecondaryWallets.cjs');
require('@hcaptcha/react-hcaptcha');
require('../../widgets/DynamicWidget/context/DynamicWidgetContext.cjs');
require('../../widgets/DynamicWidget/helpers/convertExchangeKeyAndProviderEnum.cjs');
require('../../views/ExchangeWhitelistWarning/ExchangeWhitelistWarning.cjs');
require('../ErrorContext/hooks/useErrorText/useErrorText.cjs');
require('../FooterAnimationContext/index.cjs');
require('../../views/MfaChooseDeviceView/useGetMfaOptions/useGetMfaOptions.cjs');
require('../OnrampContext/OnrampContext.cjs');
require('../../store/state/sendBalances.cjs');
require('../../store/state/connectorsInitializing/connectorsInitializing.cjs');
require('../../components/OverlayCardBase/OverlayCardTarget/OverlayCardTarget.cjs');
require('../../widgets/DynamicWidget/components/DynamicWidgetHeader/DynamicWidgetHeader.cjs');
require('../../views/TransactionConfirmationView/TransactionConfirmationView.cjs');
require('../../widgets/DynamicWidget/components/PasskeyCard/PasskeyCard.cjs');
require('../../widgets/DynamicWidget/views/CryptoComOnramp/CryptoComOnramp.cjs');
require('../../../index.cjs');
require('../../widgets/DynamicWidget/views/ReceiveWalletFunds/ReceiveWalletFunds.cjs');
require('../../store/state/tokenBalances.cjs');
require('../../store/state/multichainBalances.cjs');
require('../../shared/utils/functions/getInitialUrl/getInitialUrl.cjs');

const PasskeyContext = React.createContext(undefined);
const PasskeyContextProviderWithBrowser = ({ children, }) => {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    const { userHasEmbeddedWallet, getWalletVersion } = useEmbeddedWallet.useEmbeddedWallet();
    const { isSessionKeyCompatible, isTurnkeyWalletWithoutAuthenticator } = useIsTurnkeyWallet.useIsTurnkeyWallet();
    const { environmentId, projectSettings, user } = useInternalDynamicContext.useInternalDynamicContext();
    // state for when passkey list needs to re-render
    const [passkeyEdited, setPasskeyEdited] = React.useState(false);
    // states to pass into rename passkey popup
    const [passkey, setPasskey] = React.useState(undefined);
    const [passkeyIcon, setPasskeyIcon] = React.useState(undefined);
    const [_showSecureAccountBanner, setShowSecureAccountBanner] = useLocalStorage.useLocalStorage(localStorage.EMBEDDED_WALLET_SECURE_BANNER, true);
    const showSecureAccountBanner = React.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 = React.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.usePromise(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        const walletVersion = getWalletVersion();
        const isV1Wallet = walletVersion === constants.EmbeddedWalletVersion.V1;
        if (isV1Wallet) {
            const data = yield embeddedWallets.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 = React.useMemo(() => {
        if (typeof window === 'undefined') {
            return false;
        }
        const hostname = utils.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 === utils.getTLD() || passkeyHostname === hostname;
            }
            catch (e) {
                logger.logger.error(e);
                return false;
            }
        });
    }, [getUserPasskeysResult.data]);
    // user has passkey configured, but not for current origin
    const userNeedsCrossDomainPasskey = !isTurnkeyWalletWithoutAuthenticator && !userHasPasskeysForCurrentOrigin;
    const value = React.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 (jsxRuntime.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, }) => (jsxRuntime.jsx(PasskeyContextProviderWithBrowser, { children: children }));
const usePasskeyContext = () => {
    const context = React.useContext(PasskeyContext);
    if (context === undefined) {
        throw new Error('usage of PasskeyContext not wrapped in `PasskeyContextProvider`.');
    }
    return context;
};

exports.PasskeyContext = PasskeyContext;
exports.PasskeyContextProvider = PasskeyContextProvider;
exports.usePasskeyContext = usePasskeyContext;
