import { useEffect } from 'react';

interface KeyboardShortcut {
  key: string;
  ctrlKey?: boolean;
  metaKey?: boolean;
  shiftKey?: boolean;
  handler: () => void;
}

export const useKeyboardShortcuts = (shortcuts: KeyboardShortcut[]) => {
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      // Skip if event.key is undefined or empty (some special keys)
      if (!event.key || !event.key.trim()) {
        return;
      }

      for (const shortcut of shortcuts) {
        // Validate shortcut key exists
        if (!shortcut.key || !shortcut.key.trim()) {
          continue;
        }

        const matchesKey = event.key.toLowerCase() === shortcut.key.toLowerCase();
        
        // Handle Ctrl/Cmd: if ctrlKey is true, accept either Ctrl (Windows/Linux) or Cmd (Mac)
        const isCtrlOrCmd = event.ctrlKey || event.metaKey;
        const matchesCtrl = shortcut.ctrlKey === undefined || (shortcut.ctrlKey && isCtrlOrCmd) || (!shortcut.ctrlKey && !isCtrlOrCmd);
        
        const matchesMeta = shortcut.metaKey === undefined || event.metaKey === shortcut.metaKey;
        const matchesShift = shortcut.shiftKey === undefined || event.shiftKey === shortcut.shiftKey;

        if (matchesKey && matchesCtrl && matchesMeta && matchesShift) {
          event.preventDefault();
          shortcut.handler();
          break;
        }
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [shortcuts]);
};
