import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2025-2026 GoodData Corporation
import { forwardRef, useLayoutEffect, useState } from "react";
import { bem } from "../@utils/bem.js";
import { UiIcon } from "../UiIcon/UiIcon.js";
import { UiTooltip } from "../UiTooltip/UiTooltip.js";
const { b, e } = bem("gd-ui-kit-tag");
/**
 * @internal
 */
export const UiTag = forwardRef(function UiTag({ label, size = "small", variant = "solid", iconBefore, iconBeforeColor, tabIndex, deleteTabIndex, accessibilityConfig, isDisabled, isDeletable, dataTestId, labelAs, onClick, onDelete, onDeleteKeyDown, }, ref) {
    const [labelRef, setLabelRef] = useState(null);
    const [hasTooltip, setHasTooltip] = useState(false);
    const { ariaLabel, ariaLabelledBy, deleteAriaLabel } = accessibilityConfig ?? {};
    useLayoutEffect(() => {
        if (labelRef && labelRef.offsetWidth < labelRef.scrollWidth) {
            setHasTooltip(true);
        }
        else {
            setHasTooltip(false);
        }
    }, [labelRef]);
    const iconSize = size === "small" ? 14 : 16;
    const defaultIconColor = variant === "decorated" ? "complementary-0" : "complementary-6";
    const iconColor = iconBeforeColor ?? defaultIconColor;
    const labelIsButton = labelAs ? labelAs === "button" : onClick !== undefined;
    const labelClassName = e("trigger", {
        isDeletable: isDeletable ?? false,
        isDisabled: isDisabled ?? false,
    });
    const labelInner = (_jsxs(_Fragment, { children: [iconBefore ? (_jsx("span", { className: e("icon-before"), children: _jsx(UiIcon, { type: iconBefore, size: iconSize, color: iconColor }) })) : null, _jsx("span", { className: e("label"), ref: setLabelRef, children: label })
        ] }));
    const labelElement = labelIsButton ? (_jsx("button", { ref: ref, tabIndex: tabIndex, "data-testid": dataTestId, className: labelClassName, disabled: isDisabled, "aria-disabled": isDisabled, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, onClick: onClick, children: labelInner })) : (_jsx("span", { className: labelClassName, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, "data-testid": dataTestId, children: labelInner }));
    return (_jsxs("div", { className: b({ size, variant }), children: [hasTooltip ? (_jsx(UiTooltip, { anchor: labelElement, content: _jsx("div", { className: e("tooltip"), children: label }), triggerBy: ["hover"], arrowPlacement: "top" })) : (labelElement), isDeletable && !isDisabled ? (_jsx("button", { tabIndex: deleteTabIndex, "data-testid": dataTestId ? `${dataTestId}-delete-button` : undefined, "aria-label": deleteAriaLabel, className: e("delete"), onClick: onDelete, onKeyDown: onDeleteKeyDown, children: _jsx("span", { className: e("icon-delete"), children: _jsx(UiIcon, { size: 14, type: "cross", color: variant === "decorated" ? "complementary-0" : "complementary-6" }) }) })) : null] }));
});
