import { useMemo, useState, useEffect } from 'react';
import index from '../../../../../node_modules/swr/mutation/dist/index.mjs';
import { readB2BInternals } from '../../utils/internal.mjs';
import { useEventCallback, useErrorCallback, useStytch, useGlobalReducer, useConfig } from './GlobalContextProvider.mjs';
import { AppScreens } from './types/AppScreens.mjs';
import { ErrorType } from './types/ErrorType.mjs';
import { StytchEventType } from '../../../../core/src/public/ui.mjs';
import { AuthFlowType } from '../../../../core/src/public/b2b/ui.mjs';

const KeyToStytchEventMap = {
    'stytch.magicLinks.authenticate': StytchEventType.B2BMagicLinkAuthenticate,
    'stytch.sso.authenticate': StytchEventType.B2BSSOAuthenticate,
    'stytch.sso.discoverConnections': StytchEventType.B2BSSODiscoverConnections,
    'stytch.magicLinks.discovery.authenticate': StytchEventType.B2BMagicLinkDiscoveryAuthenticate,
    'stytch.discovery.organizations.create': StytchEventType.B2BDiscoveryOrganizationsCreate,
    'stytch.discovery.intermediateSessions.exchange': StytchEventType.B2BDiscoveryIntermediateSessionExchange,
    'stytch.magicLinks.email.loginOrSignup': StytchEventType.B2BMagicLinkEmailLoginOrSignup,
    'stytch.magicLinks.email.discovery.send': StytchEventType.B2BMagicLinkEmailDiscoverySend,
    'stytch.oauth.authenticate': StytchEventType.B2BOAuthAuthenticate,
    'stytch.oauth.discovery.authenticate': StytchEventType.B2BOAuthDiscoveryAuthenticate,
    'stytch.otps.sms.send': StytchEventType.B2BSMSOTPSend,
    'stytch.otps.sms.authenticate': StytchEventType.B2BSMSOTPAuthenticate,
    'stytch.totp.create': StytchEventType.B2BTOTPCreate,
    'stytch.totp.authenticate': StytchEventType.B2BTOTPAuthenticate,
    'stytch.recoveryCodes.recover': StytchEventType.B2BRecoveryCodesRecover,
    'stytch.impersonation.authenticate': StytchEventType.B2BImpersonationAuthenticate,
    'stytch.otps.email.authenticate': StytchEventType.B2BOTPsEmailAuthenticate,
    'stytch.otps.email.discovery.authenticate': StytchEventType.B2BOTPsEmailDiscoveryAuthenticate,
    'stytch.otps.email.discovery.send': StytchEventType.B2BOTPsEmailDiscoverySend,
    'stytch.otps.email.loginOrSignup': StytchEventType.B2BOTPsEmailLoginOrSignup,
    'stytch.organization.getBySlug': StytchEventType.B2BOrganizationsGetBySlug
};
function getStytchEventByKey(key) {
    return KeyToStytchEventMap[key];
}
const useMutate = (key, fetcher, options = {})=>{
    const onEvent = useEventCallback();
    const onError = useErrorCallback();
    const result = index(key, fetcher, {
        throwOnError: false,
        ...options,
        onSuccess: (data, key, config)=>{
            const eventType = getStytchEventByKey(key);
            if (eventType) {
                onEvent({
                    type: eventType,
                    data
                });
            }
            options.onSuccess?.(data, key, config);
        },
        onError: (error, key, config)=>{
            onError(error);
            options.onError?.(error, key, config);
        }
    });
    // Hide the error while mutating. This helps avoid the errors continuing to show after the user has clicked submit
    // and also ensures repeating errors causes <ErrorText> to re-render which is important for screenreaders to
    // re-announce them
    return result.isMutating ? {
        ...result,
        error: undefined
    } : result;
};
/**
 *
 * This hook triggers a request to retrieve the organization from the slug.
 * The hook only triggers the request if the SDK is being used in an organization flow,
 * and a slug pattern is present. The hook returns an isSearching boolean that can be used
 * to display a loading state while the search is in progress.
 */ const useExtractSlug = ()=>{
    const [state, dispatch] = useGlobalReducer();
    const [pattern, setPattern] = useState();
    const config = useConfig();
    const stytchClient = useStytch();
    const slug = config.organizationSlug ?? extractFromPattern(pattern || null, window.location.href);
    const { trigger, isMutating: isSearching } = useMutate('stytch.organization.getBySlug', (_, { arg: { slug } })=>stytchClient.organization.getBySlug({
            organization_slug: slug
        }), {
        onSuccess: ({ organization })=>{
            if (organization === null) {
                dispatch({
                    type: 'set_error_message_and_transition',
                    errorType: ErrorType.Organization,
                    canGoBack: false
                });
            } else {
                dispatch({
                    type: 'set_organization',
                    organization: {
                        ...organization
                    }
                });
            }
        }
    });
    useEffect(()=>{
        readB2BInternals(stytchClient).bootstrap.getAsync().then(({ slugPattern })=>{
            setPattern(slugPattern);
        });
    }, [
        stytchClient
    ]);
    useEffect(()=>{
        if (slug !== null && state.flowState.organization === null && state.screen === AppScreens.Main && state.flowState.type == AuthFlowType.Organization) {
            trigger({
                slug
            });
        }
    // eslint-disable-next-line react-hooks/exhaustive-deps -- SDK-1354
    }, [
        slug,
        state.flowState,
        state.screen
    ]);
    // The org is pending identification if the slug pattern has not yet been
    // determined (i.e., `undefined`) or the organization request is in progress
    const resultPending = pattern === undefined || isSearching;
    return {
        slug,
        resultPending
    };
};
const useBootstrap = ()=>{
    const stytchClient = useStytch();
    const [bootstrap, setBootstrap] = useState(readB2BInternals(stytchClient).bootstrap.getSync());
    useEffect(()=>{
        readB2BInternals(stytchClient).bootstrap.getAsync().then((data)=>{
            setBootstrap(data);
        });
    }, [
        stytchClient
    ]);
    return bootstrap;
};
const onAuthenticateSuccess = (data, dispatch, config)=>{
    dispatch({
        type: 'primary_authenticate_success',
        response: data,
        includedMfaMethods: config.mfaProductInclude
    });
};
const onDiscoveryAuthenticateSuccess = (data, dispatch)=>{
    dispatch({
        type: 'set_discovery_state',
        email: data.email_address,
        discoveredOrganizations: data.discovered_organizations
    });
};
const extractFromPattern = (pattern, href)=>{
    if (pattern === null) return null;
    const url = new URL(href);
    url.search = '';
    const currentUrl = url.toString().trim();
    const regexPattern = pattern.replace(/\./g, '\\.').replace(/\*/g, '(?:[^.]+)').replace('{{slug}}', '(.+)');
    const regex = new RegExp(regexPattern);
    const match = currentUrl.match(regex);
    if (match && match[1]) {
        return match?.[1];
    }
    return null;
};
function hasProduct(products, product) {
    return products.some((p)=>p.id === product);
}
function useProductComponents({ products, organizationProducts }, screenType) {
    return useMemo(()=>{
        const map = {};
        for (const product of [
            ...products,
            ...organizationProducts
        ]){
            if (product[screenType]) Object.assign(map, product[screenType]);
        }
        return map;
    }, [
        products,
        organizationProducts,
        screenType
    ]);
}

export { extractFromPattern, getStytchEventByKey, hasProduct, onAuthenticateSuccess, onDiscoveryAuthenticateSuccess, useBootstrap, useExtractSlug, useMutate, useProductComponents };
//# sourceMappingURL=utils.mjs.map
