import { useEffect, useState } from 'react';

/**
 * Track a CSS media query from React, for the cases where a media query in the
 * stylesheet is not enough — deciding whether to mount an element at all, not
 * just how to paint it.
 *
 * Returns false where `matchMedia` is missing (server render, jsdom), which
 * makes the cheaper branch the default everywhere it cannot be measured.
 */
export function useMediaQuery(query: string): boolean {
  const [matches, setMatches] = useState(() => {
    if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false;
    return window.matchMedia(query).matches;
  });

  useEffect(() => {
    if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return;
    const list = window.matchMedia(query);
    const update = () => setMatches(list.matches);
    update();
    list.addEventListener('change', update);
    return () => list.removeEventListener('change', update);
  }, [query]);

  return matches;
}
