import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2025-2026 GoodData Corporation
import { useId, useMemo, useRef, useState } from "react";
import { useResponsiveTags } from "./hooks/useResponsiveTags.js";
import { useTagsInteractions } from "./interactions.js";
import { UiTag } from "./UiTag.js";
import { bem } from "../@utils/bem.js";
import { UiButton } from "../UiButton/UiButton.js";
import { UiCombobox } from "../UiCombobox/UiCombobox.js";
import { UiComboboxInput } from "../UiCombobox/UiComboboxInput.js";
import { UiComboboxList } from "../UiCombobox/UiComboboxList.js";
import { UiComboboxListItem, UiComboboxListItemCreatableLabel, UiComboboxListItemLabel, } from "../UiCombobox/UiComboboxListItem.js";
import { UiComboboxPopup } from "../UiCombobox/UiComboboxPopup.js";
import { UiPopover } from "../UiPopover/UiPopover.js";
const { b, e } = bem("gd-ui-kit-tags");
const defaultAccessibilityConfig = {};
/**
 * @internal
 */
export function UiTags({ tags, tagOptions, addLabel = "Add tag", nameLabel = "Name", cancelLabel = "Cancel", closeLabel = "Close", saveLabel = "Save", noTagsLabel = "No tags", moreLabel = "More tags", removeLabel = "Remove", creatableLabel = "(Create new)", mode = "single-line", canDeleteTags = true, canCreateTag = true, readOnly = false, onTagClick = () => { }, onTagAdd = () => { }, onTagRemove = () => { }, accessibilityConfig = defaultAccessibilityConfig, }) {
    const inputRef = useRef(null);
    const [popupOpen, setPopupOpen] = useState(false);
    const popupId = useId();
    const isDeletable = canDeleteTags && !readOnly;
    const isAddable = canCreateTag && !readOnly;
    const { rootRef, showedTags, hiddenTags, tagsContainerRef, hiddenTagsContainerRef, tooltipTagsContainerRef, addButtonRef, allContainerRef, tooltipWidth, availableWidth, lastAvailableWidth, setTooltipContainer, } = useResponsiveTags(tags, mode, [canCreateTag, canDeleteTags, readOnly]);
    const items = [...showedTags, hiddenTags];
    const { handleKeyDown, interactionState, onMoreOpen, onMoreClose, onAddOpen, onAddClose, showedFocusedIndex, hiddenFocusedIndex, tag, setTag, onTagClickHandler, onTagRemoveHandler, onTagAddHandler, } = useTagsInteractions(rootRef, tooltipTagsContainerRef, showedTags, hiddenTags, onTagClick, onTagAdd, onTagRemove);
    const comboboxOptions = useMemo(() => {
        if (!tagOptions) {
            return [];
        }
        const tagIds = new Set(tags.map((tag) => tag.id));
        return tagOptions
            .filter((tagOption) => !tagIds.has(tagOption.id))
            .map((tagOption) => ({ id: tagOption.id, label: tagOption.label }));
    }, [tagOptions, tags]);
    return (_jsxs("div", { ref: rootRef, tabIndex: tags.length === 0 ? -1 : 0, onKeyDown: handleKeyDown, className: b({ readOnly, mode }), "aria-label": accessibilityConfig?.ariaLabel, "aria-labelledby": accessibilityConfig?.ariaLabelledBy, "aria-describedby": accessibilityConfig?.ariaDescribedBy, role: accessibilityConfig?.role ?? "list", children: [
            _jsx("div", { className: e("shadow-container"), ref: allContainerRef, children: tags.map((tag) => {
                    return (_jsx(UiTag, { tag: tag, isDeletable: isDeletable }, getKey(tag, isDeletable, readOnly)));
                }) }), _jsxs("div", { className: e("tags-container"), ref: tagsContainerRef, children: [items.map((tag, i) => {
                        if (Array.isArray(tag)) {
                            if (hiddenTags.length === 0) {
                                return null;
                            }
                            return (_jsx("div", { role: "listitem", className: e("hidden-tags", { isFocused: showedFocusedIndex === i }), onClick: (e) => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                }, children: hiddenTags.length > 0 ? (_jsx(UiPopover, { onOpen: onMoreOpen, onClose: onMoreClose, enableFocusTrap: true, initialFocus: tooltipTagsContainerRef, returnFocusTo: rootRef, anchor: _jsx(UiButton, { tabIndex: -1, label: `+${hiddenTags.length}`, size: "small", variant: "tertiary", ref: (ref) => {
                                            hiddenTagsContainerRef.current = ref;
                                            interactionState.current.more = ref;
                                        } }), width: 300, title: moreLabel, content: () => (_jsx("div", { onKeyDown: handleKeyDown, className: e("tags-more-tooltip"), ref: (ref) => {
                                            tooltipTagsContainerRef.current = ref;
                                            setTooltipContainer(ref);
                                        }, tabIndex: 0, children: hiddenTags.map((tag, i) => {
                                            return (_jsx(UiTag, { tag: tag, deleteLabel: removeLabel, ref: (ref) => {
                                                    interactionState.current.tags[tag.id] = ref;
                                                }, isDeletable: isDeletable, isDisabled: readOnly, isFocused: hiddenFocusedIndex === i, maxWidth: tooltipWidth, onDelete: onTagRemoveHandler, onClick: onTagClickHandler }, i));
                                        }) })), footer: ({ onClose }) => (_jsx(_Fragment, { children: _jsx(UiButton, { ref: (ref) => {
                                                interactionState.current.close = ref;
                                            }, label: closeLabel, variant: "secondary", onClick: () => {
                                                onClose();
                                            } }) })) })) : null }, i));
                        }
                        return (_jsx(UiTag, { tag: tag, ref: (ref) => {
                                interactionState.current.tags[tag.id] = ref;
                            }, isDeletable: isDeletable, isDisabled: readOnly, deleteLabel: removeLabel, isFocused: showedFocusedIndex === i, onDelete: onTagRemoveHandler, onClick: onTagClickHandler, maxWidth: i === showedTags.length - 1 ? lastAvailableWidth : availableWidth }, getKey(tag, isDeletable, readOnly)));
                    }), isAddable ? (_jsx("div", { className: e("add-button"), ref: addButtonRef, onClick: (e) => {
                            e.stopPropagation();
                            e.preventDefault();
                        }, children: _jsx(UiPopover, { id: popupId, onOpen: () => {
                                onAddOpen();
                                setPopupOpen(true);
                            }, onClose: () => {
                                setTag("");
                                onAddClose();
                                setPopupOpen(false);
                            }, enableFocusTrap: true, anchor: _jsx(UiButton, { label: showedTags.length > 0 ? "" : addLabel, accessibilityConfig: {
                                    ariaHaspopup: true,
                                    ariaControls: popupId,
                                    ariaLabel: showedTags.length > 0 ? addLabel : undefined,
                                    ariaExpanded: popupOpen,
                                    role: "listitem",
                                }, size: "small", iconBefore: "plus", variant: "tertiary", ref: (ref) => {
                                    interactionState.current.add = ref;
                                } }), title: addLabel, initialFocus: inputRef, content: ({ onClose }) => (_jsxs(UiCombobox, { options: comboboxOptions, value: tag, onValueChange: setTag, creatable: true, children: [
                                    _jsx(UiComboboxInput, { ref: (node) => {
                                            inputRef.current = node;
                                            interactionState.current.input = node;
                                        }, name: "add-input", className: e("add-input"), "aria-label": nameLabel, onKeyDown: (event) => {
                                            if (event.isDefaultPrevented()) {
                                                return;
                                            }
                                            if (event.key === "Enter") {
                                                onTagAddHandler();
                                                onClose();
                                            }
                                        } }), _jsx(UiComboboxPopup, { children: _jsx(UiComboboxList, { role: "none", children: (option, index) => (_jsxs(UiComboboxListItem, { option: option, index: index, children: [
                                                    _jsx(UiComboboxListItemLabel, { children: option.label }), option.creatable ? (_jsx(UiComboboxListItemCreatableLabel, { children: creatableLabel })) : null] }, option.id)) }) })
                                ] })), footer: ({ onClose }) => (_jsxs(_Fragment, { children: [
                                    _jsx(UiButton, { label: cancelLabel, variant: "secondary", onClick: onClose, ref: (ref) => {
                                            interactionState.current.close = ref;
                                        } }), _jsx(UiButton, { label: saveLabel, isDisabled: !tag, variant: "primary", onClick: () => {
                                            onTagAddHandler();
                                            onClose();
                                        }, ref: (ref) => {
                                            interactionState.current.save = ref;
                                        } })
                                ] })) }) })) : null, !isAddable && tags.length === 0 ? (_jsx("div", { className: e("empty-state"), children: noTagsLabel })) : null] })
        ] }));
}
function getKey(tag, isDeletable, readOnly) {
    return [tag.id, tag.isDeletable, isDeletable, readOnly].filter(Boolean).join("-");
}
//# sourceMappingURL=UiTags.js.map