import { useLingui } from '../../../../../../node_modules/@lingui/react/dist/index.mjs';
import wn from '../../../../../../node_modules/preact/compat/dist/compat.module.mjs';
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 { useErrorCallback, useStytch, useEventCallback } from '../GlobalContextProvider.mjs';
import { useStytchMember } from '../hooks/useStytchMember.mjs';
import { useBootstrap } from '../utils.mjs';
import { useState as h, useRef as _, useEffect as p } from '../../../../../../node_modules/preact/hooks/dist/hooks.module.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;
    // TODO: Consumer and B2B Bootstrap hooks should return same shape
    const bootstrap = useBootstrap();
    const idpConsentState = useIDPState({
        initialError,
        initialParams,
        oauthAuthorizeStart,
        oauthAuthorizeSubmit,
        onError,
        onEvent
    });
    return /*#__PURE__*/ wn.createElement(IDPConsent, {
        bootstrap: bootstrap,
        bootstrapNotLoaded: false,
        ...idpConsentState
    });
};
const IDPLogoutScreenImpl = ({ initialError, initialParams, navigate })=>{
    const stytchClient = useStytch();
    const onError = useErrorCallback();
    const { oauthLogoutStart } = stytchClient.idp;
    const revokeSession = ()=>stytchClient.session.revoke({
            forceClear: true
        });
    const bootstrap = useBootstrap();
    const idpLogoutState = useLogoutState({
        initialError,
        initialParams,
        oauthLogoutStart,
        revokeSession,
        onError,
        navigate
    });
    return /*#__PURE__*/ wn.createElement(IDPLogout, {
        ...idpLogoutState,
        bootstrap: bootstrap,
        bootstrapNotLoaded: false
    });
};
const IDPConsentScreen = ({ searchParams = window.location.search, navigate } = {})=>{
    // Preserve the URL Params seen on first render - even if they change later
    const [{ flow, error }] = h(parseIDPParams(searchParams));
    const { theme, displayWatermark } = usePresentation();
    let content;
    if (flow.type === 'Authorize') {
        content = /*#__PURE__*/ wn.createElement(EnsureMemberIsLoggedIn, null, /*#__PURE__*/ wn.createElement(IDPConsentScreenImpl, {
            initialError: error,
            initialParams: flow.params
        }));
    } else if (flow.type === 'Logout') {
        content = /*#__PURE__*/ wn.createElement(IDPLogoutScreenImpl, {
            initialError: error,
            initialParams: flow.params,
            navigate: navigate
        });
    }
    return /*#__PURE__*/ wn.createElement(MainContainer, {
        theme: theme,
        displayWatermark: displayWatermark
    }, content);
};
const EnsureMemberIsLoggedIn = ({ children })=>{
    const { i18n: $__i18n, _: $__ } = useLingui();
    const member = useStytchMember();
    const onError = useErrorCallback();
    const onErrorRef = _(onError);
    p(()=>{
        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] = h(false);
    const [attested, setAttested] = h(false);
    p(()=>{
        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
                // store the member to refer to its organization_id later
                const member = stytchClient.self.getSync();
                if (member) {
                    await stytchClient.session.revoke();
                }
                try {
                    await stytchClient.session.attest({
                        token,
                        profile_id,
                        organization_id: member?.organization_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
    ]);
    p(()=>{
        if (member) return;
        onErrorRef.current(new NoCurrentSessionError());
    }, [
        member
    ]);
    if (attesting) {
        return /*#__PURE__*/ wn.createElement(LoadingScreen, null);
    } else if (member) {
        return children;
    } else {
        return /*#__PURE__*/ wn.createElement(ErrorDisplay, {
            text: $__i18n._({
                id: "idpConsent.noActiveSession",
                message: "No active session detected. Please log in to continue."
            })
        });
    }
};

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