import { useLingui } from '../../../../../../../node_modules/@lingui/react/dist/index.mjs';
import { useState } from 'react';
import { convertMagicLinkOptions } from '../../../../utils/index.mjs';
import { getTranslatedError } from '../../../../utils/getTranslatedError.mjs';
import { errorToast } from '../../../components/atoms/Toast.mjs';
import { useStytch, useConfig, useGlobalReducer, useEventCallback, useErrorCallback } from '../../GlobalContextProvider.mjs';
import { DEFAULT_OTP_EXPIRATION_MINUTES } from '../../../../../../core/src/constants.mjs';
import { StytchEventType, OTPMethods } from '../../../../../../core/src/public/ui.mjs';

function usePasswordlessAuthenticate() {
    const { i18n: $__i18n, _: $__ } = useLingui();
    const stytchClient = useStytch();
    const { emailMagicLinksOptions, otpOptions } = useConfig();
    const [state, dispatch] = useGlobalReducer();
    const onEvent = useEventCallback();
    const onError = useErrorCallback();
    const [isSubmitting, setIsSubmitting] = useState(false);
    const email = state.formState.passwordState.email;
    const sendLink = async ()=>{
        setIsSubmitting(true);
        try {
            const data = await stytchClient.magicLinks.email.loginOrCreate(email, convertMagicLinkOptions(emailMagicLinksOptions));
            onEvent({
                type: StytchEventType.MagicLinkLoginOrCreateEvent,
                data: {
                    ...data,
                    email
                }
            });
            dispatch({
                type: 'set_magic_link_email',
                email: email
            });
        } catch (e) {
            onError(e);
            errorToast({
                message: getTranslatedError(e, $__)
            });
            throw e;
        } finally{
            setIsSubmitting(false);
        }
    };
    const sendCode = async ()=>{
        setIsSubmitting(true);
        try {
            const data = await stytchClient.otps.email.loginOrCreate(email, {
                expiration_minutes: otpOptions?.expirationMinutes ?? DEFAULT_OTP_EXPIRATION_MINUTES,
                locale: otpOptions?.locale
            });
            onEvent({
                type: StytchEventType.OTPsLoginOrCreateEvent,
                data
            });
            dispatch({
                type: 'update_otp_state',
                otpState: {
                    type: OTPMethods.Email,
                    methodId: data.method_id,
                    otpDestination: email
                }
            });
        } catch (e) {
            onError(e);
            errorToast({
                message: getTranslatedError(e, $__)
            });
            throw e;
        } finally{
            setIsSubmitting(false);
        }
    };
    return {
        sendLink,
        sendCode,
        isSubmitting
    };
}

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