'use client'

import { useEffect } from 'react'
import { usePathname, useRouter } from 'next/navigation'

/**
 * App-wide single-key shortcuts. Mounted once in the root layout.
 *
 *   s — jump to search (focus the search input on `/`, navigating there first
 *       if needed). Ignored when typing in an input/textarea/contenteditable.
 */
export function Hotkeys() {
  const router = useRouter()
  const pathname = usePathname()

  useEffect(() => {
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.ctrlKey || e.metaKey || e.altKey) return
      if (e.key !== 's' && e.key !== 'S') return

      const target = e.target as HTMLElement | null
      if (target) {
        const tag = target.tagName
        if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return
        if (target.isContentEditable) return
      }

      e.preventDefault()
      const focusInput = () => {
        const el = document.getElementById('eorg-search-input') as HTMLInputElement | null
        if (el) {
          el.focus()
          // Position cursor at end so typing appends to any existing query.
          const v = el.value
          el.setSelectionRange(v.length, v.length)
        }
      }

      if (pathname === '/') {
        focusInput()
      } else {
        router.push('/')
        // The search page mounts fresh; give it a tick to render the input.
        // (autoFocus on first mount should also fire, but this covers
        // already-cached navigations.)
        setTimeout(focusInput, 80)
      }
    }
    document.addEventListener('keydown', onKeyDown)
    return () => document.removeEventListener('keydown', onKeyDown)
  }, [pathname, router])

  return null
}
