import { useRef, useEffect } from 'react';
import { getFocusableElements } from '../utils/index.js';

function useTrappedFocus(ref) {
    const firstFocusableRef = useRef(null);
    const lastFocusableRef = useRef(null);
    const tabHandler = (event) => {
        var _a, _b;
        const isLastFocused = document.activeElement === lastFocusableRef.current;
        const isFirstFocused = document.activeElement === firstFocusableRef.current;
        if (event.key !== 'Tab') {
            return;
        }
        if (isLastFocused && !event.shiftKey) {
            event.preventDefault();
            (_a = firstFocusableRef.current) === null || _a === void 0 ? void 0 : _a.focus();
        }
        if (isFirstFocused && event.shiftKey) {
            event.preventDefault();
            (_b = lastFocusableRef.current) === null || _b === void 0 ? void 0 : _b.focus();
        }
    };
    useEffect(() => {
        const focusableElements = getFocusableElements(ref.current);
        firstFocusableRef.current = focusableElements[0];
        lastFocusableRef.current = focusableElements[focusableElements.length - 1];
        if (firstFocusableRef.current) {
            firstFocusableRef.current.focus();
        }
    }, [ref.current]);
    useEffect(() => {
        var _a;
        (_a = ref.current) === null || _a === void 0 ? void 0 : _a.addEventListener('keydown', tabHandler);
        return () => {
            var _a;
            (_a = ref.current) === null || _a === void 0 ? void 0 : _a.removeEventListener('keydown', tabHandler);
        };
    }, [tabHandler]);
}

export { useTrappedFocus };
