import { n as c, C as p } from "../chunks/lib-cortex-element.CVMmyPMC.js";
import { c as b } from "../chunks/component.styles.CRO4Odto.js";
import { c as g } from "../chunks/custom-element.L4WJXn1j.js";
import { L as v } from "../chunks/i18n.BABe9hN4.js";
import { i as y, x as f } from "../chunks/lit-element.jLBm65_O.js";
import { r as w } from "../chunks/state.CSDxrqLd.js";
import { e as x } from "../chunks/query.BBf1UFkC.js";
import { n as k } from "../chunks/when.Dr1es41R.js";
import M from "./menu-item.js";
var d = /* @__PURE__ */ ((e) => (e.Default = "default", e.Multiple = "multiple", e))(d || {});
const A = y`:host{background:var(--cx-panel-background-color);border:solid var(--cx-panel-border-width) var(--cx-panel-border-color);border-radius:var(--cx-border-radius-large);padding:var(--cx-spacing-x-small) 0;--divider-color:var(--cx-panel-border-color);--divider-width:var(--cx-panel-border-width);--divider-spacing:var(--cx-spacing-x-small);display:block;position:relative;overflow:auto}:host([horizontal]){padding:0 var(--cx-spacing-x-small);flex-wrap:wrap;justify-content:space-between;display:flex}::slotted(cx-divider){--color:var(--divider-color);--width:var(--divider-width);--spacing:var(--divider-spacing)}::slotted([data-alternating-grouping]):before{content:" ";background-color:var(--divider-color);margin:var(--divider-spacing) 0;height:var(--divider-width);display:block}::slotted([data-alternating-grouping=horizontal]):before{height:100%;margin:0 var(--divider-spacing);width:var(--divider-width);display:inline-block}:host([horizontal]) ::slotted(cx-menu-section){flex-wrap:wrap;justify-content:space-between;display:flex}:host([horizontal]) ::slotted(cx-menu-item){display:flex}:host([variant=multiple]){position:relative;overflow:hidden}:host([variant=multiple]) ::slotted(cx-menu[name]){opacity:0;pointer-events:none;transition:opacity var(--cx-transition-fast) ease-in-out, transform var(--cx-transition-medium) ease-in-out;border:none;top:0;left:0;transform:translate(-50%);position:absolute!important}:host([variant=multiple]) ::slotted(cx-menu[active]){opacity:1;pointer-events:auto;transform:translate(0)}.back__button::part(checked-icon),.back__button::part(submenu-icon){display:none}.back__divider{--spacing:var(--cx-spacing-x-small)}`;
var I = Object.defineProperty, C = Object.getOwnPropertyDescriptor, u = (e, t, r, i) => {
  for (var o = i > 1 ? void 0 : i ? C(t, r) : t, h = e.length - 1, n; h >= 0; h--)
    (n = e[h]) && (o = (i ? n(t, r, o) : n(o)) || o);
  return i && o && I(t, r, o), o;
};
function m(e) {
  return e.tagName.toLowerCase() === "cx-menu" && e instanceof l && e.getAttribute("role") === "menu";
}
let l = class extends p {
  constructor() {
    super(...arguments), this.localize = new v(this), this.horizontal = !1, this.variant = d.Default, this.active = !1, this.name = "", this.back = "", this.default = !1, this.bubbleKeyDown = !1, this.ignoredKeys = [], this.disabledTabLoop = !1, this.noUncheck = !1, this.resizeObserver = null, this.slotMutationObserver = null;
  }
  connectedCallback() {
    super.connectedCallback(), this.setAttribute("role", "menu"), this.slotMutationObserver = new MutationObserver(() => this.handleSlotChange()), this.slotMutationObserver.observe(this, {
      attributeFilter: ["inert", "is-empty"],
      attributes: !0,
      subtree: !0
    });
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this.resizeObserver && (this.resizeObserver.disconnect(), this.resizeObserver = null), this.slotMutationObserver && (this.slotMutationObserver.disconnect(), this.slotMutationObserver = null);
  }
  runFirstUpdated() {
    if (this.variant === d.Multiple) {
      const e = this.getAllSubMenus();
      this.setActiveMenu(e[0]?.name ?? ""), this.updateComplete.then(() => {
        this.adjustMenuSize();
      });
    }
  }
  handleClick(e) {
    const t = ["menuitem", "menuitemcheckbox"], r = e.composedPath(), i = r.find(
      (a) => t.includes(a?.getAttribute?.("role") || "")
    );
    if (!i)
      return;
    const o = i.menu;
    if (o) {
      this.setActiveMenu(o);
      return;
    }
    if (r.find(
      (a) => a?.getAttribute?.("role") === "menu"
    ) !== this)
      return;
    const s = i;
    s.type === "checkbox" && (s.checked && (this.noUncheck || s.noUncheck) || (s.checked = !s.checked)), this.emit("cx-select", { detail: { item: s } });
  }
  handleKeyDown(e) {
    if (!this.ignoredKeys.includes(e.key)) {
      if (this.isMenuItem(e.target) && (e.key === "Enter" || e.key === " ")) {
        const t = this.getCurrentItem();
        e.preventDefault(), this.bubbleKeyDown || e.stopPropagation(), t?.click();
      } else if ([
        "Home",
        "End",
        "Tab",
        "ArrowDown",
        "ArrowUp",
        "ArrowLeft",
        "ArrowRight"
      ].includes(e.key)) {
        const t = this.getAllItems(), r = this.getCurrentItem();
        let i = r ? t.indexOf(r) : 0;
        if (["ArrowLeft", "ArrowRight"].includes(e.key) && !this.bubbleKeyDown && !(this.parentElement instanceof l) && !(this.parentElement instanceof M) && e.stopPropagation(), t.length > 0) {
          const o = this.horizontal ? e.key === "ArrowRight" || i === t.length - 1 && e.key === "ArrowDown" : e.key === "ArrowDown", h = this.horizontal ? e.key === "ArrowLeft" || i === 0 && e.key === "ArrowUp" : e.key === "ArrowUp";
          if (["ArrowRight", "ArrowDown", "ArrowLeft", "ArrowUp"].includes(
            e.key
          ) && !o && !h)
            return;
          if (this.bubbleKeyDown || e.stopPropagation(), o || e.key === "Tab" && !e.shiftKey)
            i++;
          else if (h || e.key === "Tab" && e.shiftKey)
            i--;
          else if (e.key === "Home") {
            e.preventDefault();
            let n = this.parentElement?.firstElementChild;
            for (; n && !m(n); )
              n = n.nextElementSibling;
            if (n) {
              const s = n.getAllItems();
              if (s.length > 0) {
                n.setCurrentItem(s[0]), s[0].focus();
                return;
              }
            }
            i = 0;
          } else if (e.key === "End") {
            e.preventDefault();
            let n = this.parentElement?.lastElementChild;
            for (; n && !m(n); )
              n = n.previousElementSibling;
            if (n) {
              const s = n.getAllItems();
              if (s.length > 0) {
                n.setCurrentItem(s[s.length - 1]), s[s.length - 1].focus();
                return;
              }
            }
            i = 0;
          }
          if (i < 0 && !this.disabledTabLoop) {
            e.preventDefault();
            let n = this.previousElementSibling;
            for (; n && !m(n); )
              n = n.previousElementSibling;
            if (n) {
              const s = n.getAllItems();
              if (s.length > 0) {
                n.setCurrentItem(
                  s[s.length - 1]
                ), s[s.length - 1].focus();
                return;
              }
            } else {
              let s = this.parentElement?.lastElementChild;
              for (; s && !m(s); )
                s = s.previousElementSibling;
              if (s) {
                const a = s.getAllItems();
                if (a.length > 0) {
                  s.setCurrentItem(a[a.length - 1]), a[a.length - 1].focus();
                  return;
                }
              }
              i = 0;
            }
          }
          if (i > t.length - 1 && !this.disabledTabLoop) {
            e.preventDefault();
            let n = this.nextElementSibling;
            for (; n && !m(n); )
              n = n.nextElementSibling;
            if (n) {
              const s = n.getAllItems();
              if (s.length > 0) {
                n.setCurrentItem(s[0]), s[0].focus();
                return;
              }
            } else {
              let s = this.parentElement?.firstElementChild;
              for (; s && !m(s); )
                s = s.nextElementSibling;
              if (s) {
                const a = s.getAllItems();
                if (a.length > 0) {
                  s.setCurrentItem(a[0]), a[0].focus();
                  return;
                }
              }
              i = 0;
            }
          }
          if (i < 0 || i > t.length - 1)
            return;
          e.preventDefault(), this.setCurrentItem(t[i]), t[i].focus();
        }
      }
    }
  }
  handleMouseDown(e) {
    const t = e.target;
    this.isMenuItem(t) && this.setCurrentItem(t);
  }
  handleSlotChange() {
    const e = this.getAllItems();
    e.length > 0 && this.setCurrentItem(e[0]);
    let t = null;
    this.defaultSlot.assignedElements().filter((r) => {
      const i = r;
      return this.isMenuItem(i) || this.isMenuSection(i);
    }).forEach((r) => {
      const i = r, o = !i.inert && !i.hasAttribute("is-empty");
      t && o && (this.isMenuSection(t) && this.isMenuItem(i) || this.isMenuSection(i) && i.childElementCount > 0) ? i.setAttribute(
        "data-alternating-grouping",
        this.horizontal ? "horizontal" : ""
      ) : i.removeAttribute("data-alternating-grouping"), o && (t = i);
    });
  }
  isMenuSection(e) {
    return e instanceof HTMLElement ? e.tagName.toLowerCase() === "cx-menu-section" : !1;
  }
  isMenuItem(e) {
    return e instanceof HTMLElement ? e.tagName.toLowerCase() === "cx-menu-item" || ["menuitem", "menuitemcheckbox", "menuitemradio"].includes(
      e.getAttribute("role") ?? ""
    ) : !1;
  }
  /** @internal Gets all slotted menu items, ignoring dividers, headers, and other elements. */
  getAllItems() {
    return this.defaultSlot.assignedElements({ flatten: !0 }).flatMap((t) => {
      if (this.isMenuSection(t)) {
        const r = t.shadowRoot?.querySelector("slot");
        return r ? [...r.assignedElements({ flatten: !0 })] : [];
      }
      return t;
    }).filter((t) => !(t.inert || !this.isMenuItem(t)));
  }
  /** @internal Gets all slotted submenus, used for 'multiple' variant */
  getAllSubMenus() {
    return [...this.querySelectorAll("cx-menu")];
  }
  setActiveMenu(e) {
    const t = this.getAllSubMenus();
    let r = null;
    t.forEach((i) => {
      i.name === e ? (i.active = !0, r = i) : i.active = !1;
    }), this.adjustMenuSize(), r && (this.resizeObserver && (this.resizeObserver.disconnect(), this.resizeObserver = null), this.resizeObserver = new ResizeObserver(() => {
      this.adjustMenuSize();
    }), this.resizeObserver.observe(r));
  }
  async adjustMenuSize(e = 250) {
    const t = this.getActiveMenu();
    if (t) {
      await t.updateComplete;
      const r = t.offsetWidth, i = t.offsetHeight;
      this.animate(
        [
          {
            height: this.style.height ?? `${i}px`,
            width: this.style.width ?? `${r}px`
          },
          { height: `${i}px`, width: `${r}px` }
          // Fade out
        ],
        {
          duration: this.offsetHeight === 0 ? 0 : e,
          fill: "forwards"
        }
      ).play();
    } else
      this.style.width = "", this.style.height = "";
  }
  resetActiveMenu() {
    this.getAllSubMenus().forEach((t) => {
      t.default && this.setActiveMenu(t.name);
    });
  }
  getActiveMenu() {
    return this.getAllSubMenus().find((t) => t.active) || void 0;
  }
  /**
   * @internal Gets the current menu item, which is the menu item that has `tabindex="0"` within the roving tab index.
   * The menu item may or may not have focus, but for keyboard interaction purposes it's considered the "active" item.
   */
  getCurrentItem() {
    return this.getAllItems().find((e) => e.getAttribute("tabindex") === "0");
  }
  /**
   * @internal Sets the current menu item to the specified element. This sets `tabindex="0"` on the target element and
   * `tabindex="-1"` to all other items. This method must be called prior to setting focus on a menu item.
   */
  setCurrentItem(e) {
    this.getAllItems().forEach((r) => {
      r.setAttribute("tabindex", r === e ? "0" : "-1");
    });
  }
  render() {
    const e = k(
      this.back,
      () => f`<slot name="back-button" role="menuitem" menu=${this.back}><cx-menu-item part="back-button" class="back__button" menu=${this.back}><cx-icon slot="prefix" name="chevron_left"></cx-icon>${this.localize.term("back")}</cx-menu-item><cx-divider class="back__divider"></cx-divider></slot>`
    );
    return this.variant === d.Multiple ? f`${e}<slot @slotchange=${this.handleSlotChange} @click=${this.handleClick} @keydown=${this.handleKeyDown} @mousedown=${this.handleMouseDown}></slot>` : f`${e}<slot @slotchange=${this.handleSlotChange} @click=${this.handleClick} @keydown=${this.handleKeyDown} @mousedown=${this.handleMouseDown}></slot>`;
  }
};
l.styles = [b, A];
u([
  x("slot")
], l.prototype, "defaultSlot", 2);
u([
  c({ type: Boolean })
], l.prototype, "horizontal", 2);
u([
  c({ reflect: !0 })
], l.prototype, "variant", 2);
u([
  c({ reflect: !0, type: Boolean })
], l.prototype, "active", 2);
u([
  c({ reflect: !0 })
], l.prototype, "name", 2);
u([
  c({ reflect: !0 })
], l.prototype, "back", 2);
u([
  c({ reflect: !0, type: Boolean })
], l.prototype, "default", 2);
u([
  c({ attribute: "bubble-keydown", reflect: !0, type: Boolean })
], l.prototype, "bubbleKeyDown", 2);
u([
  c({
    attribute: "ignored-keys",
    converter: {
      fromAttribute: (e) => e?.split(" ") ?? [],
      toAttribute: (e) => e.join(" ")
    },
    type: String
  })
], l.prototype, "ignoredKeys", 2);
u([
  c({ attribute: "disabled-tab-loop", reflect: !0, type: Boolean })
], l.prototype, "disabledTabLoop", 2);
u([
  c({ attribute: "no-uncheck", reflect: !0, type: Boolean })
], l.prototype, "noUncheck", 2);
u([
  w()
], l.prototype, "resizeObserver", 2);
l = u([
  g("cx-menu")
], l);
export {
  l as default
};
