import { useLingui } from '../../../../../node_modules/@lingui/react/dist/index.mjs';
import { useState, useCallback, useEffect } from 'react';
import { extractErrorMessage } from '../../utils/extractErrorMessage.mjs';
import { extractErrorType } from '../../utils/extractErrorType.mjs';
import { useStytch, useConfig, useEventCallback, useErrorCallback, useGlobalReducer, AppScreens } from '../b2c/GlobalContextProvider.mjs';
import { hasProduct } from '../b2c/utils.mjs';
import { DEFAULT_SESSION_DURATION_MINUTES } from '../../../../core/src/constants.mjs';
import { StytchEventType } from '../../../../core/src/public/ui.mjs';

const MAX_ATTEMPTS = 5;
const usePromptPasskey = ({ canAutofill, shadowDOM })=>{
    const { i18n: $__i18n, _: $__ } = useLingui();
    const stytchClient = useStytch();
    const config = useConfig();
    const hasPasskeys = hasProduct(config.products, 'passkeys');
    const onEvent = useEventCallback();
    const onError = useErrorCallback();
    const [, dispatch] = useGlobalReducer();
    const [error, setError] = useState();
    const startPasskeyAuth = useCallback(async ({ conditionalMediation = false, abortController } = {})=>{
        try {
            const resp = await stytchClient.webauthn.authenticate({
                domain: config.passkeyOptions?.domain,
                session_duration_minutes: config.sessionOptions?.sessionDurationMinutes ?? DEFAULT_SESSION_DURATION_MINUTES,
                conditional_mediation: conditionalMediation,
                is_passkey: true,
                signal: abortController?.signal,
                disable_input_check: shadowDOM
            });
            if (!resp) {
                throw new Error('Empty response');
            }
            onEvent({
                type: StytchEventType.PasskeyAuthenticate,
                data: resp
            });
            dispatch({
                type: 'transition',
                screen: AppScreens.PasskeyConfirmation
            });
            return resp;
        } catch (e) {
            if (extractErrorType(e) === 'webauthn_registration_not_found') {
                setError($__i18n._({
                    id: "error.passkeyRegistrationNotFound",
                    message: "Passkey registration not found. You may have deleted the passkey from your account but not password manager. Please try again."
                }));
            } else if (e instanceof Error && e.name === 'StytchAPIError') {
                setError($__i18n._({
                    id: "error.passkeyUnknown",
                    message: "Unknown error occurred during passkey authentication. Please try again."
                }));
            }
            const message = extractErrorMessage(e);
            if (message) {
                onError({
                    message
                });
            }
            throw e;
        }
    }, [
        shadowDOM,
        config.passkeyOptions?.domain,
        config.sessionOptions?.sessionDurationMinutes,
        dispatch,
        onError,
        onEvent,
        stytchClient.webauthn,
        $__
    ]);
    useEffect(()=>{
        if (!hasPasskeys || !canAutofill) {
            return;
        }
        const abortController = new AbortController();
        (async ()=>{
            if (!await stytchClient.webauthn.browserSupportsAutofill()) {
                return;
            }
            for(let i = 0; i < MAX_ATTEMPTS; ++i){
                if (abortController.signal.aborted) {
                    return;
                }
                try {
                    await startPasskeyAuth({
                        abortController,
                        conditionalMediation: true
                    });
                    return;
                } catch (e) {
                    // User denied permission
                    if (e instanceof DOMException && e.name === 'NotAllowedError') {
                        return;
                    }
                // Otherwise swallow error
                }
            }
        })();
        return ()=>{
            abortController.abort();
        };
    }, [
        canAutofill,
        hasPasskeys,
        startPasskeyAuth,
        stytchClient.webauthn
    ]);
    return [
        startPasskeyAuth,
        error
    ];
};

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