import { jsx } from "react/jsx-runtime";
import React__default, { useCallback, useEffect, useMemo } from "react";
import Tooltip from "../Tooltip.js";
import { Loadable } from "../utils/loadable.js";
function useTableTooltip({ columns, data }) {
  const [tooltipProps, setTooltipProps] = React__default.useState(void 0);
  const timeoutRef = React__default.useRef(0);
  const closeTooltip = useCallback(() => {
    window.clearTimeout(timeoutRef.current);
    timeoutRef.current = 0;
    setTooltipProps(void 0);
  }, []);
  const onItemHovered = React__default.useCallback(
    (args) => {
      var _a;
      if (args.kind === "cell") {
        window.clearTimeout(timeoutRef.current);
        setTooltipProps(void 0);
        const [columnIdx, rowIdx] = args.location;
        const record = data[rowIdx];
        if (record && Loadable.isLoaded(record)) {
          const text = (_a = columns[columnIdx]) == null ? void 0 : _a.tooltip(record.data);
          if (text) {
            timeoutRef.current = window.setTimeout(() => {
              setTooltipProps({
                open: true,
                text,
                x: args.bounds.x + 20,
                y: args.bounds.y + 20
              });
            }, 500);
          }
        }
      } else {
        closeTooltip();
      }
    },
    [data, columns, closeTooltip]
  );
  useEffect(() => () => window.clearTimeout(timeoutRef.current), []);
  const tooltip = useMemo(
    () => tooltipProps ? /* @__PURE__ */ jsx(
      "div",
      {
        style: {
          left: tooltipProps.x,
          position: "fixed",
          top: tooltipProps.y,
          zIndex: 10
        },
        children: /* @__PURE__ */ jsx(Tooltip, { content: tooltipProps.text, open: tooltipProps.open, placement: "top" })
      }
    ) : null,
    [tooltipProps]
  );
  return {
    closeTooltip,
    onItemHovered,
    tooltip
  };
}
export {
  useTableTooltip
};
