import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
// (C) 2026 GoodData Corporation
import { useRef } from "react";
import { useIntl } from "react-intl";
import { olpPermissionMessages } from "../../locales.js";
import { bem } from "../@utils/bem.js";
import { UiIcon } from "../UiIcon/UiIcon.js";
import { UiIconButton } from "../UiIconButton/UiIconButton.js";
import { UiPopover } from "../UiPopover/UiPopover.js";
import { UiTooltip } from "../UiTooltip/UiTooltip.js";
const { b, e } = bem("gd-ui-kit-permission-menu");
/**
 * Per-grantee permission popover. Renders a fixed set of rows — two
 * permission levels (Can view & share / Can view), an optional divider,
 * and an optional Remove access action row. Each level row carries an
 * `infoCircle` tooltip. Labels and Transfer ownership live in the separate
 * {@link UiMoreOptionsMenu}.
 *
 * @internal
 */
export function UiPermissionMenu({ anchor, selectedLevel, onPermissionChange, onRemoveAccess, dataTestId, }) {
    return (_jsx(UiPopover, { anchor: anchor, anchorAccessibilityConfig: { ariaHaspopup: "menu" }, width: 180, content: ({ onClose }) => (_jsx(MenuBody, { selectedLevel: selectedLevel, onPermissionChange: onPermissionChange, onRemoveAccess: onRemoveAccess, onClose: onClose, dataTestId: dataTestId })) }));
}
function MenuBody({ selectedLevel, onPermissionChange, onRemoveAccess, onClose, dataTestId, }) {
    const intl = useIntl();
    const choose = (next) => () => {
        next();
        onClose();
    };
    const levelItems = [
        {
            key: "SHARE",
            label: intl.formatMessage(olpPermissionMessages.canViewAndShare),
            tooltip: intl.formatMessage(olpPermissionMessages.canViewAndShareTooltip),
            radioValue: "SHARE",
            onClick: choose(() => onPermissionChange("SHARE")),
        },
        {
            key: "VIEW",
            label: intl.formatMessage(olpPermissionMessages.canView),
            tooltip: intl.formatMessage(olpPermissionMessages.canViewTooltip),
            radioValue: "VIEW",
            onClick: choose(() => onPermissionChange("VIEW")),
        },
    ];
    const actionItems = [];
    if (onRemoveAccess) {
        actionItems.push({
            key: "remove",
            label: intl.formatMessage(olpPermissionMessages.removeAccess),
            icon: "trash",
            onClick: choose(onRemoveAccess),
        });
    }
    const menuRef = useRef(null);
    const handleKeyDown = (event) => {
        const root = menuRef.current;
        if (!root)
            return;
        const focusable = Array.from(root.querySelectorAll('button[role^="menuitem"]'));
        const currentIndex = focusable.indexOf(document.activeElement);
        if (currentIndex < 0)
            return;
        let nextIndex = null;
        switch (event.key) {
            case "ArrowDown":
                nextIndex = (currentIndex + 1) % focusable.length;
                break;
            case "ArrowUp":
                nextIndex = (currentIndex - 1 + focusable.length) % focusable.length;
                break;
            case "Home":
                nextIndex = 0;
                break;
            case "End":
                nextIndex = focusable.length - 1;
                break;
            default:
                return;
        }
        event.preventDefault();
        focusable[nextIndex]?.focus();
    };
    return (_jsx("div", { className: b(), "data-testid": dataTestId, children: _jsxs("div", { ref: menuRef, className: e("items"), role: "menu", "aria-orientation": "vertical", "aria-label": intl.formatMessage(olpPermissionMessages.menuLabel), onKeyDown: handleKeyDown, children: [levelItems.map((item) => (_jsx(PermissionMenuItem, { item: item, selectedLevel: selectedLevel }, item.key))), actionItems.length > 0 ? _jsx("div", { className: e("divider"), role: "separator" }) : null, actionItems.map((item) => (_jsx(PermissionMenuItem, { item: item, selectedLevel: selectedLevel }, item.key)))] }) }));
}
function PermissionMenuItem({ item, selectedLevel }) {
    const intl = useIntl();
    // Tooltip anchor must live OUTSIDE the menu-item button so we don't nest an
    // interactive element inside a button (invalid HTML, breaks focus). The row
    // wrapper provides the flex layout; the button covers the label; the
    // tooltip sits next to the button.
    const isRadio = !!item.radioValue;
    const isChecked = isRadio && item.radioValue === selectedLevel;
    return (_jsxs("div", { className: e("item-row"), children: [
            _jsxs("button", { type: "button", role: isRadio ? "menuitemradio" : "menuitem", "aria-checked": isRadio ? isChecked : undefined, className: e("item"), onClick: item.onClick, children: [item.icon ? _jsx(UiIcon, { type: item.icon, size: 16, color: "complementary-7" }) : null, _jsx("span", { className: e("item-label"), children: item.label })
                ] }), item.tooltip ? (_jsx(UiTooltip, { triggerBy: ["hover", "focus"], content: item.tooltip, anchor: _jsx(UiIconButton, { icon: "infoCircle", variant: "tertiary", size: "small", accessibilityConfig: {
                        ariaLabel: intl.formatMessage(olpPermissionMessages.moreInfoAriaLabel, {
                            label: item.label,
                        }),
                    } }) })) : null] }));
}
