"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "useWebOTP", {
    enumerable: true,
    get: function() {
        return useWebOTP;
    }
});
const _react = require("react");
const _utils = require("../utils");
const isOTPCredential = (credential)=>{
    return credential !== null && 'code' in credential;
};
const useWebOTP = ({ codeString, enableSMSAutoRead, disabled, codeLength, codeSetter, onFullCodeEnter })=>{
    const abortControllerRef = (0, _react.useRef)(null);
    const startWebOTPListener = (0, _react.useCallback)(async ()=>{
        if (!enableSMSAutoRead || disabled || !(0, _utils.isWebOTPSupported)()) {
            return;
        }
        if (abortControllerRef.current) {
            abortControllerRef.current.abort();
        }
        abortControllerRef.current = new AbortController();
        try {
            const otp = await navigator.credentials.get({
                otp: {
                    transport: [
                        'sms'
                    ]
                },
                signal: abortControllerRef.current.signal
            });
            if (otp && isOTPCredential(otp) && otp.code) {
                const otpCode = otp.code;
                if (otpCode.length === codeLength) {
                    const newCode = (0, _utils.getCodeValue)(codeLength, otpCode);
                    codeSetter(newCode);
                    if (onFullCodeEnter) {
                        onFullCodeEnter(otpCode);
                    }
                }
            }
        } catch (err) {
            if (err instanceof DOMException) {
                if (err.name !== 'AbortError' && err.name !== 'NotAllowedError') {
                    console.warn('Web OTP API error:', err);
                }
            } else if (err instanceof Error) {
                console.warn('Web OTP API error:', err);
            } else {
                console.warn('Unknown Web OTP API error:', err);
            }
        }
    }, [
        enableSMSAutoRead,
        disabled,
        codeLength,
        onFullCodeEnter
    ]);
    const stopWebOTPListener = (0, _react.useCallback)(()=>{
        if (abortControllerRef.current) {
            abortControllerRef.current.abort();
            abortControllerRef.current = null;
        }
    }, []);
    (0, _react.useEffect)(()=>{
        if ((0, _utils.isWebOTPSupported)() && codeString === '' && enableSMSAutoRead && !disabled) {
            startWebOTPListener();
        } else {
            stopWebOTPListener();
        }
        return ()=>{
            stopWebOTPListener();
        };
    }, [
        codeString,
        enableSMSAutoRead,
        disabled,
        startWebOTPListener,
        stopWebOTPListener
    ]);
};
