import { useEffect, useState } from 'react'

/**
 * SSR-safe CSS media-query hook. Returns the current match boolean and
 * re-renders on viewport changes. Used by /pilot to swap the task lane
 * between side panel (≥1200px) and bottom drawer (<1200px) per Phase 7.
 */
export function useMediaQuery(query: string): boolean {
  const [matches, setMatches] = useState<boolean>(() => {
    if (typeof window === 'undefined') return false
    return window.matchMedia(query).matches
  })

  useEffect(() => {
    if (typeof window === 'undefined') return
    const mql = window.matchMedia(query)
    const handler = (e: MediaQueryListEvent) => setMatches(e.matches)
    // Sync once on mount in case state drifted between render and effect.
    setMatches(mql.matches)
    mql.addEventListener('change', handler)
    return () => mql.removeEventListener('change', handler)
  }, [query])

  return matches
}

export default useMediaQuery
