import { useEffect } from 'react'

export function useKeyboardShortcuts(shortcuts = {}) {
  useEffect(() => {
    const handleKeyDown = (e) => {
      // Ignore if user is typing in an input/textarea
      if (
        e.target.tagName === 'INPUT' ||
        e.target.tagName === 'TEXTAREA' ||
        e.target.isContentEditable
      ) {
        return
      }

      // Check for modifier + key
      const key = e.key.toLowerCase()
      const ctrl = e.ctrlKey || e.metaKey
      const shift = e.shiftKey

      for (const [combination, callback] of Object.entries(shortcuts)) {
        const parts = combination.toLowerCase().split('+')
        const needsCtrl = parts.includes('ctrl') || parts.includes('cmd')
        const needsShift = parts.includes('shift')
        const keyPart = parts.find(p => !['ctrl', 'cmd', 'shift'].includes(p))

        if (
          key === keyPart &&
          needsCtrl === ctrl &&
          needsShift === shift
        ) {
          e.preventDefault()
          callback()
          return
        }
      }
    }

    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [shortcuts])
}

// Default keyboard shortcuts
export const DEFAULT_SHORTCUTS = {
  '?': () => {
    // Show help (could implement a shortcuts modal)
    console.log('Keyboard shortcuts: ? to show help')
  },
  'g d': () => window.location.hash = '#/dashboard',
  'g p': () => window.location.hash = '#/posts',
  'g c': () => window.location.hash = '#/campaigns',
  'g t': () => window.location.hash = '#/tasks',
  'g a': () => window.location.hash = '#/artefacts',
  '/': () => {
    // Focus search - implement based on your search component
    const searchInput = document.querySelector('[data-search-input]')
    if (searchInput) searchInput.focus()
  },
}
