import { useLingui } from '../../../../../../../node_modules/@lingui/react/dist/index.mjs';
import wn from '../../../../../../../node_modules/preact/compat/dist/compat.module.mjs';
import { getTranslatedError } from '../../../../utils/getTranslatedError.mjs';
import { formatNumber } 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 { useCountdown } from '../../../components/atoms/Countdown.mjs';
import ButtonColumn from '../../../components/molecules/ButtonColumn.mjs';
import { ResendOTPButton } from '../../../components/organisms/ResendOTPButton.mjs';
import { SentOTPEntry } from '../../../components/organisms/SentOTPEntry.mjs';
import { useEventCallback, useErrorCallback, useStytch, useConfig, useGlobalReducer, AppScreens } from '../../GlobalContextProvider.mjs';
import { useState as h, useEffect as p } from '../../../../../../../node_modules/preact/hooks/dist/hooks.module.mjs';
import { DEFAULT_SESSION_DURATION_MINUTES, DEFAULT_OTP_EXPIRATION_MINUTES } from '../../../../../../core/src/constants.mjs';
import { StytchEventType, OTPMethods } from '../../../../../../core/src/public/ui.mjs';
import { EmailSentType } from '../../../../../../core/src/Events.mjs';

const OTPAuthenticate = ({ hideBackButton = false })=>{
    const { i18n: $__i18n, _: $__ } = useLingui();
    const onEvent = useEventCallback();
    const onError = useErrorCallback();
    const stytchClient = useStytch();
    const config = useConfig();
    const [state, dispatch] = useGlobalReducer();
    const [isSubmitting, setIsSubmitting] = h(false);
    const destination = state.formState.otpState.otpDestination;
    const selectionMethod = state.formState.otpState.type;
    const [errorMessage, setErrorMessage] = h('');
    const [formattedDestination, setFormattedDestination] = h(destination);
    const calculateExpiration = ()=>Date.now() + 1000 * 60 * (config.otpOptions?.expirationMinutes ?? DEFAULT_OTP_EXPIRATION_MINUTES);
    p(()=>{
        const parseDestination = async ()=>{
            const parsePhoneNumber = (phoneNumber)=>readB2CInternals(stytchClient).clientsideServices.parsedPhoneNumber({
                    phoneNumber
                });
            const national = await formatNumber({
                parsePhoneNumber,
                phoneNumber: destination
            });
            setFormattedDestination(selectionMethod === OTPMethods.Email ? destination : national);
        };
        parseDestination();
    }, [
        selectionMethod,
        destination,
        stytchClient
    ]);
    const [expiration, setExpiration] = h(calculateExpiration);
    const resendCountdown = useCountdown();
    const resendOTP = async ()=>{
        if (selectionMethod === OTPMethods.Email) {
            readB2CInternals(stytchClient).networkClient.logEvent({
                name: 'email_try_again_clicked',
                details: {
                    email: destination,
                    type: EmailSentType.LoginOrCreateOTP
                }
            });
        }
        try {
            const data = await stytchClient.otps[selectionMethod].loginOrCreate(destination, {
                expiration_minutes: config.otpOptions?.expirationMinutes ?? DEFAULT_OTP_EXPIRATION_MINUTES
            });
            onEvent({
                type: StytchEventType.OTPsLoginOrCreateEvent,
                data
            });
            setExpiration(calculateExpiration());
            dispatch({
                type: 'update_otp_state',
                otpState: {
                    type: selectionMethod,
                    methodId: data.method_id,
                    otpDestination: destination
                }
            });
        } catch (e) {
            onError(e);
            setErrorMessage(getTranslatedError(e, $__));
            throw e;
        }
    };
    const handleSubmit = async (otp)=>{
        setIsSubmitting(true);
        stytchClient.otps.authenticate(otp, state.formState.otpState.methodId, {
            session_duration_minutes: config.sessionOptions?.sessionDurationMinutes ?? DEFAULT_SESSION_DURATION_MINUTES
        }).then((data)=>{
            onEvent({
                type: StytchEventType.OTPsAuthenticate,
                data
            });
            setIsSubmitting(false);
            dispatch({
                type: 'transition',
                screen: AppScreens.OTPConfirmation
            });
        }).catch((e)=>{
            onError(e);
            resendCountdown.clear();
            setIsSubmitting(false);
            setErrorMessage(getTranslatedError(e, $__));
        });
    };
    return /*#__PURE__*/ wn.createElement(Column, {
        gap: 6
    }, /*#__PURE__*/ wn.createElement(SentOTPEntry, {
        expiration: expiration,
        formattedDestination: formattedDestination,
        isSubmitting: isSubmitting,
        onSubmit: handleSubmit,
        errorMessage: errorMessage
    }), /*#__PURE__*/ wn.createElement(ButtonColumn, null, /*#__PURE__*/ wn.createElement(ResendOTPButton, {
        countdown: resendCountdown,
        resendOTP: resendOTP,
        isSubmitting: isSubmitting
    }), !hideBackButton && /*#__PURE__*/ wn.createElement(Button, {
        variant: "ghost",
        onClick: ()=>dispatch({
                type: 'transition',
                screen: AppScreens.Main
            })
    }, $__i18n._({
        id: "button.goBack",
        message: "Go back"
    }))));
};

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