import { useEffect } from "react";

const FOCUSABLE_SELECTOR =
  'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';

export function useFocusTrap(ref: React.RefObject<HTMLElement | null>, isOpen: boolean) {
  useEffect(() => {
    if (!isOpen || !ref.current) return;
    const el = ref.current;

    // Defer initial focus to the next animation frame so the browser layout is
    // complete before we attempt to focus — prevents intermittent failures when
    // the modal DOM has just been mounted.
    const rafId = requestAnimationFrame(() => {
      const focusable = Array.from(el.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR));
      focusable[0]?.focus();
    });

    function handleKeyDown(e: KeyboardEvent) {
      if (e.key !== "Tab") return;
      // Re-query on every keydown so the list is always current — form state can
      // toggle disabled attributes and add/remove sections during a session.
      const focusable = Array.from(el.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR));
      if (focusable.length === 0) { e.preventDefault(); return; }
      const first = focusable[0];
      const last = focusable[focusable.length - 1];
      if (e.shiftKey) {
        if (document.activeElement === first) { e.preventDefault(); last?.focus(); }
      } else {
        if (document.activeElement === last) { e.preventDefault(); first?.focus(); }
      }
    }

    el.addEventListener("keydown", handleKeyDown);
    return () => {
      cancelAnimationFrame(rafId);
      el.removeEventListener("keydown", handleKeyDown);
    };
  }, [isOpen, ref]);
}
