import { useLingui } from '../../../../../../node_modules/@lingui/react/dist/index.mjs';
import React__default, { useEffect, useCallback } from 'react';
import Button from '../../components/atoms/Button.mjs';
import Column from '../../components/atoms/Column.mjs';
import Typography from '../../components/atoms/Typography.mjs';
import ButtonColumn from '../../components/molecules/ButtonColumn.mjs';
import { LoggingInScreen, LoadingScreen } from '../../components/molecules/Loading.mjs';
import OrganizationRow from '../components/OrganizationRow.mjs';
import { useGlobalReducer, useStytch, useConfig } from '../GlobalContextProvider.mjs';
import { AppScreens } from '../types/AppScreens.mjs';
import { ErrorType } from '../types/ErrorType.mjs';
import { useBootstrap, useMutate, onAuthenticateSuccess } from '../utils.mjs';

const isJoinViaJitType = (type)=>type === 'eligible_to_join_by_email_domain' || type === 'eligible_to_join_by_oauth_tenant';
const DiscoverNoOrganizations = ()=>{
    const [state, dispatch] = useGlobalReducer();
    const stytchClient = useStytch();
    const config = useConfig();
    const { createOrganizationEnabled } = useBootstrap();
    const { i18n: $__i18n, _: $__ } = useLingui();
    const goBack = ()=>dispatch({
            type: 'transition',
            screen: AppScreens.Main
        });
    const { trigger: stytchCreateOrganization, isMutating: isCreateLoading } = useMutate('stytch.discovery.organizations.create', ()=>stytchClient.discovery.organizations.create({
            session_duration_minutes: config.sessionOptions.sessionDurationMinutes
        }), {
        onSuccess: (data)=>{
            onAuthenticateSuccess(data, dispatch, config);
        },
        onError: (error)=>{
            dispatch({
                type: 'set_error_message_and_transition',
                errorType: error.error_type === 'action_not_allowed_email_domain_is_claimed' ? ErrorType.OrganizationDiscoveryClaimedDomain : ErrorType.Default,
                canGoBack: true
            });
        }
    });
    const shouldAutomaticallyCreateOrganization = createOrganizationEnabled && config.directCreateOrganizationForNoMembership;
    useEffect(()=>{
        if (shouldAutomaticallyCreateOrganization) {
            stytchCreateOrganization();
        }
    }, [
        shouldAutomaticallyCreateOrganization,
        stytchCreateOrganization
    ]);
    if (shouldAutomaticallyCreateOrganization || isCreateLoading) {
        return /*#__PURE__*/ React__default.createElement(LoadingScreen, null);
    }
    const email = state.formState.discoveryState.email;
    if (createOrganizationEnabled && !config.disableCreateOrganization) {
        return /*#__PURE__*/ React__default.createElement(Column, {
            gap: 6
        }, /*#__PURE__*/ React__default.createElement(Typography, {
            variant: "header"
        }, $__i18n._({
            id: "organizationDiscovery.noOrgs.create.title",
            message: "Create an organization to get started"
        })), /*#__PURE__*/ React__default.createElement(Typography, {
            variant: "body"
        }, $__i18n._({
            id: "organizationDiscovery.noOrgs.create.content",
            message: "{email} does not have an account. Think this is a mistake? Try a different email address, or contact your admin.",
            values: {
                email: email
            }
        })), /*#__PURE__*/ React__default.createElement(ButtonColumn, null, /*#__PURE__*/ React__default.createElement(Button, {
            variant: "primary",
            onClick: ()=>stytchCreateOrganization()
        }, $__i18n._({
            id: "button.createAnOrganization",
            message: "Create an organization"
        })), /*#__PURE__*/ React__default.createElement(Button, {
            variant: "ghost",
            onClick: goBack
        }, $__i18n._({
            id: "button.goBack",
            message: "Go back"
        }))));
    }
    return /*#__PURE__*/ React__default.createElement(Column, {
        gap: 6
    }, /*#__PURE__*/ React__default.createElement(Typography, {
        variant: "header"
    }, $__i18n._({
        id: "organizationDiscovery.noOrgs.title",
        message: "{email} does not belong to any organizations.",
        values: {
            email: email
        }
    })), /*#__PURE__*/ React__default.createElement(Typography, {
        variant: "body"
    }, $__i18n._({
        id: "organizationDiscovery.noOrgs.content",
        message: "Make sure your email address is correct. Otherwise, you might need to be invited by your admin."
    })), /*#__PURE__*/ React__default.createElement(Button, {
        variant: "outline",
        onClick: goBack
    }, $__i18n._({
        id: "button.tryDifferentEmailAddress",
        message: "Try a different email address"
    })));
};
const shouldAllowDirectLoginToOrganization = (organizations, config)=>{
    // If direct login is not enabled, return false
    if (!config?.status) {
        return null;
    }
    // Count active memberships
    const activeOrganizations = organizations.filter((org)=>org.membership.type === 'active_member');
    // Check for pending invites or JIT provisioning, depending on config
    const hasBlockingConditions = organizations.some((org)=>(org.membership.type === 'pending_member' || org.membership.type === 'invited_member') && !config.ignoreInvites || isJoinViaJitType(org.membership.type) && !config.ignoreJitProvisioning);
    // Allow direct login if there is exactly one active membership and no blocking conditions
    return activeOrganizations.length === 1 && !hasBlockingConditions ? activeOrganizations[0] : null;
};
const Discovery = ()=>{
    const [state, dispatch] = useGlobalReducer();
    const stytchClient = useStytch();
    const config = useConfig();
    const { i18n: $__i18n, _: $__ } = useLingui();
    const shouldDirectLoginConfigEnabled = !!config.directLoginForSingleMembership?.status;
    const { createOrganizationEnabled } = useBootstrap();
    useEffect(()=>{
        if (isExchangeInProgress) {
            // If there is already an exchange in progress, don't do anything
            return;
        }
        const directLoginOrganization = shouldAllowDirectLoginToOrganization(state.formState.discoveryState.discoveredOrganizations, config.directLoginForSingleMembership);
        if (shouldDirectLoginConfigEnabled && directLoginOrganization !== null) {
            handleDiscoveryOrganizationStart(directLoginOrganization);
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps -- SDK-1354
    }, [
        shouldDirectLoginConfigEnabled,
        state.formState.discoveryState.discoveredOrganizations,
        config.directLoginForSingleMembership
    ]);
    const handleDiscoveryOrganizationStart = (discoveredOrganization)=>{
        const organization = discoveredOrganization.organization;
        if (discoveredOrganization.primary_required) {
            const allowedAuthMethods = discoveredOrganization.primary_required.allowed_auth_methods;
            if (allowedAuthMethods && allowedAuthMethods.length === 1 && allowedAuthMethods[0] === 'sso' && organization.sso_default_connection_id) {
                startSso(organization.sso_default_connection_id);
            } else {
                dispatch({
                    type: 'select_discovered_organization',
                    discoveredOrganization
                });
            }
        } else {
            stytchDiscoveryExchange({
                organizationId: organization.organization_id
            });
        }
    };
    const startSso = useCallback((connectionId)=>{
        stytchClient.sso.start({
            connection_id: connectionId,
            login_redirect_url: config.ssoOptions?.loginRedirectURL,
            signup_redirect_url: config.ssoOptions?.signupRedirectURL
        });
    }, [
        stytchClient,
        config.ssoOptions
    ]);
    const { trigger: stytchDiscoveryExchange, isMutating: isExchangeInProgress } = useMutate(`stytch.discovery.intermediateSessions.exchange`, (_, { arg: { organizationId } })=>stytchClient.discovery.intermediateSessions.exchange({
            organization_id: organizationId,
            session_duration_minutes: config.sessionOptions.sessionDurationMinutes
        }), {
        onSuccess: (data)=>{
            onAuthenticateSuccess(data, dispatch, config);
        },
        onError: (error)=>{
            dispatch({
                type: 'set_error_message_and_transition',
                errorType: error.error_type === 'action_not_allowed_email_domain_is_claimed' ? ErrorType.OrganizationDiscoveryClaimedDomain : ErrorType.Default,
                canGoBack: true
            });
        }
    });
    const { trigger: stytchCreateOrganization, isMutating: isCreateLoading } = useMutate('stytch.discovery.organizations.create', ()=>stytchClient.discovery.organizations.create({
            session_duration_minutes: config.sessionOptions.sessionDurationMinutes
        }), {
        onSuccess: (data)=>{
            onAuthenticateSuccess(data, dispatch, config);
        },
        onError: (error)=>{
            dispatch({
                type: 'set_error_message_and_transition',
                errorType: error.error_type === 'action_not_allowed_email_domain_is_claimed' ? ErrorType.OrganizationDiscoveryClaimedDomain : ErrorType.Default,
                canGoBack: true
            });
        }
    });
    if (isExchangeInProgress) {
        return /*#__PURE__*/ React__default.createElement(LoggingInScreen, null);
    }
    if (isCreateLoading) {
        return /*#__PURE__*/ React__default.createElement(LoadingScreen, null);
    }
    if (state.formState.discoveryState.discoveredOrganizations.length === 0) {
        return /*#__PURE__*/ React__default.createElement(DiscoverNoOrganizations, null);
    }
    const organizationButtons = state.formState.discoveryState.discoveredOrganizations.map((discoveredOrganization)=>{
        const { organization, membership } = discoveredOrganization;
        let action;
        if (isJoinViaJitType(membership.type) || membership.type === 'pending_member') action = $__i18n._({
            id: "organizationDiscovery.join",
            message: "Join"
        });
        else if (membership.type === 'invited_member') action = $__i18n._({
            id: "organizationDiscovery.acceptInvite",
            message: "Accept Invite"
        });
        return /*#__PURE__*/ React__default.createElement(OrganizationRow, {
            key: organization.organization_id,
            organization: organization,
            action: action,
            onClick: ()=>handleDiscoveryOrganizationStart(discoveredOrganization)
        });
    });
    const createOrganizationButton = createOrganizationEnabled && !config.disableCreateOrganization ? /*#__PURE__*/ React__default.createElement(Button, {
        variant: "outline",
        onClick: ()=>stytchCreateOrganization()
    }, $__i18n._({
        id: "button.createAnOrganization",
        message: "Create an organization"
    })) : null;
    const goBackButton = /*#__PURE__*/ React__default.createElement(Button, {
        variant: "ghost",
        onClick: ()=>dispatch({
                type: 'transition',
                screen: AppScreens.Main
            })
    }, $__i18n._({
        id: "button.goBack",
        message: "Go back"
    }));
    return /*#__PURE__*/ React__default.createElement(Column, {
        gap: 6
    }, /*#__PURE__*/ React__default.createElement(Typography, {
        variant: "header"
    }, $__i18n._({
        id: "organizationDiscovery.title",
        message: "Select an organization to continue"
    })), createOrganizationButton ? // Display with divider if the Create Organization Button can be shown,
    // otherwise just show everything together
    /*#__PURE__*/ React__default.createElement(ButtonColumn, {
        top: organizationButtons,
        bottom: /*#__PURE__*/ React__default.createElement(React__default.Fragment, null, createOrganizationButton, goBackButton)
    }) : /*#__PURE__*/ React__default.createElement(Column, {
        gap: 4
    }, /*#__PURE__*/ React__default.createElement(ButtonColumn, null, organizationButtons), goBackButton));
};

export { Discovery };
//# sourceMappingURL=Discovery.mjs.map
