/**
 * Reactive viewport media query. SSR-safe: defaults to true (mobile) so sidebar closed on first paint.
 * @param {string} query - CSS media query, e.g. '(max-width: 767px)'
 * @returns {import('vue').Ref<boolean>} Ref that is true when the media query matches.
 */
export function useMediaQuery(query) {
  const matches = ref(true)
  const mql = ref(null)
  const handler = (e) => {
    matches.value = e.matches
  }
  onMounted(() => {
    mql.value = window.matchMedia(query)
    matches.value = mql.value.matches
    mql.value.addEventListener('change', handler)
  })
  onBeforeUnmount(() => {
    if (mql.value) mql.value.removeEventListener('change', handler)
  })
  return matches
}
