"use client";

import { useEffect } from "react";

export function useHotkey(
  key: string,
  callback: () => void,
  opts?: { meta?: boolean; shift?: boolean; enabled?: boolean },
) {
  useEffect(() => {
    if (opts?.enabled === false) return;

    function handler(e: KeyboardEvent) {
      const target = e.target as HTMLElement;
      if (
        target.tagName === "INPUT" ||
        target.tagName === "SELECT" ||
        target.tagName === "TEXTAREA" ||
        target.isContentEditable
      ) {
        return;
      }
      if (opts?.meta && !e.metaKey && !e.ctrlKey) return;
      if (opts?.shift && !e.shiftKey) return;
      if (e.key === key || e.key.toLowerCase() === key.toLowerCase()) {
        e.preventDefault();
        callback();
      }
    }

    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [key, callback, opts?.meta, opts?.shift, opts?.enabled]);
}
