import React__default, { useState, useCallback, useEffect } from 'react';
import { readB2BInternals } from '../../../utils/internal.mjs';
import LastUsed from '../../components/molecules/LastUsed.mjs';
import { OneTapErrors } from '../../components/organisms/OneTapError.mjs';
import { useIsMounted } from '../../hooks/useIsMounted.mjs';
import { useStytch, useConfig, useGlobalReducer } from '../GlobalContextProvider.mjs';
import { useIsOnlyFloatingOneTap } from '../hooks/useIsOnlyFloatingOneTap.mjs';
import { useLastUsedAuthMethod } from '../hooks/useLastUsedAuthMethod.mjs';
import { AppScreens } from '../types/AppScreens.mjs';
import { OAuthB2BButton } from './OAuthB2BButton.mjs';
import { OneTapPositions } from '../../../../../core/src/public/ui.mjs';
import { logger } from '../../../../../core/src/utils/logger.mjs';
import { B2BOAuthProviders } from '../../../../../core/src/public/b2b/ui.mjs';

const B2BGoogleOneTap = ({ customScopes, providerParams, cancelOnTapOutside })=>{
    const stytch = useStytch();
    const config = useConfig();
    const isOnlyFloatingOneTap = useIsOnlyFloatingOneTap();
    const [oneTapError, setOneTapError] = useState();
    const isMounted = useIsMounted();
    const [state, dispatch] = useGlobalReducer();
    const [lastUsedMethod, setLastUsedMethod] = useLastUsedAuthMethod();
    /*
   * Begin One Tap Loading / Initialization Logic
   */ //
    const attemptToLoadOneTap = useCallback(async ()=>{
        const { oneTap } = readB2BInternals(stytch);
        const clientResult = await oneTap.createOneTapClient();
        if (!clientResult.success) {
            if (clientResult.reason === 'oauth_config_not_found') {
                setOneTapError(OneTapErrors.NoConfiguredOAuthClient);
            } else if (clientResult.reason === 'default_provider_not_allowed') {
                setOneTapError(OneTapErrors.DefaultProviderNotAllowed);
            } else {
                logger.error('Unable to load One Tap settings for project', clientResult);
            }
            return;
        }
        const { client } = clientResult;
        /**
     * One tap is composed of two calls, an init() call and a prompt() call
     * the init() call takes in a parent_id where one tap should be shown
     * prompt() does the actual showing. if the element does not exist,
     * we show One Tap in the upper right corner
     * if the element does exist, One Tap's lifecycle is tied to the lifecycle of said element
     * here, we call init() then prompt() in the useeffect. If the component unmounts before
     * prompt() is called, One Tap falls back to the element-does-not-exist behavior.
     * Fix: add a check for whether the component is still rendered immediately before we
     * call prompt, preventing this race condition
     */ if (!isMounted.current) {
            return;
        }
        let oneTapCallback;
        if (state.flowState.organization) {
            oneTapCallback = oneTap.createOnSuccessHandler({
                organizationId: state.flowState.organization.organization_id,
                signupRedirectUrl: config.oauthOptions?.signupRedirectURL,
                loginRedirectUrl: config.oauthOptions?.loginRedirectURL,
                onSuccess: oneTap.redirectOnSuccess,
                onError: ()=>dispatch({
                        type: 'transition',
                        screen: AppScreens.Error
                    })
            });
        } else {
            oneTapCallback = oneTap.createOnDiscoverySuccessHandler({
                discoveryRedirectUrl: config.oauthOptions?.discoveryRedirectURL,
                onSuccess: oneTap.redirectOnSuccess,
                onError: ()=>dispatch({
                        type: 'transition',
                        screen: AppScreens.Error
                    })
            });
        }
        const renderResult = await client.render({
            callback: oneTapCallback,
            style: {
                position: OneTapPositions.floating
            },
            cancelOnTapOutside
        });
        // Check if the component has become unmounted during the async OT render process
        // Kill the rest of the logic if so
        if (!isMounted.current) {
            client.cancel();
            return;
        }
        if (!renderResult.success) {
            if (renderResult.reason === 'unregistered_origin') {
                setOneTapError(OneTapErrors.OriginNotAllowedForClient);
            }
            if (renderResult.reason === 'invalid_client') {
                setOneTapError(OneTapErrors.InvalidOAuthClient);
            }
            logger.error('Unable to render One Tap prompt', renderResult);
        }
        return client;
    }, [
        stytch,
        isMounted,
        state.flowState.organization,
        config.oauthOptions?.signupRedirectURL,
        config.oauthOptions?.loginRedirectURL,
        config.oauthOptions?.discoveryRedirectURL,
        dispatch,
        cancelOnTapOutside
    ]);
    useEffect(()=>{
        let client;
        attemptToLoadOneTap().then(($client)=>client = $client).catch((err)=>{
            logger.error('Unable to render One Tap prompt', err);
        });
        return ()=>client?.cancel();
    }, [
        attemptToLoadOneTap
    ]);
    /*
   * End One Tap Loading / Initialization Logic
   */ if (isOnlyFloatingOneTap) {
        return null;
    }
    const fallbackButton = /*#__PURE__*/ React__default.createElement(OAuthB2BButton, {
        providerType: B2BOAuthProviders.Google,
        loginRedirectUrl: config.oauthOptions?.loginRedirectURL,
        signupRedirectUrl: config.oauthOptions?.signupRedirectURL,
        discoveryRedirectUrl: config.oauthOptions?.discoveryRedirectURL,
        customScopes: customScopes,
        providerParams: providerParams,
        onSuccess: ()=>setLastUsedMethod(B2BOAuthProviders.Google)
    });
    const fallbackWithLastUsed = lastUsedMethod === B2BOAuthProviders.Google ? /*#__PURE__*/ React__default.createElement(LastUsed, null, fallbackButton) : fallbackButton;
    if (oneTapError) {
        return /*#__PURE__*/ React__default.createElement(React__default.Fragment, null, (void 0), fallbackWithLastUsed);
    }
    return fallbackWithLastUsed;
};

export { B2BGoogleOneTap };
//# sourceMappingURL=B2BOneTap.mjs.map
