'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 walletConnectorCore = require('@dynamic-labs/wallet-connector-core');
require('@dynamic-labs/iconic');
var ViewContext = require('../ViewContext/ViewContext.cjs');
var logger = require('../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
require('@dynamic-labs/utils');
require('../../utils/constants/colors.cjs');
require('../../utils/constants/values.cjs');
require('@dynamic-labs/sdk-api-core');
require('../../shared/consts/index.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
var getReferencedAccount = require('../../utils/functions/getReferencedAccount/getReferencedAccount.cjs');
require('../../store/state/nonce/nonce.cjs');
var updatePrimaryWalletId = require('../../utils/functions/updatePrimaryWalletId/updatePrimaryWalletId.cjs');
require('../../store/state/connectedWalletsInfo/connectedWalletsInfo.cjs');
require('../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../store/state/primaryWalletId/primaryWalletId.cjs');
require('@dynamic-labs-sdk/client/core');
require('../../client/client.cjs');
require('@dynamic-labs-sdk/client');
require('../../config/ApiEndpoint.cjs');
require('../../events/dynamicEvents.cjs');
require('@dynamic-labs/locale');
var useDynamicEvents = require('../../utils/hooks/events/useDynamicEvents/useDynamicEvents.cjs');
require('../DynamicContext/DynamicContext.cjs');
require('../../store/state/loadingAndLifecycle/loadingAndLifecycle.cjs');
require('../../store/state/authMode/authMode.cjs');
var useInternalDynamicContext = require('../DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.cjs');
var CaptchaContext = require('../CaptchaContext/CaptchaContext.cjs');
var ErrorContext = require('../ErrorContext/ErrorContext.cjs');
var useVerifyWallet = require('../../utils/hooks/useVerifyWallet/useVerifyWallet.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');
require('bs58');
require('@dynamic-labs/types');
require('../AccessDeniedContext/AccessDeniedContext.cjs');
require('../AccountExistsContext/AccountExistsContext.cjs');
require('../LoadingContext/LoadingContext.cjs');
require('../WalletContext/WalletContext.cjs');
require('../UserWalletsContext/UserWalletsContext.cjs');
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('../PasskeyContext/PasskeyContext.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');
var useRedirectSocialHandler = require('./hooks/useRedirectSocialHandler/useRedirectSocialHandler.cjs');

const SocialRedirectContext = React.createContext(undefined);
const SocialRedirectContextProvider = ({ children, }) => {
    var _a, _b, _c, _d;
    const { setShowAuthFlow, walletConnectorOptions, setSelectedWalletConnectorKey, walletUiUtils, displaySiweStatement, environmentId, projectSettings, setIsSingleWalletAccount, setShowDynamicUserProfile, secondaryWallets, sdkHasLoaded, user, connectWallet, primaryWallet, socialProvidersFilter = (providers) => providers, } = useInternalDynamicContext.useInternalDynamicContext();
    const { setErrorMessage } = ErrorContext.useErrorContext();
    const { clearStackAndPush, pushView } = ViewContext.useViewContext();
    const { getCaptchaToken } = CaptchaContext.useCaptchaContext();
    const verifyWallet = useVerifyWallet.useVerifyWallet({
        displaySiweStatement,
        environmentId,
        projectSettings,
        setIsSingleWalletAccount,
    });
    const signInProvider = (_a = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.socialSignIn) === null || _a === void 0 ? void 0 : _a.signInProvider;
    const enabledSocialProvidersInDb = (_c = (_b = projectSettings === null || projectSettings === void 0 ? void 0 : projectSettings.sdk.socialSignIn) === null || _b === void 0 ? void 0 : _b.providers) !== null && _c !== void 0 ? _c : [];
    const enabledSocialProviders = (_d = socialProvidersFilter(enabledSocialProvidersInDb
        .filter((provider) => provider.enabled)
        .map((provider) => provider.provider))) !== null && _d !== void 0 ? _d : [];
    const socialWalletConnector = walletConnectorOptions
        .map(({ walletConnector }) => walletConnector)
        .find(walletConnectorCore.isSocialWalletConnector);
    const [redirectStatus, setRedirectStatus] = React.useState('idle');
    const [socialProvider, setSocialProvider] = React.useState();
    const userWallets = primaryWallet
        ? [primaryWallet, ...secondaryWallets]
        : secondaryWallets;
    const wallet = userWallets.find((wallet) => wallet.connector.key === (socialWalletConnector === null || socialWalletConnector === void 0 ? void 0 : socialWalletConnector.key));
    const socialAccount = React.useMemo(() => (wallet ? getReferencedAccount.getReferencedAccount(user, wallet.id) : undefined), [user, wallet]);
    // added to make sure to reset the social provider on logout
    useDynamicEvents.useInternalDynamicEvents('logout', () => setSocialProvider(undefined));
    const handleError = React.useCallback((message) => {
        logger.logger.error(message);
        if (user) {
            setShowAuthFlow(false, { emitCancelAuth: true });
            setShowDynamicUserProfile(true);
        }
        else {
            setShowAuthFlow(true);
            clearStackAndPush('wallet-list');
            setErrorMessage('-1');
        }
    }, [
        user,
        setErrorMessage,
        setShowAuthFlow,
        setShowDynamicUserProfile,
        clearStackAndPush,
    ]);
    React.useEffect(() => {
        var _a, _b;
        if (!projectSettings || !socialWalletConnector || !sdkHasLoaded) {
            // TODO: use PlatformService
            const params = new URLSearchParams(window.location.search);
            if (params.has('magic_oauth_request_id')) {
                clearStackAndPush('social-redirect-view');
                setShowAuthFlow(true);
            }
            return;
        }
        // TODO: use PlatformService
        const params = new URLSearchParams(window.location.search);
        if (params.has('error') && params.has('provider')) {
            const errorDescription = params.get('error_description');
            handleError(errorDescription !== null && errorDescription !== void 0 ? errorDescription : 'Unknown error');
            // calling this to clear the relevant query params
            (_a = socialWalletConnector.getSession) === null || _a === void 0 ? void 0 : _a.call(socialWalletConnector);
            return;
        }
        if (params.has('magic_oauth_request_id')) {
            const providerFromParams = params.get('provider');
            setSocialProvider(providerFromParams);
            setRedirectStatus('loading');
            clearStackAndPush('social-redirect-view');
            setShowAuthFlow(true);
            if (!user) {
                setSelectedWalletConnectorKey(socialWalletConnector.key);
            }
            (_b = socialWalletConnector
                .getSession) === null || _b === void 0 ? void 0 : _b.call(socialWalletConnector).then((session) => _tslib.__awaiter(void 0, void 0, void 0, function* () {
                /**
                 * If the user is already authenticated, that means that they are in the process
                 * of setting their social wallet as their primary wallet. At this point, they
                 * have successfully re-authenticated with the social provider. We can now finish
                 * the setPrimaryWallet flow
                 */
                if (user) {
                    if (!socialAccount) {
                        throw new Error('Social account not found');
                    }
                    /**
                     * consider google: a user may have multiple google accounts.
                     * we need to make sure they connected with the same google account
                     * that they originally used to authenticate
                     *
                     * there are two known scenarios that we enter this branch:
                     * 1. the user is reconnected a social wallet:
                     *   a. the user signed in with social
                     *   b. the user then linked another wallet (for ex: metamask)
                     *   c. the user signed out
                     *   d. the user signed in with metamask
                     *   e. the user selects their social wallet as their primary wallet
                     *   f. we need to reconnect the social wallet and put the user in the social oauth redirect flow
                     *
                     * 2. for an unknown reason, the magic search params get put back into the url and this component rerenders,
                     *    causing us to think the user is reconnecting.
                     *    see: https://dynamiclabsgroup.slack.com/archives/C0473MNEP0T/p1697503460754999
                     */
                    if (socialAccount.oauthAccountId === session.oauthId) {
                        if ((wallet === null || wallet === void 0 ? void 0 : wallet.id) !== (primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.id)) {
                            // justification: socialAccount is defined if and only if wallet is also defined
                            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
                            updatePrimaryWalletId.updatePrimaryWalletId(wallet.id);
                            setShowAuthFlow(false);
                            setShowDynamicUserProfile(true);
                        }
                    }
                    else {
                        yield socialWalletConnector.endSession();
                        pushView('social-wrong-account');
                    }
                }
                else {
                    yield connectWallet(socialWalletConnector);
                    const address = yield socialWalletConnector.getAddress();
                    walletUiUtils.disabledConfirmationOnce();
                    yield verifyWallet({
                        captchaToken: getCaptchaToken(),
                        oauth: {
                            accessToken: session.accessToken,
                            didToken: session.didToken,
                            provider: providerFromParams,
                        },
                        /**
                         * justification: if the user just successfully authenticated their social,
                         * then the social connector must return an address
                         */
                        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
                        publicWalletAddress: address,
                        walletConnector: socialWalletConnector,
                    });
                }
                setSocialProvider(undefined);
                setRedirectStatus('success');
            })).catch((error) => {
                setSocialProvider(undefined);
                setRedirectStatus('error');
                handleError(error);
            });
        }
    }, [
        socialAccount,
        user,
        projectSettings,
        sdkHasLoaded,
        secondaryWallets,
        setSelectedWalletConnectorKey,
        setShowAuthFlow,
        setShowDynamicUserProfile,
        pushView,
        socialWalletConnector,
        verifyWallet,
        walletUiUtils,
        wallet,
        handleError,
        connectWallet,
        primaryWallet === null || primaryWallet === void 0 ? void 0 : primaryWallet.id,
        getCaptchaToken,
        clearStackAndPush,
    ]);
    useRedirectSocialHandler.useRedirectSocialHandler({
        setSocialProvider,
    });
    return (jsxRuntime.jsx(SocialRedirectContext.Provider, { value: {
            enabledSocialProviders,
            redirectStatus,
            setSocialProvider,
            signInProvider,
            socialAccount,
            socialProvider,
            socialWalletConnector,
        }, children: children }));
};
const useSocialRedirectContext = () => {
    const context = React.useContext(SocialRedirectContext);
    if (context === undefined) {
        throw new Error('useSocialRedirectContext must be used within a SocialRedirectContextProvider');
    }
    return context;
};

exports.SocialRedirectContext = SocialRedirectContext;
exports.SocialRedirectContextProvider = SocialRedirectContextProvider;
exports.useSocialRedirectContext = useSocialRedirectContext;
