"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { CRM_SHORTCUTS } from "@/modules/crm/constants/portals";

/** Global keyboard shortcuts for CRM (g + key chord). */
export function useCrmKeyboardShortcuts() {
  const router = useRouter();

  useEffect(() => {
    let pending: string | null = null;
    let timer: ReturnType<typeof setTimeout>;

    const onKeyDown = (e: KeyboardEvent) => {
      if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) return;
      const key = e.key.toLowerCase();
      if (pending === "g") {
        const chord = `g ${key}`;
        const href = CRM_SHORTCUTS[chord];
        if (href) {
          e.preventDefault();
          router.push(href);
        }
        pending = null;
        return;
      }
      if (key === "g") {
        pending = "g";
        clearTimeout(timer);
        timer = setTimeout(() => {
          pending = null;
        }, 800);
      }
    };

    window.addEventListener("keydown", onKeyDown);
    return () => {
      window.removeEventListener("keydown", onKeyDown);
      clearTimeout(timer);
    };
  }, [router]);
}
