import type { KeyboardEvent } from 'react'
import { useRef } from 'react'

export const useKeyboardScroll = () => {
  const popoverRef = useRef<HTMLUListElement>(null)
  const onKeyDownScroll = (event: KeyboardEvent<HTMLInputElement>) => {
    const container = popoverRef.current
    if (event.isDefaultPrevented() || !container) return

    window.requestAnimationFrame(() => {
      const el = container.querySelector<HTMLElement>('[aria-selected=true]')
      if (!el) return

      const { clientHeight, scrollTop } = container
      const top = el.offsetTop - scrollTop
      const bottom = (scrollTop + clientHeight) - (el.offsetTop + el.clientHeight)

      if (bottom < 0) {
        container.scrollTop -= bottom
      }
      if (top < 0) {
        container.scrollTop += top
      }
    })
  }

  return { onKeyDownScroll, popoverRef }
}
