import { useLayoutEffect, useRef, useState } from 'react';

/**
 * Measure an element's inner width and keep it current.
 *
 * The justified grid needs a real pixel width before it can lay anything out, and panels here are resized by
 * dragging a splitter — a width read once on mount is wrong within seconds. ResizeObserver rather than a
 * window resize listener for exactly that reason: the window never changes size, the panel does.
 */
export function useContainerWidth<T extends HTMLElement>() {
  const ref = useRef<T | null>(null);
  const [width, setWidth] = useState(0);

  useLayoutEffect(() => {
    const el = ref.current;
    if (!el) return;

    setWidth(el.clientWidth);
    const observer = new ResizeObserver((entries) => {
      const next = entries[0]?.contentRect.width ?? 0;
      setWidth((prev) => (Math.abs(prev - next) < 1 ? prev : next));
    });
    observer.observe(el);
    return () => observer.disconnect();
  }, []);

  return [ref, width] as const;
}
