import { useLayoutEffect, useState } from "react"

/** Tailwind `sm` breakpoint — viewports below are treated as xs. */
export const XS_MAX_PX = 639

const XS_MQ = `(max-width: ${XS_MAX_PX}px)`

/** Sync read for event handlers / layout (no hook delay). */
export function readXsMatches(): boolean {
  if (typeof window === "undefined") return false
  return window.matchMedia(XS_MQ).matches
}

export function useIsXs() {
  const [isXs, setIsXs] = useState(false)

  useLayoutEffect(() => {
    const mql = window.matchMedia(XS_MQ)
    const update = () => setIsXs(mql.matches)
    update()
    mql.addEventListener("change", update)
    return () => mql.removeEventListener("change", update)
  }, [])

  return isXs
}
