import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2007-2025 GoodData Corporation
import { Children, Fragment, PureComponent, cloneElement } from "react";
import cx from "classnames";
import { pickBy } from "lodash-es";
import { v4 as uuid } from "uuid";
/**
 * @internal
 */
export class BubbleTrigger extends PureComponent {
    static defaultProps = {
        className: "",
        children: false,
        eventsOnBubble: false,
        tagName: "span",
        openOnInit: false,
    };
    state = {
        bubbleId: `bubble-${uuid()}`,
        isBubbleVisible: this.props.openOnInit ?? false,
    };
    onClose = () => {
        this.changeBubbleVisibility(false);
    };
    eventListeners() {
        return {};
    }
    changeBubbleVisibility(active) {
        const { onBubbleOpen, onBubbleClose } = this.props;
        const { isBubbleVisible } = this.state;
        if (active && isBubbleVisible !== active && onBubbleOpen) {
            onBubbleOpen();
        }
        if (!active && onBubbleClose) {
            onBubbleClose();
        }
        this.setState({ isBubbleVisible: active });
    }
    render() {
        const { children, eventsOnBubble, className, tagName, ...others } = this.props;
        const dataAttributes = pickBy(others, (_, key) => key.startsWith("data-"));
        const classNames = cx("gd-bubble-trigger", className, {
            [this.state.bubbleId]: true,
        });
        const TagName = tagName;
        let BubbleElement;
        let WrappedTrigger;
        Children.map(children, (child) => {
            if (child) {
                if (child.type?.identifier === "Bubble") {
                    BubbleElement = child;
                }
                else {
                    WrappedTrigger = child;
                }
            }
        });
        const bubbleProps = {
            ...(eventsOnBubble ? this.eventListeners() : {}),
            alignTo: `.${this.state.bubbleId}`,
            onClose: this.onClose,
        };
        const BubbleOverlay = this.state.isBubbleVisible && BubbleElement ? cloneElement(BubbleElement, bubbleProps) : "";
        return (_jsxs(Fragment, { children: [
                _jsx(TagName, { ...dataAttributes, ...this.eventListeners(), className: classNames, children: WrappedTrigger }), BubbleOverlay] }));
    }
}
