"use client";

import { useEffect } from "react";

/** Keys that move focus or work a widget: keyboard use even with a modifier
 *  held (Safari reaches buttons with Option+Tab, Alt+ArrowDown opens a select). */
const NAVIGATION_KEYS = new Set([
  "Tab",
  "ArrowUp",
  "ArrowDown",
  "ArrowLeft",
  "ArrowRight",
  "Home",
  "End",
  "PageUp",
  "PageDown",
  "Enter",
  " ",
  "Escape",
]);
/** Pressed alone, or held through a click (Shift auto-repeats on Windows). */
const MODIFIER_KEYS = new Set(["Shift", "Control", "Alt", "AltGraph", "Meta"]);

/**
 * Marks `data-input-modality` on `getTarget()` with the input the user last
 * reached for, read in styles/theme.css: the `keyboard:` variant, and the rule
 * that keeps a popup trigger unmarked when focus returns to it after a mouse
 * pick. The dashboard marks `<html>`; the WordPress bundle marks its own root,
 * so it never writes to wp-admin's document element.
 *
 * `:focus-visible` already does this for controls in the tab order, but not
 * inside Radix menus and selects: they move focus onto the hovered item by
 * script, and Chrome then matches `:focus-visible` for a mouse user too. The
 * highlighted item's outline is keyed on this mark instead, so it shows while
 * arrowing through a menu and stays off under the pointer (ACC-444).
 */
export function useInputModality(getTarget: () => HTMLElement | null): void {
  useEffect(() => {
    const root = getTarget();
    if (!root) return;
    // Written only on a change: every write restyles the page.
    const mark = (modality: "keyboard" | "pointer") => {
      if (root.dataset.inputModality !== modality) {
        root.dataset.inputModality = modality;
      }
    };
    const onKeyDown = (event: KeyboardEvent) => {
      if (MODIFIER_KEYS.has(event.key)) return;
      // A shortcut (copy, paste) says nothing about how the user moves around.
      const shortcut = event.metaKey || event.ctrlKey;
      if (shortcut && !NAVIGATION_KEYS.has(event.key)) return;
      mark("keyboard");
    };
    const onPointerDown = () => mark("pointer");
    // Capture phase: menu items stop the propagation of the keys they handle.
    document.addEventListener("keydown", onKeyDown, true);
    document.addEventListener("pointerdown", onPointerDown, true);
    return () => {
      document.removeEventListener("keydown", onKeyDown, true);
      document.removeEventListener("pointerdown", onPointerDown, true);
      delete root.dataset.inputModality;
    };
    // Bound once: the target is a fixed element for the host's lifetime.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
}
