import { useEffect, useState } from "react"

const BP = "(max-width: 767px)"

export function useIsMobile(): boolean {
  const [mobile, setMobile] = useState(() => window.matchMedia(BP).matches)

  useEffect(() => {
    const mql = window.matchMedia(BP)
    function onChange(e: MediaQueryListEvent) {
      setMobile(e.matches)
    }
    mql.addEventListener("change", onChange)
    return () => mql.removeEventListener("change", onChange)
  }, [])

  return mobile
}

export function MobileClass() {
  useEffect(() => {
    const root = document.documentElement
    const mql = window.matchMedia(BP)

    function sync() {
      if (mql.matches) {
        root.classList.add("mobile")
      } else {
        root.classList.remove("mobile")
      }
    }

    sync()
    mql.addEventListener("change", sync)
    return () => {
      mql.removeEventListener("change", sync)
      root.classList.remove("mobile")
    }
  }, [])

  return null
}
