/**
 * Viewport queries, with the breakpoints named once.
 *
 * They were not named once before, and it cost: the Piggy sheet-versus-drawer
 * switch used `md` (768px) while the shell switched navigation at `lg`
 * (1024px), so between those two widths a tablet got the desktop side sheet
 * *and* the phone tab bar, and the sheet slid in underneath it. Anything that
 * needs "is this the phone layout?" must ask the same question the shell asks.
 */
import { useEffect, useState } from 'react';

/** Tailwind `lg`. Below this the shell shows the tab bar and the nav Sheet. */
export const NAV_BREAKPOINT = 1024;

/**
 * Tailwind `xl`. The Piggy dock only earns a permanent column once the middle
 * pane still clears ~640px with both gutters taken: 1280 − 256 − 352 = 672.
 * At `lg` it would leave 416px, which is narrower than the phone layout.
 */
export const DOCK_BREAKPOINT = 1280;

export function useMediaQuery(query: string): boolean {
  const [matches, setMatches] = useState(() => window.matchMedia(query).matches);

  useEffect(() => {
    const media = window.matchMedia(query);
    const update = () => setMatches(media.matches);
    // Re-read on subscribe: the query may have changed between the initial
    // state and this effect, and a resize would otherwise be needed to notice.
    update();
    media.addEventListener('change', update);
    return () => media.removeEventListener('change', update);
  }, [query]);

  return matches;
}

/** True on the phone/small-tablet layout: tab bar, nav in a Sheet, Piggy in a Drawer. */
export function useIsMobile(): boolean {
  return !useMediaQuery(`(min-width: ${NAV_BREAKPOINT}px)`);
}

/** True when there is room for Piggy to sit in a permanent right-hand column. */
export function useHasDockRoom(): boolean {
  return useMediaQuery(`(min-width: ${DOCK_BREAKPOINT}px)`);
}
