import React__default, { useState, useEffect } from 'react';
import '../../../../../_virtual/index2.mjs';
import { useSWRConfig } from '../../../../../node_modules/swr/_internal/dist/index.mjs';
import { extractErrorType } from '../../utils/extractErrorType.mjs';
import Logo from '../components/atoms/Logo.mjs';
import { ErrorScreen } from '../components/molecules/ErrorScreen.mjs';
import { LoggingInScreen } from '../components/molecules/Loading.mjs';
import MainContainer from '../components/molecules/MainContainer.mjs';
import { usePresentation } from '../components/PresentationConfig.mjs';
import { B2BGoogleOneTap } from './components/B2BOneTap.mjs';
import { useGlobalReducer, useStytch, useErrorCallback, useEventCallback, useConfig } from './GlobalContextProvider.mjs';
import { useIsOnlyFloatingOneTap } from './hooks/useIsOnlyFloatingOneTap.mjs';
import { ConfirmationScreen } from './screens/Confirmation.mjs';
import { Discovery } from './screens/Discovery.mjs';
import { MainScreen } from './screens/Main.mjs';
import { MFAEnrollmentSelectionScreen } from './screens/MFAEnrollmentSelectionScreen.mjs';
import { RecoveryCodeEntryScreen } from './screens/RecoveryCodeEntryScreen.mjs';
import { RecoveryCodeSaveScreen } from './screens/RecoveryCodeSaveScreen.mjs';
import { SMSOTPEnrollScreen } from './screens/SMSOTPEnrollScreen.mjs';
import { SMSOTPEntryScreen } from './screens/SMSOTPEntryScreen.mjs';
import { TOTPEnrollManualScreen } from './screens/TOTPEnrollManualScreen.mjs';
import { TOTPEnrollQRScreen } from './screens/TOTPEnrollQRScreen.mjs';
import { TOTPEntryScreen } from './screens/TOTPEntryScreen.mjs';
import { AppScreens } from './types/AppScreens.mjs';
import { ErrorType } from './types/ErrorType.mjs';
import { useProductComponents, useExtractSlug, onAuthenticateSuccess, onDiscoveryAuthenticateSuccess, getStytchEventByKey } from './utils.mjs';
import { AuthFlowType } from '../../../../core/src/public/b2b/ui.mjs';

const authTokenConfig = {
    discovery: {
        mutationKey: 'stytch.magicLinks.discovery.authenticate',
        onSuccess: onDiscoveryAuthenticateSuccess,
        defaultError: ErrorType.EmailMagicLink
    },
    discovery_oauth: {
        mutationKey: 'stytch.oauth.discovery.authenticate',
        onSuccess: onDiscoveryAuthenticateSuccess
    },
    oauth: {
        mutationKey: 'stytch.oauth.authenticate',
        onSuccess: onAuthenticateSuccess
    },
    sso: {
        mutationKey: 'stytch.sso.authenticate',
        onSuccess: onAuthenticateSuccess
    },
    multi_tenant_magic_links: {
        mutationKey: 'stytch.magicLinks.authenticate',
        onSuccess: onAuthenticateSuccess,
        defaultError: ErrorType.EmailMagicLink
    },
    multi_tenant_impersonation: {
        mutationKey: 'stytch.impersonation.authenticate',
        onSuccess: onAuthenticateSuccess
    }
};
const errorTypeMap = {
    ad_blocker_detected: ErrorType.AdBlockerDetected
};
const AppContainer$1 = ()=>{
    const [state, dispatch] = useGlobalReducer();
    const stytchClient = useStytch();
    const triggerError = useErrorCallback();
    const triggerEvent = useEventCallback();
    const config = useConfig();
    const { displayWatermark, theme, options } = usePresentation();
    const isOnlyFloatingOneTap = useIsOnlyFloatingOneTap();
    const currentScreen = state.screen;
    const screenComponentMap = useProductComponents(config, 'screens');
    const handleStytchAPIError = (error, defaultErrorType = ErrorType.Default)=>{
        const error_type = extractErrorType(error);
        const errorType = errorTypeMap[error_type] ?? defaultErrorType;
        dispatch({
            type: 'set_error_message_and_transition',
            errorType,
            canGoBack: false
        });
    };
    const [isTokenAuthLoading, setIsTokenAuthLoading] = useState(false);
    const { mutate } = useSWRConfig();
    const { slug, resultPending } = useExtractSlug();
    useEffect(()=>{
        // If we're in One Tap only mode, we should not run any other effects
        if (isOnlyFloatingOneTap) {
            return;
        }
        // Password reset has special handling for exchanging a magic link token
        // for a session and then using it to reset a password
        if (state.flowState.type == AuthFlowType.PasswordReset) {
            return;
        }
        const parsed = stytchClient.parseAuthenticateUrl();
        if (!parsed?.handled) {
            return;
        }
        const { mutationKey, defaultError, onSuccess } = authTokenConfig[parsed.tokenType];
        setIsTokenAuthLoading(true);
        mutate(mutationKey, stytchClient.authenticateByUrl({
            session_duration_minutes: config.sessionOptions.sessionDurationMinutes
        })).then((result)=>{
            if (!result?.handled) return; // Should not be possible
            const { data } = result;
            const event = getStytchEventByKey(mutationKey);
            if (event) {
                triggerEvent({
                    type: event,
                    data
                });
            }
            onSuccess(data, dispatch, config);
        }, (error)=>{
            triggerError(error);
            handleStytchAPIError(error, defaultError);
        }).finally(()=>setIsTokenAuthLoading(false));
    // eslint-disable-next-line react-hooks/exhaustive-deps -- SDK-1354
    }, []);
    useEffect(()=>{
        // If we're in One Tap only mode, we should not run any other effects
        if (isOnlyFloatingOneTap) {
            return;
        }
        // Skip further action if token discovery is in progress
        if (isTokenAuthLoading) {
            return;
        }
        const parsed = stytchClient.parseAuthenticateUrl();
        if (parsed?.handled) {
            return;
        }
        if (!slug && !resultPending && state.flowState.organization === null && state.screen === AppScreens.Main && state.flowState.type == AuthFlowType.Organization) {
            // No slug found (or no slug pattern)
            dispatch({
                type: 'set_error_message_and_transition',
                errorType: ErrorType.Organization,
                canGoBack: false
            });
        }
    }, [
        dispatch,
        isOnlyFloatingOneTap,
        isTokenAuthLoading,
        resultPending,
        slug,
        state.flowState.organization,
        state.flowState.type,
        state.screen,
        stytchClient,
        triggerError
    ]);
    if (isOnlyFloatingOneTap) {
        return /*#__PURE__*/ React__default.createElement(B2BGoogleOneTap, null);
    }
    if (isTokenAuthLoading) {
        return /*#__PURE__*/ React__default.createElement(MainContainer, {
            theme: theme,
            displayWatermark: false
        }, /*#__PURE__*/ React__default.createElement(LoggingInScreen, null));
    }
    let orgLogo;
    if (state.flowState.organization?.organization_logo_url) {
        const { organization_name, organization_logo_url } = state.flowState.organization;
        orgLogo = {
            url: organization_logo_url,
            alt: organization_name ?? ''
        };
    }
    const defaultScreenComponents = {
        // Main is omitted from StytchB2BProduct since it's used by everything
        [AppScreens.Main]: MainScreen,
        [AppScreens.LoggedIn]: ConfirmationScreen,
        // Discovery can be opted into dynamically via stytch_redirect_type ResetPassword flow
        // so it cannot be statically shaken away
        [AppScreens.Discovery]: Discovery,
        [AppScreens.Error]: ErrorScreen,
        // MFA products are dynamically configured depending on organization and user choice,
        // and opted into by default
        [AppScreens.MFAEnrollmentSelection]: MFAEnrollmentSelectionScreen,
        [AppScreens.SMSOTPEnrollment]: SMSOTPEnrollScreen,
        [AppScreens.SMSOTPEntry]: SMSOTPEntryScreen,
        [AppScreens.RecoveryCodeEntry]: RecoveryCodeEntryScreen,
        [AppScreens.RecoveryCodeSave]: RecoveryCodeSaveScreen,
        [AppScreens.TOTPEnrollmentQRCode]: TOTPEnrollQRScreen,
        [AppScreens.TOTPEnrollmentManual]: TOTPEnrollManualScreen,
        [AppScreens.TOTPEntry]: TOTPEntryScreen
    };
    const ScreenComponent = defaultScreenComponents[currentScreen] ?? screenComponentMap[currentScreen];
    return /*#__PURE__*/ React__default.createElement(MainContainer, {
        theme: theme,
        displayWatermark: displayWatermark
    }, /*#__PURE__*/ React__default.createElement(Logo, {
        appLogo: options.logo,
        orgLogo: orgLogo
    }), /*#__PURE__*/ React__default.createElement(ScreenComponent, null));
};

export { AppContainer$1 as default };
//# sourceMappingURL=Container.mjs.map
