import { jsx as _jsx } from "react/jsx-runtime";
import { useCallback, useEffect } from 'react';
import { useI18n, useUID } from '../../../hooks';
import HiddenText from '../../HiddenText';
/**
 * Automatically moves focus to next referenced input when current one's number of chars is equal to max-length.
 * @example const { description, descriptionID } = useAutoFocusNextInput([ref1, ref2, ref3]);
 * @param refs - array of references to relevant input elements
 * @returns An object containing an accessible description and id for that element.
 */
const useAutoFocusNextInput = (refs) => {
    const wrapListener = useCallback((nextElement) => {
        return (ev) => {
            const targetElement = ev.target;
            if (ev.inputType === 'insertText' &&
                targetElement.value.length === targetElement.maxLength) {
                nextElement?.current?.focus();
                nextElement?.current?.select();
            }
        };
    }, []);
    useEffect(() => {
        // Save current state of ref array to ensure it is the same during cleanup.
        const els = refs.flatMap(ref => ref.current ?? []);
        const callbacks = [];
        els.forEach((el, index) => {
            callbacks.push(wrapListener(refs[index + 1]));
            el.addEventListener('input', callbacks[index]);
        });
        return () => {
            els.forEach((el, index) => {
                el.removeEventListener('input', callbacks[index]);
            });
        };
    }, [refs]);
    const t = useI18n();
    const descriptionID = useUID();
    const description = (_jsx(HiddenText, { id: descriptionID, children: t('auto_focus_next_input_description') }));
    return { description, descriptionID };
};
export default useAutoFocusNextInput;
//# sourceMappingURL=useAutoFocusNextInput.js.map