import { useEffect, useState } from "react";

/** Mobile breakpoint — matches the project's `$media-breakpoint-mobile` token (640px). */
const MOBILE_BREAKPOINT_PX = 640;

/**
 * Returns `true` when the viewport is ≤ the mobile breakpoint. Used to
 * branch TZ-prescribed mobile-only behaviors (e.g. Online-Board's
 * `Время рейса` default = -1h/+3h per §4.1.1-R5).
 *
 * SSR: returns `false` initially, then updates on first client render.
 */
export function useIsMobileViewport(): boolean {
  const [isMobile, setIsMobile] = useState<boolean>(() => {
    if (typeof window === "undefined") return false;
    return window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT_PX}px)`).matches;
  });

  useEffect(() => {
    if (typeof window === "undefined") return;
    const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT_PX}px)`);
    const listener = (e: MediaQueryListEvent | { matches: boolean }) => setIsMobile(e.matches);
    setIsMobile(mql.matches);
    mql.addEventListener("change", listener as (e: MediaQueryListEvent) => void);
    return () => mql.removeEventListener("change", listener as (e: MediaQueryListEvent) => void);
  }, []);

  return isMobile;
}
