/**
 * native chart 内核：响应式根容器
 *
 * <ChartRoot width? height />
 *   - width 缺省 → 撑满父容器，ResizeObserver 监听
 *   - children 接受函数式或元素：(geom) => <svg>...</svg>
 *   - geom = { width, height, plot: { x, y, w, h } } 已扣除 margin
 *
 * 不引入任何第三方库；依赖原生 ResizeObserver（现代浏览器默认支持）。
 */
import { useEffect, useRef, useState, useMemo } from 'react';

/**
 * 默认绘图区 margin（围绕 plot 区域留出轴标 / 图例空间）。
 */
export const DEFAULT_PLOT_MARGIN = { top: 16, right: 24, bottom: 32, left: 48 };

export default function ChartRoot({
  width: fixedWidth,
  height,
  margin = DEFAULT_PLOT_MARGIN,
  children,
  className,
  style,
  ariaLabel,
}) {
  const wrapRef = useRef(null);
  const [measured, setMeasured] = useState(0);

  useEffect(() => {
    if (fixedWidth != null) return undefined;
    const el = wrapRef.current;
    if (!el || typeof ResizeObserver === 'undefined') return undefined;
    const ro = new ResizeObserver((entries) => {
      const next = Math.floor(entries[0].contentRect.width);
      setMeasured((prev) => (prev === next ? prev : next));
    });
    ro.observe(el);
    return () => ro.disconnect();
  }, [fixedWidth]);

  const width = fixedWidth ?? measured;
  const ready = width > 0 && height > 0;

  const plot = useMemo(() => {
    const x = margin.left;
    const y = margin.top;
    const w = Math.max(0, width - margin.left - margin.right);
    const h = Math.max(0, height - margin.top - margin.bottom);
    return { x, y, w, h };
  }, [width, height, margin]);

  return (
    <div
      ref={wrapRef}
      className={className}
      style={{ width: fixedWidth ?? '100%', height, position: 'relative', ...style }}
      aria-label={ariaLabel}
    >
      {ready ? (
        typeof children === 'function'
          ? children({ width, height, plot, margin })
          : children
      ) : null}
    </div>
  );
}
