import { useLingui } from '../../../../../../../node_modules/@lingui/react/dist/index.mjs';
import React__default, { useState, useRef, useEffect } from 'react';
import { parseIDPParams } from '../../../../utils/idpHelpers.mjs';
import { ErrorDisplay } from '../../../components/molecules/ErrorScreen.mjs';
import { LoadingScreen } from '../../../components/molecules/Loading.mjs';
import MainContainer from '../../../components/molecules/MainContainer.mjs';
import { useIDPState, IDPConsent } from '../../../components/organisms/IDPConsent.mjs';
import { useTrustedAuthTokenParams } from '../../../components/organisms/IDPContextProvider.mjs';
import { useLogoutState, IDPLogout } from '../../../components/organisms/IDPLogout.mjs';
import { usePresentation } from '../../../components/PresentationConfig.mjs';
import { useStytchUser } from '../../../hooks/useStytchUser.mjs';
import { useErrorCallback, useStytch, useEventCallback } from '../../GlobalContextProvider.mjs';
import { useBootstrap } from '../../utils.mjs';
import { NoCurrentSessionError } from '../../../../../../core/src/public/SDKErrors.mjs';

const IDPConsentScreenImpl = ({ initialError, initialParams })=>{
    const stytchClient = useStytch();
    const onError = useErrorCallback();
    const onEvent = useEventCallback();
    const { oauthAuthorizeStart, oauthAuthorizeSubmit } = stytchClient.idp;
    const { bootstrap, fromCache: bootstrapNotLoaded } = useBootstrap();
    const idpConsentInfo = useIDPState({
        initialError,
        initialParams,
        oauthAuthorizeStart,
        oauthAuthorizeSubmit,
        onError,
        onEvent
    });
    return /*#__PURE__*/ React__default.createElement(IDPConsent, {
        bootstrap: bootstrap,
        bootstrapNotLoaded: bootstrapNotLoaded,
        ...idpConsentInfo
    });
};
const IDPLogoutScreenImpl = ({ initialError, initialParams, navigate })=>{
    const stytchClient = useStytch();
    const onError = useErrorCallback();
    const { oauthLogoutStart } = stytchClient.idp;
    const revokeSession = ()=>stytchClient.session.revoke({
            forceClear: true
        });
    const { bootstrap, fromCache: bootstrapNotLoaded } = useBootstrap();
    const idpLogoutState = useLogoutState({
        initialError,
        initialParams,
        oauthLogoutStart,
        revokeSession,
        onError,
        navigate
    });
    return /*#__PURE__*/ React__default.createElement(IDPLogout, {
        ...idpLogoutState,
        bootstrap: bootstrap,
        bootstrapNotLoaded: bootstrapNotLoaded
    });
};
const IDPConsentScreen = ({ searchParams = window.location.search, navigate } = {})=>{
    // Preserve the URL Params seen on first render - even if they change later
    const [{ flow, error }] = useState(parseIDPParams(searchParams));
    const { theme, displayWatermark } = usePresentation();
    let content;
    if (flow.type === 'Authorize') {
        content = /*#__PURE__*/ React__default.createElement(EnsureUserIsLoggedIn, null, /*#__PURE__*/ React__default.createElement(IDPConsentScreenImpl, {
            initialError: error,
            initialParams: flow.params
        }));
    } else if (flow.type === 'Logout') {
        content = /*#__PURE__*/ React__default.createElement(IDPLogoutScreenImpl, {
            initialError: error,
            initialParams: flow.params,
            navigate: navigate
        });
    }
    return /*#__PURE__*/ React__default.createElement(MainContainer, {
        theme: theme,
        displayWatermark: displayWatermark
    }, content);
};
const EnsureUserIsLoggedIn = ({ children })=>{
    const { i18n: $__i18n, _: $__ } = useLingui();
    const user = useStytchUser();
    const onError = useErrorCallback();
    const onErrorRef = useRef(onError);
    useEffect(()=>{
        onErrorRef.current = onError;
    }, [
        onError
    ]);
    // if a trusted auth token is provided, attest it before rendering the consent screen
    const stytchClient = useStytch();
    const authParams = useTrustedAuthTokenParams();
    const [attesting, setAttesting] = useState(false);
    const [attested, setAttested] = useState(false);
    useEffect(()=>{
        if (attesting || attested) return;
        const attestTrustedToken = async (authParams)=>{
            if (authParams?.trustedAuthToken && authParams?.tokenProfileID) {
                setAttesting(true);
                const token = authParams.trustedAuthToken;
                const profile_id = authParams.tokenProfileID;
                // revoke the current session before calling attest
                if (stytchClient.user.getSync()) {
                    await stytchClient.session.revoke({
                        forceClear: true
                    });
                }
                try {
                    await stytchClient.session.attest({
                        token,
                        profile_id,
                        session_duration_minutes: 60
                    });
                } catch (error) {
                    onErrorRef.current(error);
                } finally{
                    setAttesting(false);
                    setAttested(true);
                }
            }
            // set this either way to short-circuit the useEffect below
            setAttested(true);
        };
        attestTrustedToken(authParams);
    }, [
        authParams,
        attesting,
        attested,
        stytchClient
    ]);
    useEffect(()=>{
        if (user) return;
        onErrorRef.current(new NoCurrentSessionError());
    }, [
        user
    ]);
    if (attesting) {
        return /*#__PURE__*/ React__default.createElement(LoadingScreen, null);
    } else if (user) {
        return children;
    } else {
        return /*#__PURE__*/ React__default.createElement(ErrorDisplay, {
            text: $__i18n._({
                id: "idpConsent.noActiveSession",
                message: "No active session detected. Please log in to continue."
            })
        });
    }
};

export { IDPConsentScreen };
//# sourceMappingURL=IDPConsent.mjs.map
