import { useLingui } from '../../../../../../../../node_modules/@lingui/react/dist/index.mjs';
import React__default, { useState } from 'react';
import { EMAIL_REGEX } from '../../../../../utils/index.mjs';
import { getTranslatedError } from '../../../../../utils/getTranslatedError.mjs';
import { formatNumberToIncludeCountryCode } from '../../../../../utils/handleParsePhoneNumber.mjs';
import { readB2CInternals } from '../../../../../utils/internal.mjs';
import Button from '../../../../components/atoms/Button.mjs';
import Column from '../../../../components/atoms/Column.mjs';
import EmailInput from '../../../../components/molecules/EmailInput.mjs';
import PhoneInput, { getPhoneNumberProps } from '../../../../components/molecules/PhoneInput.mjs';
import { useEventCallback, useErrorCallback, useStytch, useConfig, useGlobalReducer, AppScreens } from '../../../GlobalContextProvider.mjs';
import { hasProduct } from '../../../utils.mjs';
import { OTPMethods, StytchEventType } from '../../../../../../../core/src/public/ui.mjs';
import { DEFAULT_OTP_EXPIRATION_MINUTES } from '../../../../../../../core/src/constants.mjs';
import { EmailSentType } from '../../../../../../../core/src/Events.mjs';

const OTPButtonText = {
    [OTPMethods.SMS]: {
        id: "button.sms",
        message: "Continue with text message"
    },
    [OTPMethods.WhatsApp]: {
        id: "button.whatsapp",
        message: "Continue with WhatsApp"
    },
    [OTPMethods.Email]: {
        id: "button.emailLogin",
        message: "Continue with email"
    }
};
const OTPEmailForm = ()=>{
    const { i18n: $__i18n, _: $__ } = useLingui();
    const onEvent = useEventCallback();
    const onError = useErrorCallback();
    const stytchClient = useStytch();
    const config = useConfig();
    const [, dispatch] = useGlobalReducer();
    const [email, setEmail] = useState('');
    const [errorMessage, setErrorMessage] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);
    const hasPasskeys = hasProduct(config.products, 'passkeys');
    const stopSubmit = (errorText)=>{
        onError({
            message: errorText
        });
        setIsSubmitting(false);
        return setErrorMessage(errorText);
    };
    const handleEmailSubmit = async (e)=>{
        e.preventDefault();
        setIsSubmitting(true);
        if (!email.match(EMAIL_REGEX)) return stopSubmit($__i18n._({
            id: "errors.invalidEmail",
            message: "Invalid email address."
        }));
        setErrorMessage('');
        setIsSubmitting(true);
        stytchClient.otps.email.loginOrCreate(email, {
            expiration_minutes: config.otpOptions?.expirationMinutes ?? DEFAULT_OTP_EXPIRATION_MINUTES,
            login_template_id: config.otpOptions?.loginTemplateId,
            signup_template_id: config.otpOptions?.signupTemplateId,
            locale: config.otpOptions?.locale
        }).then((data)=>{
            setIsSubmitting(false);
            onEvent({
                type: StytchEventType.OTPsLoginOrCreateEvent,
                data
            });
            dispatch({
                type: 'update_otp_state',
                otpState: {
                    type: OTPMethods.Email,
                    methodId: data.method_id,
                    otpDestination: email
                }
            });
            dispatch({
                type: 'transition',
                screen: AppScreens.OTPAuthenticate
            });
            readB2CInternals(stytchClient).networkClient.logEvent({
                name: 'email_sent',
                details: {
                    email: email,
                    type: EmailSentType.LoginOrCreateOTP
                }
            });
        }).catch((e)=>{
            onError(e);
            setIsSubmitting(false);
            setErrorMessage(getTranslatedError(e, $__));
        });
    };
    return /*#__PURE__*/ React__default.createElement(Column, {
        as: "form",
        onSubmit: handleEmailSubmit,
        gap: 4
    }, /*#__PURE__*/ React__default.createElement(EmailInput, {
        email: email,
        setEmail: setEmail,
        hasPasskeys: hasPasskeys,
        hideLabel: true,
        error: errorMessage
    }), /*#__PURE__*/ React__default.createElement(Button, {
        variant: "primary",
        loading: isSubmitting,
        type: "submit"
    }, $__i18n._(OTPButtonText[OTPMethods.Email])));
};
const PhoneForm = ({ method })=>{
    const { i18n: $__i18n, _: $__ } = useLingui();
    const onEvent = useEventCallback();
    const onError = useErrorCallback();
    const stytchClient = useStytch();
    const config = useConfig();
    const [, dispatch] = useGlobalReducer();
    const [phoneNumber, setPhoneNumber] = useState('');
    // eslint-disable-next-line lingui/no-unlocalized-strings
    const [country, setCountry] = useState('US');
    const [errorMessage, setErrorMessage] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);
    const hasPasskeys = hasProduct(config.products, 'passkeys');
    const stopSubmit = (errorText)=>{
        onError({
            message: errorText
        });
        setIsSubmitting(false);
        setErrorMessage(errorText);
    };
    const { parsePhoneNumber, getExampleNumber } = getPhoneNumberProps(readB2CInternals(stytchClient).clientsideServices);
    const handlePhoneSubmit = async (e)=>{
        e.preventDefault();
        const parsedNumber = await formatNumberToIncludeCountryCode({
            parsePhoneNumber,
            phoneNumber,
            country
        });
        if (!parsedNumber.isValid) {
            return stopSubmit($__i18n._({
                id: "error.invalidPhoneNumber",
                message: "Phone number format is invalid. Ensure the phone number is in the E.164 format."
            }));
        }
        setIsSubmitting(true);
        setErrorMessage('');
        stytchClient.otps[method].loginOrCreate(parsedNumber.number, {
            expiration_minutes: config.otpOptions?.expirationMinutes ?? DEFAULT_OTP_EXPIRATION_MINUTES
        }).then((data)=>{
            setIsSubmitting(false);
            onEvent({
                type: StytchEventType.OTPsLoginOrCreateEvent,
                data
            });
            dispatch({
                type: 'update_otp_state',
                otpState: {
                    type: method,
                    methodId: data.method_id,
                    otpDestination: parsedNumber.number
                }
            });
            dispatch({
                type: 'transition',
                screen: AppScreens.OTPAuthenticate
            });
        }).catch((e)=>{
            onError(e);
            setIsSubmitting(false);
            setErrorMessage(getTranslatedError(e, $__));
        });
    };
    return /*#__PURE__*/ React__default.createElement(Column, {
        as: "form",
        gap: 4,
        onSubmit: handlePhoneSubmit
    }, /*#__PURE__*/ React__default.createElement(PhoneInput, {
        phone: phoneNumber,
        setPhone: setPhoneNumber,
        country: country,
        setCountry: setCountry,
        parsePhoneNumber: parsePhoneNumber,
        getExampleNumber: getExampleNumber,
        hasPasskeys: hasPasskeys,
        error: errorMessage
    }), /*#__PURE__*/ React__default.createElement(Button, {
        variant: "primary",
        loading: isSubmitting,
        type: "submit"
    }, $__i18n._(OTPButtonText[method])));
};

export { OTPButtonText, OTPEmailForm, PhoneForm };
//# sourceMappingURL=OTPForm.mjs.map
