import { useEffect, useState } from 'react';

export function useMediaQuery(query: string): boolean {
  const [matches, setMatches] = useState<boolean>(false);

  useEffect(() => {
    if (typeof window === 'undefined') return; // Ensures no window access on the server

    const matchMedia = window.matchMedia(query);

    const handleChange = () => setMatches(matchMedia.matches);
    
    // Set initial value
    handleChange();

    // Add and remove event listeners for changes
    matchMedia.addEventListener('change', handleChange);
    return () => {
      matchMedia.removeEventListener('change', handleChange);
    };
  }, [query]);

  return matches;
}
