import * as React from "react";

const MOBILE_BREAKPOINT = 768;

const QUERY = `(max-width: ${MOBILE_BREAKPOINT - 1}px)`;

export function useIsMobile(): boolean {
  return React.useSyncExternalStore(
    (subscribe) => {
      if (typeof window === "undefined") {
        return () => {};
      }
      const mql = window.matchMedia(QUERY);
      const onChange = () => subscribe();
      mql.addEventListener("change", onChange);
      return () => mql.removeEventListener("change", onChange);
    },
    () =>
      typeof window !== "undefined" ? window.matchMedia(QUERY).matches : false,
    () => false,
  );
}
