import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2025-2026 GoodData Corporation
import { cloneElement, useMemo, useRef, } from "react";
import { useIdPrefixed } from "../../utils/useId.js";
import { bem } from "../@utils/bem.js";
import { UiButton } from "../UiButton/UiButton.js";
import { UiFocusManager } from "../UiFocusManager/UiFocusManager.js";
import { defaultFocusCheckFn } from "../UiFocusManager/utils.js";
import { UiTooltip } from "../UiTooltip/UiTooltip.js";
const { b, e } = bem("gd-ui-kit-popover");
const defaultAccessibilityConfig = {};
function buildAnchorAriaAttrs(cfg) {
    const ariaHaspopup = cfg?.ariaHaspopup ?? "dialog";
    const out = {};
    if (ariaHaspopup !== false) {
        out["aria-haspopup"] = ariaHaspopup;
    }
    if (cfg?.ariaControls) {
        out["aria-controls"] = cfg.ariaControls;
    }
    return out;
}
/**
 * @internal
 */
export function UiPopover({ id, accessibilityConfig = defaultAccessibilityConfig, anchor, anchorAccessibilityConfig, width = "default", title, tabIndex, disabled, content, contentPadding = "default", footer, closeText, closeVisible, initialFocus, returnFocusTo, triggerBy = ["click"], arrowPlacement = "top-start", optimalPlacement = true, returnFocusAfterClose = true, focusCheckFn = defaultFocusCheckFn, enableFocusTrap = false, isOpen, onOpenChange, onOpen, onClose, }) {
    const ref = useRef(null);
    const returnFocus = useMemo(() => {
        return returnFocusTo ?? ref;
    }, [returnFocusTo]);
    const currentId = useIdPrefixed("popover");
    const titleId = useIdPrefixed("popover-title");
    // Only point aria-labelledby at the title element when one will actually
    // render — i.e. the caller supplied a title. Without this guard, titleless
    // popovers (e.g. UiPermissionMenu) emit a dangling reference. Caller-supplied
    // ariaLabel / ariaLabelledBy in accessibilityConfig still takes precedence.
    const titleLabelledBy = title ? titleId : undefined;
    return (_jsx(UiTooltip, { isOpen: isOpen, onOpenChange: onOpenChange, onOpen: onOpen, onClose: onClose, accessibilityConfig: {
            ariaLabelledBy: titleLabelledBy,
            ...accessibilityConfig,
            role: "dialog",
        }, anchor: cloneElement(anchor, {
            ...(tabIndex === undefined ? {} : { tabIndex }),
            ...buildAnchorAriaAttrs(anchorAccessibilityConfig),
            ref: mergeRefs(ref, anchor.props?.ref),
        }), offset: 0, content: ({ onClose, type }) => {
            //NOTE: Do not make screen reader tooltip visible, live content is enough
            // because we expect that poper content is accessible only when open on click
            // and contains own logic for screen readers
            if (type === "screen-reader") {
                return null;
            }
            return (_jsx(UiFocusManager, { enableFocusTrap: enableFocusTrap, enableAutofocus: initialFocus ? { initialFocus } : true, enableReturnFocusOnUnmount: returnFocusAfterClose ? { returnFocusTo: returnFocus } : false, focusCheckFn: focusCheckFn, tabOutHandler: enableFocusTrap
                    ? undefined
                    : () => {
                        onClose();
                    }, children: _jsxs("div", { id: id ?? currentId, className: b(), style: { width: width === "default" ? undefined : width }, children: [title || closeVisible ? (_jsxs("div", { className: e("header"), children: [title ? (typeof title === "string" ? (_jsx("div", { id: titleId, className: e("header-title"), children: title })) : (_jsx("div", { id: titleId, children: title }))) : null, closeVisible ? (_jsx("div", { className: e("header-close"), children: _jsx(UiButton, { label: "", size: "small", variant: "tertiary", iconBefore: "close", accessibilityConfig: {
                                            ariaLabel: closeText,
                                        }, onClick: onClose }) })) : null] })) : null, content ? (_jsx("div", { className: e("content", { padding: contentPadding }), children: typeof content === "function" ? content({ onClose }) : content })) : null, footer ? (_jsx("div", { className: e("footer"), children: typeof footer === "function" ? footer({ onClose }) : footer })) : null] }) }));
        }, variant: "none", behaviour: "popover", triggerBy: triggerBy, showArrow: false, optimalPlacement: optimalPlacement, arrowPlacement: arrowPlacement, disabled: disabled }));
}
function mergeRefs(...refs) {
    return (value) => {
        refs.forEach((ref) => {
            if (!ref)
                return;
            if (typeof ref === "function") {
                ref(value);
            }
            else {
                ref.current = value;
            }
        });
    };
}
