"use client";

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

// Charts should only render once their container has a real, measured width.
// If they render earlier (during server rendering or before the browser has
// laid out the page), Recharts' ResponsiveContainer measures -1 x -1 and logs
// "The width(-1) and height(-1) of chart should be greater than 0".
//
// Attach `containerRef` to the box that wraps the chart, and only render the
// chart itself when `chartReady` is true.
export function useDashboardChartReady() {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const [chartReady, setChartReady] = useState(false);

  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    if (container.clientWidth > 0) {
      setChartReady(true);
      return;
    }

    // The container exists but has no size yet — wait until the browser
    // gives it one, then render the chart and stop watching.
    const observer = new ResizeObserver(() => {
      if (container.clientWidth > 0) {
        setChartReady(true);
        observer.disconnect();
      }
    });

    observer.observe(container);
    return () => observer.disconnect();
  }, []);

  return { containerRef, chartReady };
}
