import { useRef, useEffect, useState, ReactNode } from 'react';

interface ChartContainerProps {
  children: (height: number) => ReactNode;
  className?: string;
}

export function ChartContainer({ children, className = '' }: ChartContainerProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [height, setHeight] = useState(500); // Default height

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

    const resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        const { height } = entry.contentRect;
        if (height > 0) {
          setHeight(Math.floor(height));
        }
      }
    });

    resizeObserver.observe(containerRef.current);

    // Initial measurement
    const initialHeight = containerRef.current.clientHeight;
    if (initialHeight > 0) {
      setHeight(initialHeight);
    }

    return () => {
      resizeObserver.disconnect();
    };
  }, []);

  return (
    <div ref={containerRef} className={`h-full w-full ${className}`}>
      {children(height)}
    </div>
  );
}