"use client";

import { useEffect, useRef } from "react";
import { isTopModal, popModal, pushModal } from "./modalStack";

/**
 * Which node Tab should move to, or `null` to let the browser handle it.
 *
 * Pure, and exported, because the wrap-around is the part with edge cases: both
 * ends, a single focusable element (where Tab must stay put rather than leave),
 * and focus that has already escaped the dialog (`activeIndex === -1`), which has
 * to be pulled back in rather than ignored. Tested in
 * `tests/modalFocusTrap.test.ts`.
 */
export function wrapFocusTarget({
  nodes,
  activeIndex,
  shiftKey,
}: {
  nodes: unknown[];
  /** Index of the focused node within `nodes`, or -1 if focus has escaped. */
  activeIndex: number;
  shiftKey: boolean;
}): number | null {
  if (nodes.length === 0) return null;
  const first = 0;
  const last = nodes.length - 1;

  // Focus is outside the dialog: bring it back to the near end.
  if (activeIndex === -1) return shiftKey ? last : first;

  if (shiftKey) return activeIndex === first ? last : null;
  return activeIndex === last ? first : null;
}

/** Everything a keyboard can reach, in DOM order. */
const FOCUSABLE = [
  "a[href]",
  "button:not([disabled])",
  "input:not([disabled]):not([type='hidden'])",
  "select:not([disabled])",
  "textarea:not([disabled])",
  '[tabindex]:not([tabindex="-1"])',
].join(",");

/**
 * The keyboard half of a dialog: Escape to dismiss, Tab confined to the dialog,
 * and focus returned to whatever opened it.
 *
 * `Modal` already declared `role="dialog"` and `aria-modal="true"`, which tell
 * assistive technology that the rest of the page is inert — but nothing made it
 * so. A keyboard user could Tab straight out of any dialog into the page behind
 * and had no way to close one without finding the ✕ with a mouse. That is WCAG
 * 2.1.2 (No Keyboard Trap) read the other way round: the trap is *required* here,
 * and its absence is the defect. One hook fixes every dialog in the app.
 *
 * Escape calls the same `onClose` the ✕ does, so a caller that guards dismissal
 * while a request is in flight — `onClose={() => !isDeleting && close()}`, the
 * pattern several confirmations use — still blocks it. No caller needs changing.
 */
export function useModalKeyboard({
  open,
  onClose,
  containerRef,
}: {
  open: boolean;
  onClose?: () => void;
  containerRef: React.RefObject<HTMLDivElement | null>;
}) {
  /** Whatever had focus before the dialog opened, to give it back. */
  const previouslyFocused = useRef<HTMLElement | null>(null);
  const onCloseRef = useRef(onClose);

  // Inline close callbacks change during typing or a parent's clock tick.
  // Keep Escape current without resetting focus in an already-open dialog.
  useEffect(() => {
    onCloseRef.current = onClose;
  }, [onClose]);

  useEffect(() => {
    if (!open) return;

    // Only the top dialog answers the keyboard (see `modalStack`).
    const dialogId = pushModal();

    previouslyFocused.current =
      document.activeElement instanceof HTMLElement
        ? document.activeElement
        : null;

    // Move focus into the dialog so the next Tab stays inside it. The first
    // focusable element is preferred over the container, so a confirmation opens
    // with its Confirm button focused rather than a bare panel.
    const container = containerRef.current;
    const first = container?.querySelector<HTMLElement>(FOCUSABLE);
    (first ?? container)?.focus?.();

    const handleKeyDown = (event: KeyboardEvent) => {
      if (!isTopModal(dialogId)) return;
      if (event.key === "Escape") {
        onCloseRef.current?.();
        return;
      }
      if (event.key !== "Tab") return;

      const nodes = Array.from(
        containerRef.current?.querySelectorAll<HTMLElement>(FOCUSABLE) ?? []
      ).filter((node) => node.offsetParent !== null);
      if (nodes.length === 0) return;

      const target = wrapFocusTarget({
        nodes,
        activeIndex: nodes.indexOf(document.activeElement as HTMLElement),
        shiftKey: event.shiftKey,
      });
      if (target !== null) {
        event.preventDefault();
        nodes[target].focus();
      }
    };

    document.addEventListener("keydown", handleKeyDown);
    return () => {
      document.removeEventListener("keydown", handleKeyDown);
      popModal(dialogId);
      // Only restore if focus is still somewhere in the dialog we are closing;
      // otherwise the user has already clicked elsewhere and we would yank it.
      const active = document.activeElement;
      if (!active || active === document.body) {
        previouslyFocused.current?.focus?.();
      }
    };
  }, [open, containerRef]);
}
