// public/components/responsive.jsx
//
// Responsive primitives — share-by-window hooks for breakpoint detection.
// Load this BEFORE any other JSX bundle so window.useIsMobile /
// window.useIsTablet / window.BREAKPOINTS are available everywhere.
//
// Breakpoints (px):  mobile ≤ 768   tablet 769–1023   desktop ≥ 1024
//   useIsMobile()  → true when viewport ≤ 768px
//   useIsTablet()  → true when viewport is 769–1023px
//   desktop = both hooks false (the layout default)
//
// Usage inside a JSX component:
//   const isMobile = useIsMobile();
//   return <div style={{ padding: isMobile ? 16 : 64 }}>…</div>;

const BREAKPOINTS = { mobile: 768, tablet: 1024 };

const useMediaQuery = (query) => {
  // Default to `false` on the server — components render desktop-first and
  // re-flow on the client after the effect runs. This matches Astro's
  // server-render then hydrate flow without flashing the mobile layout on
  // large screens.
  const getInitial = () =>
    typeof window !== "undefined" && typeof window.matchMedia === "function"
      ? window.matchMedia(query).matches
      : false;

  const [matches, setMatches] = React.useState(getInitial);

  React.useEffect(() => {
    if (typeof window === "undefined" || typeof window.matchMedia !== "function") return;
    const mql = window.matchMedia(query);
    // Re-sync in case the initial render guessed wrong (e.g. SSR fallback)
    setMatches(mql.matches);
    const handler = (e) => setMatches(e.matches);
    if (mql.addEventListener) {
      mql.addEventListener("change", handler);
      return () => mql.removeEventListener("change", handler);
    }
    // Safari < 14
    mql.addListener(handler);
    return () => mql.removeListener(handler);
  }, [query]);

  return matches;
};

const useIsMobile = () =>
  useMediaQuery(`(max-width: ${BREAKPOINTS.mobile}px)`);

const useIsTablet = () =>
  useMediaQuery(
    `(min-width: ${BREAKPOINTS.mobile + 1}px) and (max-width: ${BREAKPOINTS.tablet - 1}px)`
  );

Object.assign(window, { BREAKPOINTS, useMediaQuery, useIsMobile, useIsTablet });
