import { jsx, jsxs } from 'react/jsx-runtime';
import { createContext, useContext, useRef, useLayoutEffect, forwardRef, isValidElement, useMemo, Fragment, useState, useCallback, cloneElement, useId, useEffect } from 'react';
import { c as cx } from './index-De1g9FRV.js';
import { p as portalScopeClassNames } from './portalScopeClassNames-BTyv0FY8.js';
import { T as ThemeProviderContext } from './ThemeProviderContext-l52GohYT.js';
import { g as getKeyboardFocusableElements } from './getKeyboardFocusableElements-B_U9rt6y.js';
import { T as ThemeProvider } from './ThemeProvider-Sd8LK0A9.js';
import { u as useMergeRefs } from './useMergeRefs-Dfmtq9cI.js';
import { c as childrenToString } from './childrenToString-Bz9MqbHb.js';
import { useTrackingId } from './useTrackingId.js';
import { c as computePosition, b as autoUpdate, d as safeShowPopover, e as safeHidePopover, o as offset, f as flip, s as shift, g as arrow$1, l as limitShift } from './floating-ui.react-dom-CyrxPiI-.js';

import './Tooltip.css';const TooltipContext = createContext(null);

function useTooltipContext() {
  const context = useContext(TooltipContext);
  const invokerRef = useRef(null);
  const popoverRef = useRef(null);
  const arrowRef = useRef(null);
  useLayoutEffect(() => {
    if (!invokerRef.current) return;
    context?.setInvoker?.(invokerRef.current);
    if (!context?.openState) return;
    if (!context?.controlled) return;
    context.openTooltip();
  }, [context, invokerRef]);
  useLayoutEffect(() => {
    if (!popoverRef.current) return;
    context?.setTooltip?.(popoverRef.current);
    context?.setRootNode?.(popoverRef.current.getRootNode());
    if (!arrowRef.current) return;
    context?.setArrowElement?.(arrowRef.current);
  }, [context, popoverRef]);
  const onMouseEnterHandler = () => {
    if (context?.controlled) return;
    context?.openTooltip();
  };
  const onMouseLeaveHandler = () => {
    if (context?.controlled) return;
    context?.closeTooltip();
  };
  const onFocusHandler = () => {
    if (context?.controlled) return;
    context?.openTooltip();
  };
  const onBlurHandler = () => {
    if (context?.controlled) return;
    context?.closeTooltip();
  };
  const onKeyDownHandler = (e) => {
    if (!context?.openState) return;
    if (e.code === "Escape" && !context.controlled) {
      context?.closeTooltip();
      return;
    }
  };
  if (!context || !invokerRef || !popoverRef) return;
  return {
    invoker: {
      ref: invokerRef,
      element: context.invoker,
      onMouseEnter: onMouseEnterHandler,
      onMouseLeave: onMouseLeaveHandler,
      onKeyDown: onKeyDownHandler,
      onFocus: onFocusHandler,
      onBlur: onBlurHandler,
      "aria-haspopup": true,
      "aria-details": context.tooltipId,
      "data-state": context.openState ? "open" : "closed",
      "aria-describedby": context.tooltipId
    },
    tooltip: {
      ref: popoverRef,
      element: context.popover,
      id: context.tooltipId,
      setId: context.setTooltipId,
      show: context.openTooltip,
      close: context.closeTooltip,
      style: context.tooltipStyle,
      arrowRef,
      key: context.resetKey
    },
    setOpen: context.setOpenState,
    open: context.openState,
    controlled: context.controlled,
    placement: context.placement,
    disableFlipFallback: context.disableFlipFallback
  };
}

const content = "_content_1arq6_1";
const scroller = "_scroller_1arq6_38";
const trigger = "_trigger_1arq6_43";
const arrow = "_arrow_1arq6_48";
const styles = {
	content: content,
	scroller: scroller,
	trigger: trigger,
	arrow: arrow
};

const TooltipContentElement = forwardRef(
  function TooltipContent2(props, ref) {
    const {
      children,
      className,
      style,
      onMouseEnter,
      onMouseLeave,
      onKeyDown,
      onFocus,
      onBlur,
      id,
      ...rest
    } = props;
    const context = useTooltipContext();
    const { mode: currentMode } = useContext(ThemeProviderContext);
    const tooltipClassNames = cx(
      className,
      styles["content"],
      portalScopeClassNames
    );
    const childrenRef = useRef(null);
    const focusItems = useRef();
    const combinedStyles = {
      ...style,
      ...context?.tooltip.style
    };
    const tooltipMode = currentMode === "dark" ? "light" : "dark";
    useLayoutEffect(() => {
      if (!childrenRef.current) return;
      const focusElements = getKeyboardFocusableElements(childrenRef.current);
      focusItems.current = focusElements;
    }, [childrenRef, children, context?.open]);
    useLayoutEffect(() => {
      if (id) {
        context?.tooltip.setId(id);
      }
    }, [id, context?.tooltip.setId, context?.tooltip]);
    const onMouseEnterHandler = (e) => {
      onMouseEnter?.(e);
      if (context?.controlled) return;
      context?.tooltip.show();
    };
    const onMouseLeaveHandler = (e) => {
      onMouseLeave?.(e);
      if (context?.controlled) return;
      context?.tooltip.close();
    };
    const onFocusHandler = (e) => {
      onFocus?.(e);
      if (context?.controlled) return;
      context?.tooltip.show();
    };
    const onBlurHandler = (e) => {
      onBlur?.(e);
      if (context?.controlled) return;
      context?.tooltip.close();
    };
    const onKeyDownHandler = (e) => {
      onKeyDown?.(e);
      if (!context?.open) return;
      if (e.code === "Escape") {
        context?.tooltip.close();
      }
    };
    const hasSimpleContent = typeof children === "string";
    const role = hasSimpleContent ? "tooltip" : "region";
    const tooltipWrapperRef = useMergeRefs([context?.tooltip.ref, ref]);
    return /* @__PURE__ */ jsxs(
      "div",
      {
        popover: "manual",
        "data-anv": "tooltip-content",
        className: tooltipClassNames,
        ref: tooltipWrapperRef,
        style: combinedStyles,
        onMouseEnter: onMouseEnterHandler,
        onMouseLeave: onMouseLeaveHandler,
        onBlur: onBlurHandler,
        onFocus: onFocusHandler,
        role,
        id: context?.tooltip.id,
        ...rest,
        children: [
          /* @__PURE__ */ jsx(
            "div",
            {
              className: styles.scroller,
              role: "presentation",
              tabIndex: -1,
              ref: childrenRef,
              onKeyDown: onKeyDownHandler,
              children: hasSimpleContent ? children : /* @__PURE__ */ jsx(ThemeProvider, { mode: tooltipMode, "data-anv": "tooltip-content-theme", children })
            },
            context?.tooltip.key
          ),
          /* @__PURE__ */ jsx("span", { className: styles["arrow"], ref: context?.tooltip.arrowRef, children: /* @__PURE__ */ jsxs("svg", { "aria-hidden": "true", width: "14", height: "14", viewBox: "0 0 14 14", children: [
            /* @__PURE__ */ jsx("path", { stroke: "none", d: "M0,0 H14 L7,7 Q7,7 7,7 Z" }),
            /* @__PURE__ */ jsx("clipPath", { id: ":r9:", children: /* @__PURE__ */ jsx("rect", { x: "0", y: "0", width: "14", height: "14" }) })
          ] }) })
        ]
      }
    );
  }
);
const TooltipContent = forwardRef(
  function TooltipContent3(props, ref) {
    return /* @__PURE__ */ jsx(TooltipContentElement, { ...props, ref });
  }
);

const INTERACTIVE_ELEMENTS = ["button", "a", "input", "textarea", "select"];
function isNonInteractiveElement(element) {
  if (!isValidElement(element)) return false;
  const type = element.type;
  return typeof type === "string" && !INTERACTIVE_ELEMENTS.includes(type);
}

const TooltipTriggerElement = forwardRef(
  function TooltipTrigger2(props, propRef) {
    const { children, className, onKeyDown, onFocus, onBlur, ...rest } = props;
    const context = useTooltipContext();
    const childCanAcceptRef = useMemo(
      () => isValidElement(children) && children.type !== Fragment && typeof children.type !== "function",
      [children]
    );
    const [invokerElement, setInvokerElement] = useState(
      null
    );
    const setInvokerRef = useCallback((element) => {
      setInvokerElement(element);
    }, []);
    const refs = useMergeRefs([
      children?.ref,
      context?.invoker.ref,
      setInvokerRef
    ]);
    const childProps = useMemo(() => {
      const baseProps = {
        ref: refs,
        "aria-haspopup": context?.invoker["aria-haspopup"],
        "aria-details": context?.invoker["aria-details"],
        "data-state": context?.invoker["data-state"],
        "aria-describedby": context?.invoker["aria-describedby"]
      };
      if (isNonInteractiveElement(children)) {
        if (!("tabIndex" in (children.props || {}))) {
          baseProps.tabIndex = 0;
        }
        if (!("role" in (children.props || {}))) {
          baseProps.role = "button";
        }
      }
      return baseProps;
    }, [context?.invoker, refs, children]);
    const child = childCanAcceptRef ? cloneElement(children, childProps) : /* @__PURE__ */ jsx("span", { ...childProps, children });
    const onKeyDownHandler = (e) => {
      onKeyDown?.(e);
      context?.invoker.onKeyDown(e);
    };
    const onFocusHandler = (e) => {
      onFocus?.(e);
      context?.invoker.onFocus();
    };
    const onBlurHandler = (e) => {
      onBlur?.(e);
      context?.invoker.onBlur();
    };
    useLayoutEffect(() => {
      const invoker = context?.invoker;
      if (!invokerElement) return;
      const onMouseEnterHandler = () => {
        invoker?.onMouseEnter();
      };
      const onMouseLeaveHandler = () => {
        invoker?.onMouseLeave();
      };
      invokerElement.addEventListener("mouseleave", onMouseLeaveHandler);
      invokerElement.addEventListener("mouseenter", onMouseEnterHandler);
      return () => {
        invokerElement.removeEventListener("mouseleave", onMouseLeaveHandler);
        invokerElement.removeEventListener("mouseenter", onMouseEnterHandler);
      };
    }, [context?.invoker, invokerElement]);
    const data = {
      children: childrenToString(props.children)
    };
    const trackingId = useTrackingId({
      name: "TooltipTrigger",
      data,
      hasOverride: !!props["data-tracking-id"]
    });
    return /* @__PURE__ */ jsx(
      "span",
      {
        className: cx([styles["trigger"]], className),
        "data-anv": "tooltip-trigger",
        "data-tracking-id": trackingId,
        ref: propRef,
        onKeyDown: onKeyDownHandler,
        onFocus: onFocusHandler,
        onBlur: onBlurHandler,
        role: "presentation",
        ...rest,
        children: child
      }
    );
  }
);
const TooltipTrigger = forwardRef(
  function TooltipTrigger3(props, propRef) {
    return /* @__PURE__ */ jsx(TooltipTriggerElement, { ...props, ref: propRef });
  }
);

const Tooltip = Object.assign(
  function TooltipInner(props) {
    const {
      children,
      delay = 100,
      placement = "top",
      open,
      defaultOpen = false,
      disableShift,
      disableFlip,
      disableFlipFallback,
      id,
      offset: offsetProp = 5,
      fallbackPlacements
    } = props;
    const uid = useId();
    const [invoker, setInvoker] = useState(void 0);
    const [tooltip, setTooltip] = useState(void 0);
    const [rootNode, setRootNode] = useState();
    const [arrowElement, setArrowElement] = useState(void 0);
    const [openState, setOpenState] = useState(open ?? defaultOpen);
    const arrowRef = useRef(null);
    const [tooltipId, setTooltipId] = useState(id ?? `tooltip-${uid.replace(/:/g, "")}`);
    const updatePosition = useCallback(() => {
      if (!invoker || !tooltip) return;
      if (!openState) return;
      computePosition(invoker, tooltip, {
        strategy: "fixed",
        placement,
        middleware: [
          offset(offsetProp),
          flip({
            mainAxis: !disableFlip,
            crossAxis: false,
            fallbackAxisSideDirection: disableFlipFallback ? "none" : "end",
            fallbackPlacements,
            padding: 5
          }),
          shift({
            padding: 5,
            mainAxis: !disableShift,
            crossAxis: false,
            limiter: limitShift({
              mainAxis: !disableShift
            })
          }),
          arrow$1({
            element: arrowElement ? arrowElement : null,
            padding: 5
          })
        ]
      }).then(({ x, y, placement: placement2, middlewareData }) => {
        const side = placement2.split("-")[0];
        const staticSide = {
          top: "bottom",
          right: "left",
          bottom: "top",
          left: "right"
        }[side];
        const arrowDeg = () => {
          if (staticSide === "top") return 180;
          if (staticSide === "bottom") return 0;
          if (staticSide === "left") return 90;
          return 270;
        };
        Object.assign(tooltip.style, {
          left: `${x}px`,
          top: `${y}px`
        });
        if (middlewareData.arrow && arrowElement) {
          const { x: x2, y: y2 } = middlewareData.arrow;
          Object.assign(arrowElement.style, {
            left: x2 != null ? `${x2}px` : "",
            top: y2 != null ? `${y2}px` : "",
            right: "",
            bottom: "",
            [staticSide]: `${-arrowElement.offsetWidth + 2}px`,
            transform: `rotate(${arrowDeg()}deg)`
          });
        }
      });
    }, [
      invoker,
      tooltip,
      openState,
      placement,
      offsetProp,
      disableFlip,
      disableFlipFallback,
      fallbackPlacements,
      disableShift,
      arrowElement
    ]);
    const resetKey = useRef(0);
    useLayoutEffect(() => {
      if (!tooltip || !invoker) return;
      if (!openState) {
        resetKey.current += 1;
        return;
      }
      let requestID = null;
      const cleanup = autoUpdate(invoker, tooltip, () => {
        requestID = requestAnimationFrame(updatePosition);
      });
      return () => {
        if (requestID) cancelAnimationFrame(requestID);
        cleanup();
      };
    }, [invoker, tooltip, updatePosition, openState]);
    const isControlled = typeof open !== "undefined";
    const openTimeoutRef = useRef(null);
    const closeTimeoutRef = useRef(null);
    const openTooltip = useCallback(() => {
      clearTimeout(closeTimeoutRef.current);
      clearTimeout(openTimeoutRef.current);
      if (!tooltip || !rootNode?.querySelector(`#${tooltipId}`)) return;
      openTimeoutRef.current = setTimeout(() => {
        safeShowPopover(tooltip);
        setOpenState(true);
      }, delay);
    }, [tooltip, rootNode, tooltipId, delay]);
    const closeTooltip = useCallback(
      (fn) => {
        clearTimeout(openTimeoutRef.current);
        clearTimeout(closeTimeoutRef.current);
        if (!tooltip || !openState) return;
        closeTimeoutRef.current = setTimeout(() => {
          fn?.();
          setOpenState(false);
          safeHidePopover(tooltip);
        }, 100);
      },
      [openState, tooltip]
    );
    useEffect(() => {
      return () => {
        clearTimeout(closeTimeoutRef.current);
        clearTimeout(openTimeoutRef.current);
      };
    }, []);
    const initialRender = useRef(true);
    useEffect(() => {
      if (initialRender.current === true) {
        if (!openState || isControlled) {
          initialRender.current = false;
          return;
        }
        if (!tooltip) return;
        openTooltip();
        initialRender.current = false;
        return;
      }
    }, [openTooltip, openState, isControlled, tooltip]);
    useEffect(() => {
      if (!isControlled) return;
      if (open) {
        openTooltip();
      } else {
        closeTooltip();
      }
    }, [closeTooltip, isControlled, open, openTooltip]);
    const value = useMemo(() => {
      updatePosition();
      return {
        tooltipId,
        setTooltipId,
        invoker,
        setInvoker,
        tooltip,
        setTooltip,
        arrowElement,
        setArrowElement,
        openTooltip,
        closeTooltip,
        placement,
        openState,
        setOpenState,
        disableFlipFallback,
        controlled: isControlled,
        arrowRef,
        resetKey: resetKey.current,
        rootNode,
        setRootNode
      };
    }, [
      updatePosition,
      tooltipId,
      setTooltipId,
      invoker,
      tooltip,
      arrowElement,
      openTooltip,
      closeTooltip,
      placement,
      openState,
      disableFlipFallback,
      isControlled,
      rootNode
    ]);
    return /* @__PURE__ */ jsx(TooltipContext.Provider, { value, children });
  },
  {
    /**
     * TooltipTrigger component that wraps the element that triggers the tooltip.
     *
     * Features:
     * - Wraps any React element to make it a tooltip trigger
     * - Handles mouse and keyboard interactions
     * - Provides proper ARIA attributes for accessibility
     * - Supports all standard HTML element props
     * - Automatically clones child elements with proper refs
     * - Handles both focusable and non-focusable children
     * - Manages mouse enter/leave events for hover behavior
     *
     * @example
     * <Tooltip.Trigger>
     *   <Button>Click me</Button>
     * </Tooltip.Trigger>
     */
    Trigger: TooltipTrigger,
    /**
     * TooltipContent component that displays the tooltip content.
     *
     * Features:
     * - Displays the tooltip content with proper positioning
     * - Includes an arrow pointing to the trigger element
     * - Supports keyboard navigation and escape key to close
     * - Handles mouse interactions for hover behavior
     * - Accessible with proper ARIA roles
     * - Supports all standard div element props
     * - Automatic focus management for keyboard navigation
     * - Real-time position updates
     * - Handles both string and complex content
     *
     * @example
     * <Tooltip.Content>
     *   This tooltip provides helpful context
     * </Tooltip.Content>
     */
    Content: TooltipContent
  }
);

export { Tooltip as T };
//# sourceMappingURL=Tooltip-BC8lnFhe.js.map
