'use client';

import { useCallback, useSyncExternalStore } from 'react';

/**
 * Reactive media-query matcher. SSR liefert `false` (getServerSnapshot),
 * Client hydratet auf den echten Wert. Nutzt `useSyncExternalStore` —
 * empfohlenes Pattern für External Stores wie matchMedia (kein setState
 * in Effect, kein Hydration-Mismatch-Risiko).
 */
export function useMediaQuery(query: string): boolean {
  const subscribe = useCallback(
    (callback: () => void) => {
      const mql = window.matchMedia(query);
      mql.addEventListener('change', callback);
      return () => mql.removeEventListener('change', callback);
    },
    [query],
  );

  const getSnapshot = useCallback(() => window.matchMedia(query).matches, [query]);
  const getServerSnapshot = () => false;

  return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}
