import { useEffect } from 'react'
import type { GameAction } from './actions'
import { emit } from './inputBus'

const KEY_TO_ACTION: Partial<Record<string, GameAction>> = {
  ArrowLeft: 'LEFT',
  ArrowRight: 'RIGHT',
  ArrowUp: 'UP',
  ArrowDown: 'DOWN',
  Enter: 'BUTTON_A',
  Escape: 'BUTTON_B',
}

export function useKeyboardInput(): void {
  useEffect(() => {
    const onKeyDown = (event: KeyboardEvent) => {
      const action = KEY_TO_ACTION[event.key]
      if (!action) return
      emit(action)
    }

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