import { useEffect } from 'react';
export function getFocusableElements(container) {
  const focusableElementSelectors = 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"]):not([disabled]), [contenteditable="true"]';
  return Array.from(container?.querySelectorAll(focusableElementSelectors) || []).filter(el => el.offsetParent !== null); // Only visible elements
}
export function useFocusTrap(ref) {
  useEffect(() => {
    const handleFocus = e => {
      if (e.key !== 'Tab') {
        return;
      }
      const focusableEl = getFocusableElements(ref.current);
      if (!focusableEl || focusableEl.length === 0) {
        return;
      }
      const firstFocusableElement = focusableEl[0];
      const lastFocusableElement = focusableEl[focusableEl.length - 1];
      if (e.shiftKey) {
        if (document.activeElement === firstFocusableElement) {
          lastFocusableElement.focus();
          e.preventDefault();
        }
      } else if (document.activeElement === lastFocusableElement) {
        firstFocusableElement.focus();
        e.preventDefault();
      }
    };
    const currElement = ref.current;
    currElement?.addEventListener('keydown', handleFocus);
    return () => {
      currElement?.removeEventListener('keydown', handleFocus);
    };
  }, [ref.current]);
}