'use client'
import { __awaiter } from '../../../../_virtual/_tslib.js';
import { jsx } from 'react/jsx-runtime';
import { createContext, useContext, useState, useMemo, useCallback, useEffect } from 'react';
import { isSocialWalletConnector } from '@dynamic-labs/wallet-connector-core';
import '@dynamic-labs/iconic';
import { useViewContext } from '../ViewContext/ViewContext.js';
import { logger } from '../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import '@dynamic-labs/utils';
import '../../utils/constants/colors.js';
import '../../utils/constants/values.js';
import '@dynamic-labs/sdk-api-core';
import '../../shared/consts/index.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import { getReferencedAccount } from '../../utils/functions/getReferencedAccount/getReferencedAccount.js';
import '../../store/state/nonce/nonce.js';
import { updatePrimaryWalletId } from '../../utils/functions/updatePrimaryWalletId/updatePrimaryWalletId.js';
import '../../store/state/connectedWalletsInfo/connectedWalletsInfo.js';
import '../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../store/state/primaryWalletId/primaryWalletId.js';
import '@dynamic-labs-sdk/client/core';
import '../../client/client.js';
import '@dynamic-labs-sdk/client';
import '../../config/ApiEndpoint.js';
import '../../events/dynamicEvents.js';
import '@dynamic-labs/locale';
import { useInternalDynamicEvents } from '../../utils/hooks/events/useDynamicEvents/useDynamicEvents.js';
import '../DynamicContext/DynamicContext.js';
import '../../store/state/loadingAndLifecycle/loadingAndLifecycle.js';
import '../../store/state/authMode/authMode.js';
import { useInternalDynamicContext } from '../DynamicContext/useDynamicContext/useInternalDynamicContext/useInternalDynamicContext.js';
import { useCaptchaContext } from '../CaptchaContext/CaptchaContext.js';
import { useErrorContext } from '../ErrorContext/ErrorContext.js';
import { useVerifyWallet } from '../../utils/hooks/useVerifyWallet/useVerifyWallet.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 'bs58';
import '@dynamic-labs/types';
import '../AccessDeniedContext/AccessDeniedContext.js';
import '../AccountExistsContext/AccountExistsContext.js';
import '../LoadingContext/LoadingContext.js';
import '../WalletContext/WalletContext.js';
import '../UserWalletsContext/UserWalletsContext.js';
import '../../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 '../PasskeyContext/PasskeyContext.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';
import { useRedirectSocialHandler } from './hooks/useRedirectSocialHandler/useRedirectSocialHandler.js';

const SocialRedirectContext = 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();
    const { setErrorMessage } = useErrorContext();
    const { clearStackAndPush, pushView } = useViewContext();
    const { getCaptchaToken } = useCaptchaContext();
    const verifyWallet = 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(isSocialWalletConnector);
    const [redirectStatus, setRedirectStatus] = useState('idle');
    const [socialProvider, setSocialProvider] = 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 = useMemo(() => (wallet ? getReferencedAccount(user, wallet.id) : undefined), [user, wallet]);
    // added to make sure to reset the social provider on logout
    useInternalDynamicEvents('logout', () => setSocialProvider(undefined));
    const handleError = useCallback((message) => {
        logger.error(message);
        if (user) {
            setShowAuthFlow(false, { emitCancelAuth: true });
            setShowDynamicUserProfile(true);
        }
        else {
            setShowAuthFlow(true);
            clearStackAndPush('wallet-list');
            setErrorMessage('-1');
        }
    }, [
        user,
        setErrorMessage,
        setShowAuthFlow,
        setShowDynamicUserProfile,
        clearStackAndPush,
    ]);
    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) => __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(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({
        setSocialProvider,
    });
    return (jsx(SocialRedirectContext.Provider, { value: {
            enabledSocialProviders,
            redirectStatus,
            setSocialProvider,
            signInProvider,
            socialAccount,
            socialProvider,
            socialWalletConnector,
        }, children: children }));
};
const useSocialRedirectContext = () => {
    const context = useContext(SocialRedirectContext);
    if (context === undefined) {
        throw new Error('useSocialRedirectContext must be used within a SocialRedirectContextProvider');
    }
    return context;
};

export { SocialRedirectContext, SocialRedirectContextProvider, useSocialRedirectContext };
