import { useLingui } from '../../../../../../node_modules/@lingui/react/dist/index.mjs';
import React__default from 'react';
import { assertUnreachable } from '../../../utils/assertUnreachable.mjs';
import Button from '../../components/atoms/Button.mjs';
import ButtonColumn from '../../components/molecules/ButtonColumn.mjs';
import LastUsed from '../../components/molecules/LastUsed.mjs';
import { usePresentation, getButtonId } from '../../components/PresentationConfig.mjs';
import { useGlobalReducer, useConfig } from '../GlobalContextProvider.mjs';
import { useEffectiveAuthConfig } from '../hooks/useEffectiveAuthConfig.mjs';
import { useLastUsedAuthMethod } from '../hooks/useLastUsedAuthMethod.mjs';
import { MainScreenComponent, AppScreens } from '../types/AppScreens.mjs';
import { getButtonKey, getSsoMethodKey } from '../types/authMethodKeys.mjs';
import { useProductComponents } from '../utils.mjs';
import { arrayUtils } from '../../../../../core/src/utils/arrayUtils.mjs';
import { AuthFlowType, B2BOAuthProviders } from '../../../../../core/src/public/b2b/ui.mjs';

// OAuth helper functions
const getCustomScopesForProvider = (oauthProvider, oauthOptionsCustomScopes)=>{
    let currentCustomScopes = oauthProvider.customScopes;
    if (Object.keys(currentCustomScopes).length == 0) {
        currentCustomScopes = oauthOptionsCustomScopes;
    }
    return currentCustomScopes;
};
const getProviderParamsForProvider = (oauthProvider, oauthOptionsProviderParams, email)=>{
    let currentProviderParams = oauthProvider.providerParams;
    if (Object.keys(currentProviderParams).length == 0) {
        currentProviderParams = oauthOptionsProviderParams ?? {};
    }
    if (email && (oauthProvider.type === B2BOAuthProviders.Google || oauthProvider.type === B2BOAuthProviders.Microsoft) && !('login_hint' in currentProviderParams)) {
        currentProviderParams = {
            ...currentProviderParams,
            login_hint: email
        };
    }
    return currentProviderParams;
};
const SsoAndOAuthButtons = ({ buttons })=>{
    const { i18n: $__i18n, _: $__ } = useLingui();
    const [state, dispatch] = useGlobalReducer();
    const { oauthProviderSettings = [] } = useEffectiveAuthConfig();
    const presentation = usePresentation();
    const [lastUsedMethod, setLastUsedMethod] = useLastUsedAuthMethod();
    const config = useConfig();
    const { loginRedirectURL, signupRedirectURL, discoveryRedirectURL, customScopes, providerParams } = config.oauthOptions ?? {};
    const { B2BGoogleOneTap, OAuthB2BButton, SSOButton } = useProductComponents(config, 'ssoAndOAuthButtons');
    // Determine which buttons need to be displayed
    const isDiscoveryFlow = state.flowState.type === AuthFlowType.Discovery;
    const authButtons = buttons.flatMap((button)=>{
        if (button === MainScreenComponent.OAuthButtons) {
            return oauthProviderSettings.map((provider)=>({
                    type: 'oauth',
                    provider
                }));
        } else if (button === MainScreenComponent.SSOButtons) {
            return isDiscoveryFlow ? {
                type: 'sso-discovery'
            } : state.flowState.organization?.sso_active_connections?.map((connection)=>({
                    type: 'sso',
                    connection
                })) ?? [];
        } else {
            assertUnreachable();
        }
    });
    if (authButtons.length === 0) {
        return null;
    }
    // Reorder providers based on last used
    const [reorderedButtons, foundLastUsedOAuth] = arrayUtils.moveToFront(authButtons, (button)=>getButtonKey(button) === lastUsedMethod);
    // Helper function to create OAuth button component
    const createOAuthButton = (oauthProvider)=>{
        const providerProps = {
            customScopes: getCustomScopesForProvider(oauthProvider, customScopes),
            providerParams: getProviderParamsForProvider(oauthProvider, providerParams, state.primary.email)
        };
        if (oauthProvider.one_tap) {
            return /*#__PURE__*/ React__default.createElement(B2BGoogleOneTap, {
                key: oauthProvider.type,
                ...providerProps,
                cancelOnTapOutside: oauthProvider.cancel_on_tap_outside
            });
        }
        return /*#__PURE__*/ React__default.createElement(OAuthB2BButton, {
            key: oauthProvider.type,
            providerType: oauthProvider.type,
            loginRedirectUrl: loginRedirectURL,
            signupRedirectUrl: signupRedirectURL,
            discoveryRedirectUrl: discoveryRedirectURL,
            onSuccess: ()=>setLastUsedMethod(oauthProvider.type),
            ...providerProps
        });
    };
    return /*#__PURE__*/ React__default.createElement(ButtonColumn, null, reorderedButtons.map((button, index)=>{
        const buttonComponent = (()=>{
            switch(button.type){
                case 'oauth':
                    return createOAuthButton(button.provider);
                case 'sso':
                    return /*#__PURE__*/ React__default.createElement(SSOButton, {
                        key: button.connection.display_name,
                        connection: button.connection,
                        onStart: ()=>setLastUsedMethod(getSsoMethodKey(button.connection))
                    });
                case 'sso-discovery':
                    return /*#__PURE__*/ React__default.createElement(Button, {
                        key: "sso-discovery",
                        variant: "outline",
                        id: getButtonId('sso-discovery', presentation.options),
                        onClick: ()=>{
                            dispatch({
                                type: 'transition',
                                screen: AppScreens.SSODiscoveryEmail,
                                history: 'push'
                            });
                        }
                    }, $__i18n._({
                        id: "provider.continueWithSSO",
                        message: "Use single sign-on"
                    }));
                default:
                    assertUnreachable();
            }
        })();
        return foundLastUsedOAuth && index === 0 ? /*#__PURE__*/ React__default.createElement(LastUsed, {
            key: getButtonKey(button)
        }, buttonComponent) : buttonComponent;
    }));
};

export { SsoAndOAuthButtons, getCustomScopesForProvider, getProviderParamsForProvider };
//# sourceMappingURL=SsoAndOAuthButtons.mjs.map
