import { useEffect, useRef } from 'react'
import type { RefObject } from 'react'
import type { MediaPlayerInstance } from '@vidstack/react'
import { usePreferencesStore } from '../stores/preferences-store'
import {
  buildBindingMap,
  eventToBinding,
  findShortcut,
  type ShortcutContext,
} from '../lib/player-shortcuts'

/**
 * Single window-scoped keydown listener that resolves the canonical binding
 * for the event and dispatches to the matching shortcut handler. Reads
 * user overrides from the preferences store so rebindings (#20) take
 * effect without a reload.
 */
export function usePlayerShortcuts(
  playerRef: RefObject<MediaPlayerInstance | null>,
  context: ShortcutContext,
) {
  // Pin the latest context in a ref so handlers always see fresh state
  // setters / refs without us having to re-bind the listener on every
  // render.
  const ctxRef = useRef(context)
  ctxRef.current = context

  const overrides = usePreferencesStore(s => s.keyboardShortcuts)
  const overridesRef = useRef(overrides)
  overridesRef.current = overrides

  useEffect(() => {
    function onKey(e: KeyboardEvent) {
      // Don't intercept while the user is typing into a text field
      const tag = (document.activeElement?.tagName || '').toLowerCase()
      if (tag === 'input' || tag === 'textarea' || tag === 'select') return
      if ((document.activeElement as HTMLElement | null)?.isContentEditable) return

      const map = buildBindingMap(overridesRef.current)
      const id = map.get(eventToBinding(e))
      if (!id) return
      const sc = findShortcut(id)
      if (!sc) return
      const player = playerRef.current
      if (!player) return
      e.preventDefault()
      sc.handler(player, ctxRef.current)
    }
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
    // overrides ref is read inside, no need to depend on the value here
  }, [playerRef])
}
