'use client';

import { cloneElement, type ReactElement, useEffect, useRef, useState } from 'react';

type SafeResponsiveChartProps = {
  children: ReactElement<Record<string, unknown>>;
  className?: string;
};

export default function SafeResponsiveChart({ children, className = 'h-full min-h-0 min-w-0 w-full' }: SafeResponsiveChartProps) {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const [size, setSize] = useState({ width: 0, height: 0 });

  useEffect(() => {
    const node = containerRef.current;
    if (!node) return;

    let frameId = 0;
    const updateSize = () => {
      window.cancelAnimationFrame(frameId);
      frameId = window.requestAnimationFrame(() => {
        const rect = node.getBoundingClientRect();
        setSize({
          width: Math.max(0, Math.floor(rect.width)),
          height: Math.max(0, Math.floor(rect.height)),
        });
      });
    };

    updateSize();
    const observer = new ResizeObserver(updateSize);
    observer.observe(node);

    return () => {
      window.cancelAnimationFrame(frameId);
      observer.disconnect();
    };
  }, []);

  const canRenderChart = size.width >= 16 && size.height >= 16;

  return (
    <div ref={containerRef} className={className}>
      {canRenderChart ? (
        cloneElement(children, {
          width: size.width,
          height: size.height,
        })
      ) : null}
    </div>
  );
}
