/**
 * 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;

/**
 * Below this the viewport is short, not small.
 *
 * Every other breakpoint in this file is a width, and that is why the Piggy
 * workspace could hand a landscape phone a two-row header, a composer and a
 * tab bar and leave 40px of transcript between them: the layout was correct
 * for 393x852 and was being asked to draw 852x393.
 *
 * 560 is above both of the screens that need the room back — a phone in
 * landscape is about 390 tall, and a portrait phone with the keyboard up is
 * about the same — and comfortably below every phone held upright.
 */
export const SHORT_VIEWPORT_HEIGHT = 560;

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)`);
}

/**
 * True when the viewport is tall enough to spend a row on chrome.
 *
 * Anything that stacks a header, a scrollport and a composer inside the
 * viewport has to ask this as well as "is this the phone layout?" — the two
 * questions have different answers on a phone held sideways.
 */
export function useHasVerticalRoom(): boolean {
  return useMediaQuery(`(min-height: ${SHORT_VIEWPORT_HEIGHT}px)`);
}
