"use client";

import { useEffect, useState } from "react";

import { PLAYER_DESKTOP_BREAKPOINT_PX } from "@/lib/player-viewport";

/**
 * 是否按移动端紧凑布局渲染（< lg / 1024px）。
 * 桌面端启用侧栏 + 顶栏布局（见 UI 设计稿）。
 */
export function useIsMobile(): boolean {
  const [isMobile, setIsMobile] = useState(() => {
    if (typeof window === "undefined") return true;
    return window.matchMedia(
      `(max-width: ${PLAYER_DESKTOP_BREAKPOINT_PX - 1}px)`,
    ).matches;
  });

  useEffect(() => {
    const query = `(max-width: ${PLAYER_DESKTOP_BREAKPOINT_PX - 1}px)`;
    const mq = window.matchMedia(query);
    const sync = () => setIsMobile(mq.matches);
    // sync() is still needed for the rare case where the lazy initializer
    // was correct but the viewport changed between SSR and hydration.
    sync();
    mq.addEventListener("change", sync);
    return () => mq.removeEventListener("change", sync);
  }, []);

  return isMobile;
}