import { jsx as _jsx } from "react/jsx-runtime";
import { useCallback, useEffect, useState, } from "react";
import { SimpleTooltip } from "./styled";
export const useFixedTooltip = (scrollable = false) => {
    const [tooltipData, setTooltipData] = useState(null);
    const onElementEnter = useCallback((e) => {
        const rect = e.target?.getBoundingClientRect?.();
        setTooltipData({
            rect,
            t: rect.top,
            l: rect.left + rect?.width / 2,
            initialMouseXY: [e.clientX - rect.left, e.clientY - rect.top],
            initialOffsetXY: [window.pageXOffset, window.pageYOffset],
        });
    }, []);
    const onElementLeave = useCallback(() => {
        setTooltipData(null);
    }, []);
    const onScroll = useCallback(() => {
        if (!scrollable) {
            setTooltipData(null);
            return;
        }
        if (!tooltipData)
            return;
        const { initialMouseXY, initialOffsetXY } = tooltipData;
        const offsetXY = [window.pageXOffset, window.pageYOffset];
        const deltaXY = initialOffsetXY.map((v, i) => v - offsetXY[i]);
        const prevRect = tooltipData.rect.toJSON();
        const currentRect = document
            .elementFromPoint(tooltipData.l + initialMouseXY[0] - deltaXY[0], tooltipData.t + initialMouseXY[1] - deltaXY[1])
            ?.getBoundingClientRect()
            .toJSON();
        const isSameElement = currentRect &&
            prevRect.x === currentRect.x - deltaXY[0] &&
            prevRect.y === currentRect.y - deltaXY[1] &&
            prevRect.width === currentRect.width &&
            prevRect.height === currentRect.height;
        if (!isSameElement) {
            setTooltipData(null);
        }
        else {
            setTooltipData({
                ...tooltipData,
                t: currentRect.top,
                l: currentRect.left,
            });
        }
    }, [tooltipData]);
    useEffect(() => {
        window.addEventListener("scroll", onScroll);
        return () => window.removeEventListener("scroll", onScroll);
    });
    const TooltipComponent = useCallback(({ children, offsetX, offsetY, width }) => {
        if (!tooltipData)
            return _jsx("div", {});
        const autoWidth = typeof children === "string" ? 50 + children.length * 6 : null;
        return (_jsx(SimpleTooltip, { width: autoWidth ?? width, top: tooltipData.t + (offsetY ?? 0), left: tooltipData.l + (offsetX ?? 0), fixed: true, children: children }));
    }, [tooltipData?.t, tooltipData?.l]);
    return { onElementEnter, onElementLeave, TooltipComponent };
};
//# sourceMappingURL=index.js.map