/**
 * Copyright IBM Corp. 2026
 *
 * This source code is licensed under the Apache-2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */

import "../../globals/settings.js";
import { carbonElement } from "../../globals/decorators/carbon-element.js";
import { __decorate } from "../../_virtual/_@oxc-project_runtime@0.126.0/helpers/decorate.js";
import iconLoader from "../../globals/internal/icon-loader.js";
import HostListener from "../../globals/decorators/host-listener.js";
import HostListenerMixin from "../../globals/mixins/host-listener.js";
import { MenuContext } from "./menu-context.js";
import menu_item_default$1 from "./menu-item.scss.js";
import { MENU_ITEM_KIND, MENU_SIZE } from "./defs.js";
import { LitElement, html } from "lit";
import { property, state } from "lit/decorators.js";
import Checkmark16 from "@carbon/icons/es/checkmark/16.js";
import CaretLeft16 from "@carbon/icons/es/caret--left/16.js";
import CaretRight16 from "@carbon/icons/es/caret--right/16.js";
import { consume } from "@lit/context";
//#region src/components/menu/menu-item.ts
/**
* Copyright IBM Corp. 2019, 2026
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
const MENU_CLOSE_ROOT_EVENT = `cds-menu-close-root-request`;
/**
* Menu Item.
*
* @element cds-menu-item
*/
let CDSmenuItem = class CDSmenuItem extends HostListenerMixin(HostListenerMixin(LitElement)) {
	constructor(..._args) {
		super(..._args);
		this.hoverIntentDelay = 150;
		this._parentMenu = null;
		this.dangerDescription = "danger";
		this.submenuOpen = false;
		this.kind = "default";
		this.boundaries = {
			x: -1,
			y: -1
		};
		this.ariaChecked = this.getAttribute("selected") ?? "false";
		this.isRtl = false;
		this.hasSubmenu = false;
		this._handleClick = (e) => {
			if (this.disabled) return;
			if (this.hasSubmenu) {
				this._openSubmenu();
				return;
			}
			if (e.type === "keydown") {
				this.click();
				return;
			}
			this.dispatchEvent(new CustomEvent(MENU_CLOSE_ROOT_EVENT, {
				bubbles: true,
				composed: true,
				detail: { triggerEvent: e }
			}));
		};
		this._handleMouseEnter = () => {
			this.hoverIntentTimeout = setTimeout(() => {
				this._openSubmenu();
			}, this.hoverIntentDelay);
		};
		this._handleMouseLeave = () => {
			if (this.hoverIntentTimeout) {
				clearTimeout(this.hoverIntentTimeout);
				this._closeSubmenu();
				this.focus();
			}
		};
		this._openSubmenu = () => {
			const { x, y, width, height } = this.getBoundingClientRect();
			if (this.isRtl) this.boundaries = {
				x: [-x, x - width],
				y: [y, y + height]
			};
			else this.boundaries = {
				x: [x, x + width],
				y: [y, y + height]
			};
			this.submenuOpen = true;
		};
		this._registerSubMenuItems = () => {
			new MutationObserver((mutationsList) => {
				for (const mutation of mutationsList) if (mutation.type === "childList") {
					const item = (this.shadowRoot?.querySelector("slot[name=\"submenu\"]"))?.assignedElements?.()?.[0];
					if (item) switch (item.tagName) {
						case "CDS-MENU-ITEM-RADIO-GROUP":
							this.submenuEntry = item.querySelector(`cds-menu-item`);
							break;
						case "CDS-MENU-ITEM-GROUP": {
							const slotElements = item.shadowRoot?.querySelector("slot")?.assignedElements();
							const firstElement = slotElements?.length && slotElements[0];
							this.submenuEntry = firstElement;
							break;
						}
						case "CDS-MENU-ITEM":
							this.submenuEntry = item;
							break;
					}
				}
			}).observe(this.shadowRoot, {
				childList: true,
				subtree: true
			});
		};
		this._closeSubmenu = () => {
			this.boundaries = {
				x: -1,
				y: -1
			};
			this.submenuOpen = false;
			(this.shadowRoot?.querySelector(`.cds--menu-item`))?.focus();
		};
		this._handleKeyDown = (e) => {
			if (this.hasSubmenu && [
				"ArrowRight",
				"Enter",
				" "
			].includes(e.key)) {
				this._openSubmenu();
				setTimeout(() => {
					this.submenuEntry.focus();
				});
				e.stopPropagation();
			} else if (e.key === "Enter" || e.key === " ") this._handleClick(e);
		};
	}
	async dispatchIconDetect() {
		if (!!this.querySelector("[slot=\"render-icon\"]")) {
			await void 0;
			this.dispatchEvent(new CustomEvent("icon-detect", {
				bubbles: true,
				composed: true
			}));
		}
	}
	_updateAttributes() {
		if (this.disabled && !this.hasSubmenu) {
			this.setAttribute("aria-disabled", this.disabled);
			this.setAttribute("tabindex", "-1");
		} else if (this._parentMenu && !this._parentMenu.open) {
			this.removeAttribute("aria-disabled");
			this.setAttribute("tabindex", "-1");
		} else {
			this.removeAttribute("aria-disabled");
			this.setAttribute("tabindex", "0");
		}
		if (this.hasSubmenu) this.setAttribute("aria-haspopup", this.hasSubmenu + "");
		else this.removeAttribute("aria-haspopup");
		if (this.closest(`cds-menu-item-radio-group`)) {
			this.setAttribute("role", "menuitemradio");
			this.setAttribute("aria-checked", this.ariaChecked + "");
		} else if (!this.getAttribute("role")) this.setAttribute("role", "menuitem");
	}
	firstUpdated() {
		this.hasSubmenu = !!this.querySelector("[slot=\"submenu\"]");
		this.dispatchIconDetect();
		this.isRtl = document.dir === "rtl";
		this._registerSubMenuItems();
		this._parentMenu = this.closest(`cds-menu`);
		this._updateAttributes();
		this.addEventListener(`cds-menu-closed`, () => {
			this.focus();
			this._closeSubmenu();
		});
		if (this._parentMenu) {
			this._parentMenuObserver = new MutationObserver(() => {
				this._updateAttributes();
			});
			this._parentMenuObserver.observe(this._parentMenu, {
				attributes: true,
				attributeFilter: ["open"]
			});
		}
	}
	disconnectedCallback() {
		this._parentMenuObserver?.disconnect();
	}
	updated() {
		if (this.hasSubmenu) this.setAttribute("aria-expanded", this.hasSubmenu + "");
		else this.removeAttribute("aria-expanded");
		if (this.kind === "danger") this.classList.toggle(`cds--menu-item--danger`);
	}
	handleClick(event) {
		this._handleClick(event);
	}
	handleMouseDown(event) {
		if (this.disabled) event.preventDefault();
	}
	handleMouseEnter() {
		if (this.hasSubmenu) this._handleMouseEnter();
	}
	handleMouseLeave() {
		if (this.hasSubmenu) this._handleMouseLeave();
	}
	handleKeyDown(event) {
		this._handleKeyDown(event);
	}
	render() {
		const { label, shortcut, submenuOpen, boundaries, isRtl, kind, dangerDescription } = this;
		const isDanger = kind === "danger" && !this.hasSubmenu;
		const menuClassName = this.context?.hasSelectableItems ? `cds--menu--with-selectable-items` : "";
		return html`
      <div class="${"cds"}--menu-item__selection-icon">
        ${this.ariaChecked === "true" ? iconLoader(Checkmark16) : void 0}
      </div>

      <div class="${"cds"}--menu-item__icon">
        <slot name="render-icon"></slot>
      </div>
      <div class="${"cds"}--menu-item__label">${label}</div>
      ${isDanger ? html`<span id="danger-description" class="${"cds"}--visually-hidden"
            >${dangerDescription}</span
          >` : html``}
      ${shortcut && !this.hasSubmenu ? html` <div class="${"cds"}--menu-item__shortcut">${shortcut}</div> ` : html``}
      ${this.hasSubmenu ? html`
            <div class="${"cds"}--menu-item__shortcut">
              ${isRtl ? iconLoader(CaretLeft16) : iconLoader(CaretRight16)}
            </div>
            <cds-menu
              className=${menuClassName}
              size=${this.parentElement?.getAttribute("size") ?? "lg"}
              ?isChild="${this.hasSubmenu}"
              label="${label}"
              .open="${submenuOpen}"
              .x="${boundaries.x}"
              .y="${boundaries.y}">
              <slot name="submenu"></slot>
            </cds-menu>
          ` : html``}
    `;
	}
	static {
		this.styles = menu_item_default$1;
	}
};
__decorate([consume({ context: MenuContext })], CDSmenuItem.prototype, "context", void 0);
__decorate([property({ type: String })], CDSmenuItem.prototype, "label", void 0);
__decorate([property({ type: String })], CDSmenuItem.prototype, "shortcut", void 0);
__decorate([property({ type: Boolean })], CDSmenuItem.prototype, "disabled", void 0);
__decorate([property({
	type: String,
	attribute: "danger-description"
})], CDSmenuItem.prototype, "dangerDescription", void 0);
__decorate([property({ type: Boolean })], CDSmenuItem.prototype, "submenuOpen", void 0);
__decorate([property()], CDSmenuItem.prototype, "kind", void 0);
__decorate([property()], CDSmenuItem.prototype, "boundaries", void 0);
__decorate([property({ attribute: "aria-checked" })], CDSmenuItem.prototype, "ariaChecked", void 0);
__decorate([state()], CDSmenuItem.prototype, "submenuEntry", void 0);
__decorate([state()], CDSmenuItem.prototype, "isRtl", void 0);
__decorate([state()], CDSmenuItem.prototype, "hasSubmenu", void 0);
__decorate([HostListener("click", { capture: true })], CDSmenuItem.prototype, "handleClick", null);
__decorate([HostListener("mousedown")], CDSmenuItem.prototype, "handleMouseDown", null);
__decorate([HostListener("mouseenter")], CDSmenuItem.prototype, "handleMouseEnter", null);
__decorate([HostListener("mouseleave")], CDSmenuItem.prototype, "handleMouseLeave", null);
__decorate([HostListener("keydown")], CDSmenuItem.prototype, "handleKeyDown", null);
CDSmenuItem = __decorate([carbonElement(`cds-menu-item`)], CDSmenuItem);
var menu_item_default = CDSmenuItem;
//#endregion
export { MENU_CLOSE_ROOT_EVENT, MENU_ITEM_KIND, MENU_SIZE, menu_item_default as default };

//# sourceMappingURL=menu-item.js.map