import { useEffect } from 'react'

export const isTypingTarget = (el) =>
  el.tagName === 'TEXTAREA' ||
  el.isContentEditable ||
  (el.tagName === 'INPUT' && !['checkbox', 'radio', 'button'].includes(el.type))

// Escape closes — unless focus is in a text field, where it only leaves it.
export default function useEscape(onClose) {
  useEffect(() => {
    const handler = (e) => {
      if (e.key !== 'Escape') return
      if (isTypingTarget(e.target)) {
        e.target.blur()
        return
      }
      onClose()
    }
    window.addEventListener('keydown', handler)
    return () => window.removeEventListener('keydown', handler)
  }, [onClose])
}
