import { useEffect, useState } from 'react';

/**
 * True when the viewport is narrower than Tailwind's `md` breakpoint (768px).
 * Used to mount mobile-only (touch/swipe) vs desktop (click) UI as a SINGLE DOM
 * branch — rendering both branches and hiding one with CSS would duplicate
 * heavy/stateful children (e.g. a ChatPane textarea), which breaks strict
 * locators and mounts redundant side-effecting content.
 *
 * @param maxWidthPx breakpoint in px (default 768 = Tailwind `md`).
 */
export function useIsMobile(maxWidthPx = 768): boolean {
  const query = `(max-width: ${maxWidthPx - 0.02}px)`;
  const [isMobile, setIsMobile] = useState(() =>
    typeof window !== 'undefined' && typeof window.matchMedia === 'function'
      ? window.matchMedia(query).matches
      : false,
  );

  useEffect(() => {
    if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return;
    const mql = window.matchMedia(query);
    const onChange = () => setIsMobile(mql.matches);
    onChange();
    mql.addEventListener('change', onChange);
    return () => mql.removeEventListener('change', onChange);
  }, [query]);

  return isMobile;
}
