import React, { useEffect, useState } from 'react'

export const useDebounce = <T>(value: T, delay: number): T => {
  const [debouncedValue, setDebouncedValue] = useState(value)

  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedValue(value)
    }, delay)

    return () => {
      clearTimeout(timer)
    }
  }, [value, delay])

  return debouncedValue
}

export const useKeyPress = (targetKey: string, callback: () => void) => {
  useEffect(() => {
    const downHandler = ({ key }: KeyboardEvent) => {
      if (key.toLowerCase() === targetKey.toLowerCase()) {
        callback()
      }
    }

    window.addEventListener('keydown', downHandler)
    return () => window.removeEventListener('keydown', downHandler)
  }, [targetKey, callback])
}

export const useResizeObserver = (
  ref: React.RefObject<HTMLElement>,
  onResize: (rect: DOMRectReadOnly) => void
) => {
  useEffect(() => {
    const element = ref.current
    if (!element) return

    const observer = new ResizeObserver((entries) => {
      for (const entry of entries) {
        onResize(entry.contentRect)
      }
    })

    observer.observe(element)

    return () => observer.disconnect()
  }, [ref, onResize])
}