import { useCallback, useRef, useState } from "react";

export function useContainerWidth(defaultContainerWidth) {
  const ref = useRef(null);
  const observerRef = useRef();

  const [containerWidth, setContainerWidth] = useState(defaultContainerWidth);

  const containerRef = useCallback((node) => {
    observerRef.current?.disconnect();
    observerRef.current = undefined;

    ref.current = node;

    const updateWidth = () => {
      if (!ref.current) {
        return;
      }
      let width = ref.current.clientWidth;
      try {
        width = ref.current.getBoundingClientRect().width;
      } catch {
        //
      }
      setContainerWidth(Math.floor(width));
    };

    updateWidth();

    if (node && typeof ResizeObserver !== "undefined") {
      observerRef.current = new ResizeObserver(updateWidth);
      observerRef.current.observe(node);
    }
  }, []);

  return { containerRef, containerWidth };
}
