import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
// (C) 2025 GoodData Corporation
import { useCallback, useRef, useState } from "react";
import { FloatingArrow, FloatingPortal, arrow, autoUpdate, flip, offset, safePolygon, useClick, useDismiss, useFloating, useFocus, useHover, useInteractions, } from "@floating-ui/react";
import { ConditionalScopedThemeProvider, useIsScopeThemed, useTheme } from "@gooddata/sdk-ui-theme-provider";
import { ARROW_HEIGHT, ARROW_WIDTH, HIDE_DELAY, SHOW_DELAY } from "./constants.js";
import { computeArrowOffset, computeTooltipShift, getDimensionsFromRect, getDimensionsFromRef, getFlipFallbackOrder, getOppositeBasicPlacement, } from "./utils.js";
import { useOverlayZIndexWithRegister } from "../../Overlay/index.js";
import { bem } from "../@utils/bem.js";
const { b, e } = bem("gd-ui-kit-tooltip");
/**
 * @internal
 */
export function UiTooltip({ id, anchor, content, arrowPlacement = "top", triggerBy = [], hoverOpenDelay = SHOW_DELAY, hoverCloseDelay = HIDE_DELAY, showArrow = true, width, offset: offsetProp, optimalPlacement = false, accessibilityConfig, variant = "default", disabled, isOpen: isOpenProp, onOpen, onClose, }) {
    const [isOpenInternal, setIsOpen] = useState(false);
    const isOpen = !disabled && (isOpenProp === undefined ? isOpenInternal || triggerBy.length === 0 : isOpenProp);
    const arrowRef = useRef(null);
    const themeFromContext = useTheme();
    const isScopeThemed = useIsScopeThemed();
    const theme = isScopeThemed ? themeFromContext : undefined;
    const zIndex = useOverlayZIndexWithRegister();
    const handleOpen = useCallback((open) => {
        setIsOpen(open);
        if (open) {
            onOpen?.();
        }
        else {
            onClose?.();
        }
    }, [onClose, onOpen]);
    const handleClose = useCallback(() => {
        setIsOpen(false);
        onClose?.();
    }, [onClose]);
    const customShiftMiddleware = {
        name: "customShift",
        fn(args) {
            const { x, y, rects, middlewareData } = args;
            const currentFloatingDimensions = getDimensionsFromRect(rects?.floating);
            const enable = !middlewareData?.flip?.index;
            const shift = computeTooltipShift(arrowPlacement, currentFloatingDimensions, enable, theme);
            return {
                x: shift.x ? x + shift.x : x,
                y: shift.y ? y + shift.y : y,
            };
        },
    };
    const { refs, floatingStyles, context, middlewareData } = useFloating({
        open: isOpen,
        onOpenChange: handleOpen,
        placement: getOppositeBasicPlacement(arrowPlacement),
        whileElementsMounted: autoUpdate,
        middleware: [
            offset(offsetProp ?? ARROW_HEIGHT),
            customShiftMiddleware,
            ...(optimalPlacement
                ? [
                    flip({
                        fallbackPlacements: getFlipFallbackOrder(arrowPlacement),
                        fallbackStrategy: "initialPlacement",
                    }),
                ]
                : []),
            arrow({
                element: arrowRef,
            }),
        ],
    });
    const triggerDimensions = getDimensionsFromRef(refs.reference);
    const floatingDimensions = getDimensionsFromRef(refs.floating);
    // trigger events
    const hover = useHover(context, {
        enabled: triggerBy.includes("hover"),
        move: false,
        handleClose: safePolygon({ requireIntent: true }),
        delay: {
            open: hoverOpenDelay,
            close: hoverCloseDelay,
        },
    });
    const focus = useFocus(context, {
        enabled: triggerBy.includes("focus"),
    });
    const click = useClick(context, {
        enabled: triggerBy.includes("click"),
    });
    //close on escape
    const dismiss = useDismiss(context);
    const { getReferenceProps, getFloatingProps } = useInteractions([
        ...(isOpenProp === undefined ? [dismiss] : []),
        hover,
        focus,
        click,
    ]);
    return (_jsxs(_Fragment, { children: [_jsx("div", { className: e("anchor"), ref: refs.setReference, ...getReferenceProps(), children: anchor }), _jsx("span", { className: "sr-only", id: id, children: isOpen
                    ? typeof content === "function"
                        ? content({ onClose: handleClose, type: "screen-reader" })
                        : content
                    : null }), isOpen ? (_jsx(FloatingPortal, { children: _jsx(ConditionalScopedThemeProvider, { children: _jsxs("div", { className: b({
                            width: width === "same-as-anchor" ? "same-as-anchor" : false,
                            variant,
                        }), ref: refs.setFloating, style: {
                            zIndex,
                            ...floatingStyles,
                            width: width === "same-as-anchor" ? triggerDimensions?.width : width,
                        }, "aria-label": accessibilityConfig?.ariaLabel, "aria-labelledby": accessibilityConfig?.ariaLabelledBy, "aria-describedby": accessibilityConfig?.ariaDescribedBy, "aria-expanded": accessibilityConfig?.ariaExpanded, role: accessibilityConfig?.role ?? "tooltip", ...getFloatingProps(), children: [typeof content === "function"
                                ? content({ onClose: handleClose, type: "live" })
                                : content, showArrow ? (_jsx(FloatingArrow, { staticOffset: computeArrowOffset(arrowPlacement, floatingDimensions, !middlewareData?.flip?.index, theme), className: e("arrow"), ref: arrowRef, tipRadius: 1, context: context, height: ARROW_HEIGHT, width: ARROW_WIDTH })) : null] }) }) })) : null] }));
}
//# sourceMappingURL=UiTooltip.js.map