import { ErrorMonitor } from '@wix/bex-core';

type MatchMediaChangeListener = ({ matches }: { matches: boolean }) => void;

export function registerMatchMedia({
  matchMedia,
  matchMediaChangeListener,
  errorMonitor,
}: {
  matchMedia: MediaQueryList;
  matchMediaChangeListener: MatchMediaChangeListener;
  errorMonitor: ErrorMonitor;
}) {
  try {
    if (typeof matchMedia.addEventListener === 'function') {
      matchMedia.addEventListener('change', matchMediaChangeListener);
    } else if (typeof matchMedia.addListener === 'function') {
      matchMedia.addListener(matchMediaChangeListener);
    } else {
      throw new Error(
        'window.matchMedia does not support `addEventListener` or `addListener`',
      );
    }
  } catch (e) {
    errorMonitor.captureException(e);
  }

  return () =>
    matchMedia.removeEventListener('change', matchMediaChangeListener);
}
