import { useEffect } from 'react';

/**
 * True when the user is typing, so a shortcut must not steal the keystroke.
 *
 * Without this, typing a company name into the search box would jump rows on
 * every "j" and try to claim on every "c".
 */
function isTyping(target: EventTarget | null): boolean {
  if (!(target instanceof HTMLElement)) return false;
  const tag = target.tagName;
  return (
    tag === 'INPUT' ||
    tag === 'TEXTAREA' ||
    tag === 'SELECT' ||
    target.isContentEditable
  );
}

interface QueueKeyboardHandlers {
  onNext: () => void;
  onPrevious: () => void;
  onOpen: () => void;
  onClaim: () => void;
  onEscape: () => void;
  onHelp: () => void;
  /** Disabled while a modal or drawer owns the keyboard. */
  enabled?: boolean;
}

/**
 * Queue keyboard navigation: j/k to move, Enter to open, c to claim.
 *
 * Officers work through a queue one row at a time all day; reaching for the
 * mouse for each is the slow path. Modifier combinations are ignored so
 * browser and OS shortcuts keep working.
 */
export function useQueueKeyboard({
  onNext,
  onPrevious,
  onOpen,
  onClaim,
  onEscape,
  onHelp,
  enabled = true,
}: QueueKeyboardHandlers): void {
  useEffect(() => {
    if (!enabled) return;

    const handler = (event: KeyboardEvent) => {
      if (isTyping(event.target)) {
        // Esc still works while typing — it is how you get out of the field.
        if (event.key === 'Escape') onEscape();
        return;
      }
      if (event.metaKey || event.ctrlKey || event.altKey) return;

      switch (event.key) {
        case 'j':
          event.preventDefault();
          onNext();
          break;
        case 'k':
          event.preventDefault();
          onPrevious();
          break;
        case 'Enter':
          event.preventDefault();
          onOpen();
          break;
        case 'c':
          event.preventDefault();
          onClaim();
          break;
        case 'Escape':
          onEscape();
          break;
        case '?':
          event.preventDefault();
          onHelp();
          break;
        default:
          break;
      }
    };

    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [enabled, onNext, onPrevious, onOpen, onClaim, onEscape, onHelp]);
}

/** Rows shown in the `?` cheatsheet. */
export const KEYBOARD_SHORTCUTS: Array<{ keys: string; labelKey: string }> = [
  { keys: '⌘K', labelKey: 'shortcuts.commandPalette' },
  { keys: 'j / k', labelKey: 'shortcuts.moveRow' },
  { keys: 'Enter', labelKey: 'shortcuts.openRow' },
  { keys: 'c', labelKey: 'shortcuts.claimRow' },
  { keys: 'Esc', labelKey: 'shortcuts.dismiss' },
  { keys: '?', labelKey: 'shortcuts.help' },
];
