import React from "react";
import { useAnchoredPosition, portalToBody } from "./Popover.jsx";

/**
 * A 12px label naming an icon-only control. Portalled to the document in viewport
 * coordinates, so a tooltip opened from inside a scrolling table, sidebar or chart
 * is not clipped by the container.
 */
export function Tooltip({ content, side = "top", delay = 200, className = "", children }) {
  const [open, setOpen] = React.useState(false);
  const anchorRef = React.useRef(null);
  const panelRef = React.useRef(null);
  const timer = React.useRef(null);
  const pos = useAnchoredPosition(open, anchorRef, panelRef, side, "center");
  const show = () => { timer.current = setTimeout(() => setOpen(true), delay); };
  const hide = () => { clearTimeout(timer.current); setOpen(false); };
  React.useEffect(() => () => clearTimeout(timer.current), []);
  return (
    <span ref={anchorRef} className={className} style={{ display: "inline-flex" }} data-slot="tooltip"
      onMouseEnter={show} onMouseLeave={hide} onFocus={show} onBlur={hide}>
      {children}
      {open ? portalToBody(
        <span ref={panelRef} role="tooltip" className="o-tooltip" data-slot="tooltip-popup" data-side={side}
          style={{ position: "fixed", top: pos.top, left: pos.left, zIndex: 70, whiteSpace: "nowrap" }}>{content}</span>
      ) : null}
    </span>
  );
}
export function TooltipProvider({ children }) { return <>{children}</>; }
export function TooltipTrigger({ children }) { return children; }
export function TooltipPopup({ children }) { return <>{children}</>; }
