import { useState, useEffect } from 'react';
import { getFocusables, testElForOverflow } from '../utils';
/**
 * Determines whether a content element should be keyboard-focusable by evaluating if it is
 * scrollable and contains no other focusable elements. Returns a `tabIndex` value of `0` when
 * the content is scrollable but has no focusable children, ensuring keyboard users can still
 * access the scrollable region. Returns `undefined` otherwise.
 * @example useContentTabIndex(dialogRef, dialogContentRef, [closeButtonRef])
 * @example useContentTabIndex(modalRef, modalContentRef, [closeButtonRef], [isLoading])
 * @param containerRef ref of the container element to search for focusables
 * @param contentRef ref of the content element that may need to be focusable
 * @param excludeRefs optional refs to elements that should be excluded from the focusable check (e.g., close button)
 * @param dependencies optional list of variables that will trigger re-evaluation when they are updated (e.g., loading state, content ID)
 * @returns contentTabIndex value (0 or undefined)
 */
const useContentTabIndex = (containerRef, contentRef, excludeRefs, dependencies = []) => {
    const [contentTabIndex, setContentTabIndex] = useState(undefined);
    useEffect(() => {
        if (!contentRef.current)
            return;
        const rafId = requestAnimationFrame(() => {
            const content = contentRef.current;
            if (!content) {
                setContentTabIndex(undefined);
                return;
            }
            if (content.clientHeight === 0 && content.clientWidth === 0) {
                setContentTabIndex(undefined);
                return;
            }
            const focusables = getFocusables(containerRef);
            const contentHasFocusables = focusables.some(el => content.contains(el) && el !== content && !excludeRefs?.some(ref => ref.current === el));
            const computedStyle = window.getComputedStyle(content);
            const hasOverflowYStyle = computedStyle.overflowY === 'auto' || computedStyle.overflowY === 'scroll';
            const hasOverflowXStyle = computedStyle.overflowX === 'auto' || computedStyle.overflowX === 'scroll';
            const [hasHorizontalOverflow, hasVerticalOverflow] = testElForOverflow(content);
            const isScrollable = (hasOverflowYStyle && hasVerticalOverflow) || (hasOverflowXStyle && hasHorizontalOverflow);
            const newTabIndex = !contentHasFocusables && isScrollable ? 0 : undefined;
            setContentTabIndex(newTabIndex);
        });
        return () => {
            cancelAnimationFrame(rafId);
        };
    }, dependencies);
    return contentTabIndex;
};
export default useContentTabIndex;
//# sourceMappingURL=useContentTabIndex.js.map