import { useEffect } from "react";
import { useNavigate } from "@tanstack/react-router";

const NAV_KEYS: Record<string, string> = {
  "1": "/initiatives",
  "2": "/agents",
  "3": "/inbox",
  "4": "/settings/health",
};

interface UseGlobalKeyboardOptions {
  onCommandK: () => void;
}

export function useGlobalKeyboard({ onCommandK }: UseGlobalKeyboardOptions) {
  const navigate = useNavigate();

  useEffect(() => {
    function handleKeyDown(e: KeyboardEvent) {
      // Skip if user is typing in an input/textarea/contenteditable
      const target = e.target as HTMLElement;
      if (
        target.tagName === "INPUT" ||
        target.tagName === "TEXTAREA" ||
        target.isContentEditable
      ) {
        // But still allow Cmd+K even in inputs
        if ((e.metaKey || e.ctrlKey) && e.key === "k") {
          e.preventDefault();
          onCommandK();
        }
        return;
      }

      // Cmd+K / Ctrl+K — command palette
      if ((e.metaKey || e.ctrlKey) && e.key === "k") {
        e.preventDefault();
        onCommandK();
        return;
      }

      // Number keys 1-4 for quick nav (no modifier)
      if (!e.metaKey && !e.ctrlKey && !e.altKey) {
        const path = NAV_KEYS[e.key];
        if (path) {
          navigate({ to: path });
        }
      }
    }

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [navigate, onCommandK]);
}
