'use client'
import { __awaiter } from '../../../../../../_virtual/_tslib.js';
import { useState, useCallback } from 'react';
import { DynamicError } from '@dynamic-labs/utils';
import { getDynamicClient } from '../../../../client/client.js';
import '@dynamic-labs/iconic';
import '@dynamic-labs/wallet-connector-core';
import 'react/jsx-runtime';
import { useViewContext } from '../../../ViewContext/ViewContext.js';
import { logger } from '../../../../shared/logger.js';
import '@dynamic-labs/wallet-book';
import { isSSR } from '../../../../shared/utils/functions/isSSR/isSSR.js';
import '../../../../utils/constants/colors.js';
import '../../../../utils/constants/values.js';
import '@dynamic-labs/sdk-api-core';
import { useEffectOnceCondition } from '../../../../shared/utils/hooks/useEffectOnceCondition/useEffectOnceCondition.js';
import '../../../../shared/consts/index.js';
import '@dynamic-labs/multi-wallet';
import 'react-international-phone';
import { searchSocialStorageByState, deleteSocialStorage } from '../../../../utils/functions/socialStorage/socialStorage.js';
import { getSocialSignInProviderForProviderEnum } from '../../../../utils/functions/getSocialSignInProviderForProviderEnum/getSocialSignInProviderForProviderEnum.js';
import '../../../../store/state/nonce/nonce.js';
import '@dynamic-labs-sdk/client/core';
import '@dynamic-labs-sdk/client';
import '../../../../config/ApiEndpoint.js';
import '../../../../events/dynamicEvents.js';
import '@dynamic-labs/locale';
import '../../../../store/state/dynamicContextProps/dynamicContextProps.js';
import '../../../../store/state/primaryWalletId/primaryWalletId.js';
import '../../../../store/state/connectedWalletsInfo/connectedWalletsInfo.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 '../../../CaptchaContext/CaptchaContext.js';
import '../../../ErrorContext/ErrorContext.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 'bs58';
import '@dynamic-labs/types';
import '../../SocialRedirectContext.js';
import { useSocialAuth } from '../../../../utils/hooks/useSocialAuth/useSocialAuth.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 '../../../WalletContext/WalletContext.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 { useEffectOnce } from '../../../../utils/hooks/useEffectOnce/useEffectOnce.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 '../../../LoadingContext/LoadingContext.js';
import { useWidgetContext } from '../../../../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 '../../../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.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 { usePromptAmountAndFundWithExchange } from '../../../../utils/hooks/usePromptAndFundWithExchange/usePromptAndFundWithExchange.js';
import { getDynamicRedirectData } from '../../utils/getDynamicRedirectData/getDynamicRedirectData.js';

const useRedirectSocialHandler = ({ setSocialProvider, }) => {
    const { clearStackAndPush } = useViewContext();
    const { setDynamicWidgetView } = useWidgetContext();
    const promptAmountAndFundWithExchange = usePromptAmountAndFundWithExchange();
    const [socialStorageItem, setSocialStorageItem] = useState(null);
    const { sdkHasLoaded, setShowAuthFlow, isRenderingEmbeddedAuthFlow, setShowDynamicUserProfile, redirectUrl, } = useInternalDynamicContext();
    const { completeConnection } = useSocialAuth({});
    const updateInterfaceStateForSignIn = useCallback((socialStorageItem) => {
        const socialSignInProvider = getSocialSignInProviderForProviderEnum(socialStorageItem.provider);
        setSocialProvider(socialSignInProvider);
        clearStackAndPush('social-redirect-view');
        // Only open the auth flow when the embedded widget is not rendered
        // and when this is NOT a headless sign-in flow
        const isHeadless = Boolean(socialStorageItem.isHeadlessSocialSignIn);
        if (!isRenderingEmbeddedAuthFlow && !isHeadless) {
            setShowAuthFlow(true);
        }
    }, [
        setSocialProvider,
        clearStackAndPush,
        isRenderingEmbeddedAuthFlow,
        setShowAuthFlow,
    ]);
    useEffectOnce(() => {
        var _a;
        // Do not run on server side
        if (isSSR())
            return;
        /**
         * Find the redirect data from the first available source
         */
        const { dynamicOauthCode, dynamicOauthState, dynamicOauthSsoProviderId } = (_a = getDynamicRedirectData(redirectUrl !== null && redirectUrl !== void 0 ? redirectUrl : null, window.location.href)) !== null && _a !== void 0 ? _a : {};
        if (!dynamicOauthState || !dynamicOauthCode) {
            return;
        }
        const socialStorageItem = searchSocialStorageByState(dynamicOauthState);
        if (!socialStorageItem)
            return;
        // we got back the dynamicOauthCode from the oauth provider, set it here so we can use it to sign in
        socialStorageItem.code = dynamicOauthCode;
        socialStorageItem.dynamicOauthSsoProviderId = dynamicOauthSsoProviderId;
        setSocialStorageItem(socialStorageItem);
        // Clear the state from local storage
        deleteSocialStorage(socialStorageItem.provider);
    });
    useEffectOnceCondition(() => __awaiter(void 0, void 0, void 0, function* () {
        if (!socialStorageItem)
            return;
        // Update UI to reflect the original state
        if (socialStorageItem.mode === 'signin') {
            if (getDynamicClient().user) {
                logger.error(new DynamicError('User is already logged in'));
                return;
            }
            updateInterfaceStateForSignIn(socialStorageItem);
        }
        else if (socialStorageItem.mode === 'link') {
            if (!getDynamicClient().user) {
                logger.error(new DynamicError('User not logged in'));
                return;
            }
            // Link was called from the widget, so show the profile on redirect
            if (socialStorageItem.showWidgetAfterConnection) {
                setDynamicWidgetView('profile');
                setShowDynamicUserProfile(true);
            }
        }
        yield completeConnection({
            authCode: socialStorageItem.code,
            authMode: socialStorageItem.mode,
            captchaToken: socialStorageItem.captchaToken,
            provider: socialStorageItem.provider,
            ssoProviderId: socialStorageItem.dynamicOauthSsoProviderId,
            state: socialStorageItem.state,
            verifier: socialStorageItem.codeVerifier,
        });
        if (socialStorageItem.triggerFundFromExchangeOnSuccess) {
            const payDynamicProps = socialStorageItem.payingWithDynamic;
            if (payDynamicProps) {
                promptAmountAndFundWithExchange({
                    exchange: socialStorageItem.triggerFundFromExchangeOnSuccess,
                    hideBackButton: true,
                    payingWithDynamic: payDynamicProps,
                });
            }
            else {
                promptAmountAndFundWithExchange({
                    exchange: socialStorageItem.triggerFundFromExchangeOnSuccess,
                });
            }
        }
    }), Boolean(socialStorageItem) && sdkHasLoaded);
};

export { useRedirectSocialHandler };
