'use client'

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

/**
 * "h" goes home, from anywhere — including /trades and /health, which have no
 * nav of their own beyond a back arrow. Mounted in the root layout rather than
 * on the dashboard (where the "s" search hotkey lives), because the whole point
 * is the pages you have to climb out of.
 *
 * Guards, matching the search hotkey's rules so the two behave alike:
 *  - never while typing: inputs, textareas, selects, contenteditable
 *  - never with a modifier, so Cmd/Ctrl+H (hide the window) still belongs to
 *    the OS and nobody loses a keystroke they meant for something else
 *  - never on auto-repeat from a held key
 *  - not on /login, where there is no home to go to yet
 */
/** The minimum of a KeyboardEvent this decision needs — so it can be tested. */
export interface HotkeyEventLike {
  key: string
  metaKey?: boolean
  ctrlKey?: boolean
  altKey?: boolean
  repeat?: boolean
  target?: { tagName?: string; isContentEditable?: boolean } | null
}

/** Exported for its own sake: the guard is the whole feature, not the router call. */
export function isHomeHotkey(e: HotkeyEventLike): boolean {
  if (e.key !== 'h' && e.key !== 'H') return false
  if (e.metaKey || e.ctrlKey || e.altKey || e.repeat) return false
  const el = e.target
  if (el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName || ''))) return false
  return true
}

export function HomeHotkey() {
  const router = useRouter()
  const pathname = usePathname()

  useEffect(() => {
    if (pathname === '/' || pathname === '/login') return

    const onKey = (e: KeyboardEvent) => {
      if (!isHomeHotkey(e as unknown as HotkeyEventLike)) return
      e.preventDefault()
      router.push('/')
    }

    document.addEventListener('keydown', onKey)
    return () => document.removeEventListener('keydown', onKey)
  }, [pathname, router])

  return null
}
