"use client";
/**
 * 响应式断点 hook
 *
 * 
 *
 * 实现要点（与 `src/lib/auth/use-auth-gate.tsx` 同款 `useSyncExternalStore` 模式）：
 *   - `subscribe` 监听 3 个 media query 的 change 事件，调用方重读 snapshot。
 *   - `getServerSnapshot` 返回 `"mobile"`（最保守的默认）以避免 SSR/水合首帧不一致。
 *   - `getSnapshot` 在客户端按 desktop → tablet → mobile 优先级匹配。
 *
 * 用法：
 *   const size = useBreakpoint();
 *   if (size === "mobile") return <MobileLayout />;
 */
import { useSyncExternalStore } from "react";

import type { DeviceSize } from "@/core/breakpoints";

const QUERIES = {
  mobile: "(max-width: 599.98px)",
  tablet: "(min-width: 600px) and (max-width: 1023.98px)",
  desktop: "(min-width: 1024px)",
} as const satisfies Record<DeviceSize, string>;

const subscribe = (cb: () => void): (() => void) => {
  if (typeof window === "undefined") return () => {};
  const mqls = Object.values(QUERIES).map((q) => window.matchMedia(q));
  const handler = () => cb();
  mqls.forEach((mql) => mql.addEventListener("change", handler));
  return () => mqls.forEach((mql) => mql.removeEventListener("change", handler));
};

const getSnapshot = (): DeviceSize => {
  if (typeof window === "undefined") return "mobile";
  if (window.matchMedia(QUERIES.desktop).matches) return "desktop";
  if (window.matchMedia(QUERIES.tablet).matches) return "tablet";
  return "mobile";
};

const getServerSnapshot = (): DeviceSize => "mobile";

export function useBreakpoint(): DeviceSize {
  return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
}
