'use client'
'use strict';

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

var _tslib = require('../../../../../../_virtual/_tslib.cjs');
var React = require('react');
var utils = require('@dynamic-labs/utils');
var client = require('../../../../client/client.cjs');
require('@dynamic-labs/iconic');
require('@dynamic-labs/wallet-connector-core');
require('react/jsx-runtime');
var ViewContext = require('../../../ViewContext/ViewContext.cjs');
var logger = require('../../../../shared/logger.cjs');
require('@dynamic-labs/wallet-book');
var isSSR = require('../../../../shared/utils/functions/isSSR/isSSR.cjs');
require('../../../../utils/constants/colors.cjs');
require('../../../../utils/constants/values.cjs');
require('@dynamic-labs/sdk-api-core');
var useEffectOnceCondition = require('../../../../shared/utils/hooks/useEffectOnceCondition/useEffectOnceCondition.cjs');
require('../../../../shared/consts/index.cjs');
require('@dynamic-labs/multi-wallet');
require('react-international-phone');
var socialStorage = require('../../../../utils/functions/socialStorage/socialStorage.cjs');
var getSocialSignInProviderForProviderEnum = require('../../../../utils/functions/getSocialSignInProviderForProviderEnum/getSocialSignInProviderForProviderEnum.cjs');
require('../../../../store/state/nonce/nonce.cjs');
require('@dynamic-labs-sdk/client/core');
require('@dynamic-labs-sdk/client');
require('../../../../config/ApiEndpoint.cjs');
require('../../../../events/dynamicEvents.cjs');
require('@dynamic-labs/locale');
require('../../../../store/state/dynamicContextProps/dynamicContextProps.cjs');
require('../../../../store/state/primaryWalletId/primaryWalletId.cjs');
require('../../../../store/state/connectedWalletsInfo/connectedWalletsInfo.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');
require('../../../CaptchaContext/CaptchaContext.cjs');
require('../../../ErrorContext/ErrorContext.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');
require('bs58');
require('@dynamic-labs/types');
require('../../SocialRedirectContext.cjs');
var useSocialAuth = require('../../../../utils/hooks/useSocialAuth/useSocialAuth.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('../../../WalletContext/WalletContext.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');
var useEffectOnce = require('../../../../utils/hooks/useEffectOnce/useEffectOnce.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('../../../LoadingContext/LoadingContext.cjs');
var DynamicWidgetContext = 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('../../../../utils/hooks/useEmbeddedWallet/useSecureEnclaveEmbeddedWallet/constants.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 usePromptAndFundWithExchange = require('../../../../utils/hooks/usePromptAndFundWithExchange/usePromptAndFundWithExchange.cjs');
var getDynamicRedirectData = require('../../utils/getDynamicRedirectData/getDynamicRedirectData.cjs');

const useRedirectSocialHandler = ({ setSocialProvider, }) => {
    const { clearStackAndPush } = ViewContext.useViewContext();
    const { setDynamicWidgetView } = DynamicWidgetContext.useWidgetContext();
    const promptAmountAndFundWithExchange = usePromptAndFundWithExchange.usePromptAmountAndFundWithExchange();
    const [socialStorageItem, setSocialStorageItem] = React.useState(null);
    const { sdkHasLoaded, setShowAuthFlow, isRenderingEmbeddedAuthFlow, setShowDynamicUserProfile, redirectUrl, } = useInternalDynamicContext.useInternalDynamicContext();
    const { completeConnection } = useSocialAuth.useSocialAuth({});
    const updateInterfaceStateForSignIn = React.useCallback((socialStorageItem) => {
        const socialSignInProvider = getSocialSignInProviderForProviderEnum.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.useEffectOnce(() => {
        var _a;
        // Do not run on server side
        if (isSSR.isSSR())
            return;
        /**
         * Find the redirect data from the first available source
         */
        const { dynamicOauthCode, dynamicOauthState, dynamicOauthSsoProviderId } = (_a = getDynamicRedirectData.getDynamicRedirectData(redirectUrl !== null && redirectUrl !== void 0 ? redirectUrl : null, window.location.href)) !== null && _a !== void 0 ? _a : {};
        if (!dynamicOauthState || !dynamicOauthCode) {
            return;
        }
        const socialStorageItem = socialStorage.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
        socialStorage.deleteSocialStorage(socialStorageItem.provider);
    });
    useEffectOnceCondition.useEffectOnceCondition(() => _tslib.__awaiter(void 0, void 0, void 0, function* () {
        if (!socialStorageItem)
            return;
        // Update UI to reflect the original state
        if (socialStorageItem.mode === 'signin') {
            if (client.getDynamicClient().user) {
                logger.logger.error(new utils.DynamicError('User is already logged in'));
                return;
            }
            updateInterfaceStateForSignIn(socialStorageItem);
        }
        else if (socialStorageItem.mode === 'link') {
            if (!client.getDynamicClient().user) {
                logger.logger.error(new utils.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);
};

exports.useRedirectSocialHandler = useRedirectSocialHandler;
