// responsive.jsx — tiny viewport helpers shared across the landing templates.
// useVW(): current window width, re-rendering on resize (debounced via rAF).
// Pages derive `const m = useVW() < 760` to flip grids/padding/nav for mobile.
// useElementWidth(): measured width of a ref'd node (used to scale live
// thumbnails on the index page).

function useVW() {
  const [w, setW] = React.useState(() => (typeof window !== 'undefined' ? window.innerWidth : 1280));
  React.useEffect(() => {
    let raf = 0;
    const on = () => { cancelAnimationFrame(raf); raf = requestAnimationFrame(() => setW(window.innerWidth)); };
    window.addEventListener('resize', on);
    return () => { window.removeEventListener('resize', on); cancelAnimationFrame(raf); };
  }, []);
  return w;
}

function useElementWidth() {
  const ref = React.useRef(null);
  const [w, setW] = React.useState(0);
  React.useLayoutEffect(() => {
    const el = ref.current;
    if (!el) return;
    const ro = new ResizeObserver((entries) => {
      for (const e of entries) setW(e.contentRect.width);
    });
    ro.observe(el);
    setW(el.getBoundingClientRect().width);
    return () => ro.disconnect();
  }, []);
  return [ref, w];
}

Object.assign(window, { useVW, useElementWidth });
