import { useCallback, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { MAIN_MENU_ENTRIES } from './main-menu-config'

const LEN = MAIN_MENU_ENTRIES.length

/**
 * Keyboard-driven main menu: ArrowUp/ArrowDown move selection; Enter confirms.
 * Click/tap still works via button onClick handlers in the page.
 */
export function useHomeMainMenu() {
  const navigate = useNavigate()
  const [selectedIndex, setSelectedIndex] = useState(0)

  const move = useCallback((delta: number) => {
    setSelectedIndex((i) => (i + delta + LEN) % LEN)
  }, [])

  const confirm = useCallback(() => {
    const entry = MAIN_MENU_ENTRIES[selectedIndex]
    if (entry) navigate(entry.to)
  }, [navigate, selectedIndex])

  useEffect(() => {
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'ArrowDown') {
        e.preventDefault()
        move(1)
        return
      }
      if (e.key === 'ArrowUp') {
        e.preventDefault()
        move(-1)
        return
      }
      if (e.key === 'Enter') {
        e.preventDefault()
        confirm()
      }
    }

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

  return { selectedIndex, setSelectedIndex, confirm }
}
