/**
 * native chart 内核：Tooltip Host
 *
 * 监听 svg overlay 的 pointer 事件，根据 categoryScale 反查最近类目，
 * 通过 onActiveChange 回调把当前 active key + 像素位置 通知图表，
 * 由图表决定渲染 cursor 与 ChartTooltip 的位置/内容。
 */
import { useState, useRef, useCallback } from 'react';

/**
 * @param {{
 *   plot: { x:number, y:number, w:number, h:number },
 *   getCategoryAtX: (px:number, py:number) => any,   // bandScale.invert 的封装；
 *                                                    // 横向柱图需要 py，纵向柱图/折线只用 px
 *   onActiveChange?: (info:{ key:any, x:number, y:number }|null) => void,
 *   children?: React.ReactNode,                       // cursor 等覆盖层
 * }} props
 */
export default function TooltipHost({
  plot,
  getCategoryAtX,
  onActiveChange,
  children,
}) {
  const rectRef = useRef(null);
  const [, setActive] = useState(null);

  const handleMove = useCallback((e) => {
    const r = rectRef.current?.getBoundingClientRect();
    if (!r) return;
    // rect 自身从 plot.x / plot.y 起，因此把 client 偏移加回 plot 原点，
    // 还原成 SVG 用户坐标，才能与 xScale/yScale 同坐标系比较。
    const localX = plot.x + (e.clientX - r.left);
    const localY = plot.y + (e.clientY - r.top);
    if (localX < plot.x || localX > plot.x + plot.w || localY < plot.y || localY > plot.y + plot.h) {
      setActive(null);
      onActiveChange?.(null);
      return;
    }
    const key = getCategoryAtX(localX, localY);
    const info = { key, x: localX, y: localY, clientX: e.clientX, clientY: e.clientY };
    setActive(info);
    onActiveChange?.(info);
  }, [plot.x, plot.y, plot.w, plot.h, getCategoryAtX, onActiveChange]);

  const handleLeave = useCallback(() => {
    setActive(null);
    onActiveChange?.(null);
  }, [onActiveChange]);

  return (
    <g>
      <rect
        ref={rectRef}
        x={plot.x}
        y={plot.y}
        width={plot.w}
        height={plot.h}
        fill="transparent"
        onPointerMove={handleMove}
        onPointerLeave={handleLeave}
      />
      {children}
    </g>
  );
}
