import { onMounted, onBeforeUnmount } from 'vue'

/**
 * Registers a keyboard shortcut listener for a single key.
 *
 * @param {string} key - The key to listen for (e.g. 'e', 'n', 'escape', 'enter')
 * @param {Function} handler - Callback to invoke when the key is pressed
 * @param {boolean|object} options - Legacy boolean (preventDefault) or options object:
 *   - preventDefault {boolean} - Whether to call event.preventDefault() (default: true)
 *   - ctrl {boolean} - Require Ctrl to be held (default: false)
 *   - ignoreInputs {boolean} - Skip when focus is in input/textarea/select (default: true)
 */
export function useKeyboardShortcut(key, handler, options = {}) {
  if (typeof options === 'boolean') options = { preventDefault: options }
  const { preventDefault = true, ctrl = false, ignoreInputs = true } = options

  function onKeydown(event) {
    if (event.key.toLowerCase() !== key.toLowerCase()) return
    if (ctrl && !event.ctrlKey) return

    const tag = event.target.tagName.toLowerCase()
    if (ignoreInputs && (tag === 'input' || tag === 'textarea' || tag === 'select')) return

    if (preventDefault) event.preventDefault()
    handler()
  }

  onMounted(() => window.addEventListener('keydown', onKeydown))
  onBeforeUnmount(() => window.removeEventListener('keydown', onKeydown))
}
