import * as React from "react"

const MOBILE_BREAKPOINT = 768

export function useIsMobile() {
  const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)

  React.useEffect(() => {
    const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
    const onChange = () => {
      setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
    }
    mql.addEventListener("change", onChange)
    setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
    return () => mql.removeEventListener("change", onChange)
  }, [])

  return !!isMobile
}

export function useIsTouchDevice() {
  const [isTouch, setIsTouch] = React.useState<boolean | undefined>(undefined)

  React.useEffect(() => {
    const checkTouch = () => {
      const hasTouch = 'ontouchstart' in window || 
                      navigator.maxTouchPoints > 0 ||
                      (navigator.userAgent.includes('CrOS') && 'ontouchstart' in window) ||
                      window.matchMedia('(pointer: coarse)').matches ||
                      !window.matchMedia('(hover: hover)').matches
      
      setIsTouch(hasTouch)
    }
    
    checkTouch()
    
    const mediaQuery = window.matchMedia('(pointer: coarse)')
    const hoverQuery = window.matchMedia('(hover: hover)')
    
    const handleChange = () => checkTouch()
    
    mediaQuery.addEventListener('change', handleChange)
    hoverQuery.addEventListener('change', handleChange)
    
    return () => {
      mediaQuery.removeEventListener('change', handleChange)
      hoverQuery.removeEventListener('change', handleChange)
    }
  }, [])

  return !!isTouch
}
