import { h, r as registerInstance, c as createEvent, H as Host, g as getElement } from './index-baa5e267.js';
import { ElementIDUtils, ObjectUtils } from '@sankhyalabs/core';

const DropdownItem = ({ item, hasIcon, hasChildren, isLockedLevels, onSubActionClick }) => {
  return (h("div", { class: "ez-dropdown__item-wrapper", title: item.label },
    getContentLeft(item, hasIcon),
    h("span", { class: "ez-dropdown__item-label" }, item.label),
    getContentRight(item, hasChildren, isLockedLevels, onSubActionClick)));
};
const getContentLeft = (item, hasIcon) => {
  if (item == undefined || !hasIcon) {
    return;
  }
  if (item.iconName) {
    return (h("ez-icon", Object.assign({ class: "ez-dropdown__icon-left", iconName: item.iconName, size: "medium" }, { [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: `${item.id}_ezDropdownItemIcon` })));
  }
  return (h("ez-icon", { class: "ez-dropdown__icon-left ez-dropdown__hidden", size: "medium" }));
};
const getContentRight = (item, hasChildren, isLockedLevels, onClick) => {
  var _a, _b;
  if (item == undefined) {
    return;
  }
  if (!((_a = item.children) === null || _a === void 0 ? void 0 : _a.length) && item.subAction != undefined && Object.keys(item.subAction).length > 0) {
    return (h("span", Object.assign({ onClick: () => onClick(item), title: item.subAction.label, class: `ez-dropdown__link ez-dropdown__link--${item.subAction.type || "primary"}` }, { [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: `${item.subAction.id}_ezDropdownItemSubAction` }), item.subAction.label));
  }
  if (isLockedLevels || !hasChildren) {
    return;
  }
  if (((_b = item.children) === null || _b === void 0 ? void 0 : _b.length) > 0) {
    return (h("ez-icon", Object.assign({ class: "ez-dropdown__icon-right", iconName: "chevron-right", size: "medium" }, { [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: `${item.id}_ezDropdownIconOpenChildren` })));
  }
  return (h("ez-icon", { class: "ez-dropdown__icon-right ez-dropdown__hidden", size: "medium" }));
};

class SubmenuControl {
  constructor() { }
  //---------------------------------------------
  // Public methods
  //---------------------------------------------
  /**
   * Método responsável por fechar submenus abertos e abrir o submenu desejado.
   * @param menu - Item de menu selecionado para abrir o submenu.
   */
  show(menu) {
    const submenu = menu === null || menu === void 0 ? void 0 : menu.querySelector(".ez-dropdown__submenu");
    if (menu == undefined || submenu == undefined) {
      return;
    }
    submenu.classList.remove("ez-dropdown__submenu--hide");
    this.setPosition(menu);
    this.setScrollContainer(menu);
    this.setMaxHeight(submenu);
  }
  /**
   * Método responsável por fechar um determinado submenu aberto.
   * @param menu - Item de menu selecionado com o submenu aberto.
   */
  hide(menu) {
    if (menu == undefined) {
      return;
    }
    const submenuSelector = ".ez-dropdown__submenu:not(.ez-dropdown__submenu--hide)";
    const submenuElement = menu.querySelector(submenuSelector);
    this.reset(submenuElement);
    this.hideChild(submenuElement);
  }
  /**
   * Método responsável por fechar todos os submenus filhos de um determinado submenu.
   * @param submenu - Elemento HTML do submenu pai.
   */
  hideChild(submenu) {
    if (submenu == undefined) {
      return;
    }
    submenu.querySelectorAll(".ez-dropdown__submenu")
      .forEach((child) => {
      this.reset(child);
    });
  }
  /**
   * Método responsável por posicionar o submenu na tela.
   * @param menu - Item da lista selecionado para abrir o submenu.
   */
  setPosition(menu) {
    const submenu = menu === null || menu === void 0 ? void 0 : menu.querySelector(".ez-dropdown__submenu");
    const dropdown = menu === null || menu === void 0 ? void 0 : menu.closest(".ez-dropdown");
    if (submenu == undefined || dropdown == undefined) {
      return;
    }
    submenu.style.top = this.getPositionTop(menu);
    submenu.style.left = this.getPositionRight(dropdown);
    const bounding = submenu === null || submenu === void 0 ? void 0 : submenu.getBoundingClientRect();
    const docWidth = document.body.clientWidth;
    if ((bounding === null || bounding === void 0 ? void 0 : bounding.right) > docWidth) {
      this.updatePosition(dropdown, submenu);
    }
  }
  /**
   * Método responsável por controlar a altura máxima do dropdown.
   * @param element - Elemento HTML pai do dropdown que será renderizado.
   */
  setMaxHeight(element) {
    var _a;
    const parentElement = (element === null || element === void 0 ? void 0 : element.shadowRoot) || element;
    const dropdown = parentElement === null || parentElement === void 0 ? void 0 : parentElement.querySelector(".ez-dropdown");
    const docHeight = document.body.clientHeight;
    let submenu;
    let bounding;
    if ((parentElement === null || parentElement === void 0 ? void 0 : parentElement["tagName"]) != undefined) {
      submenu = parentElement;
      bounding = submenu === null || submenu === void 0 ? void 0 : submenu.getBoundingClientRect();
    }
    else {
      bounding = dropdown === null || dropdown === void 0 ? void 0 : dropdown.getBoundingClientRect();
    }
    if (dropdown == undefined || bounding == undefined) {
      return;
    }
    /**
     * Menu aberto irá ultrapassar a altura da página?
     */
    if ((bounding.y + bounding.height) > docHeight) {
      /**
       * Menu aberto é um submenu?
       * Sim: realiza o calculo com base na altura do menu pai
       * Não: recalcula a altura do menu para atualizar a barra de rolagem
       */
      if (submenu != undefined) {
        const dropdownParent = submenu.closest(".ez-dropdown");
        const boundingParent = dropdownParent === null || dropdownParent === void 0 ? void 0 : dropdownParent.getBoundingClientRect();
        const marginTop = parseFloat(((_a = getComputedStyle(submenu)) === null || _a === void 0 ? void 0 : _a.marginTop) || "0");
        if (dropdownParent == undefined || boundingParent == undefined) {
          return;
        }
        /**
         * Submenu aberto ao ser reposicionado ficará acima da altura do menu pai?
         * Sim: posiciona o submenu na altura do menu pai e recalcula a sua altura para atualizar a barra de rolagem
         * Não: posiciona o submenu entre a altura do menu pai e o rodapé da página
         */
        if ((boundingParent.y + bounding.height) > docHeight) {
          submenu.style.top = (boundingParent.y - marginTop) + "px";
          dropdown.style.maxHeight = (docHeight - boundingParent.y) + "px";
        }
        else {
          submenu.style.top = (docHeight - bounding.height - marginTop) + "px";
        }
      }
      else {
        let maxHeight = docHeight - bounding.y;
        if (maxHeight < 0) {
          maxHeight = bounding.height - docHeight;
        }
        dropdown.style.maxHeight = maxHeight + "px";
      }
    }
    this.setSpacerContainer(dropdown);
  }
  /**
   * Método responsável por atribuir a classe de espaçamento entre o conteúdo e o scroll.
   * @param dropdown - Elemento HTML pai do container que receberá a classe.
   */
  setSpacerContainer(dropdown) {
    const container = dropdown === null || dropdown === void 0 ? void 0 : dropdown.querySelector(".ez-dropdown__container");
    if (container == undefined) {
      return;
    }
    if (container.scrollHeight > container.clientHeight) {
      container.classList.add("ez-dropdown__container--spacer");
    }
    else {
      container.classList.remove("ez-dropdown__container--spacer");
    }
  }
  /**
   * Método responsável por resetar um determinado submenu aberto.
   * @param submenu - Elemento HTML do submenu que será resetado.
   */
  reset(submenu) {
    if (submenu == undefined) {
      return;
    }
    submenu.classList.add("ez-dropdown__submenu--hide");
    submenu.style.left = "";
    submenu.style.top = "";
    const dropdown = submenu.querySelector(".ez-dropdown");
    this.resetDropdown(dropdown);
  }
  /**
   * Método responsável por resetar um determinado dropdown renderizado.
   * @param dropdown - Elemento HTML do dropdown que será resetado.
   */
  resetDropdown(dropdown) {
    if (dropdown == undefined) {
      return;
    }
    dropdown.style.maxHeight = "";
    this.setSpacerContainer(dropdown);
  }
  //---------------------------------------------
  // Private methods
  //---------------------------------------------
  /**
   * Método responsável por controlar o scroll do container do submenu aberto.
   * @param menu - Item da lista selecionado para abrir o submenu.
   */
  setScrollContainer(menu) {
    const container = menu === null || menu === void 0 ? void 0 : menu.closest(".ez-dropdown__container");
    if (container == undefined) {
      return;
    }
    container.onscroll = this.onScrollContainer.bind(this);
  }
  /**
   * Método responsável por fechar os submenus filhos ao movimentar o scroll.
   * @param event - Evento de scroll disparado pelo Elemento HTML pai.
   */
  onScrollContainer(event) {
    const target = event === null || event === void 0 ? void 0 : event.target;
    this.hideChild(target);
  }
  /**
   * Método responsável por retornar a posição superior (top) de um elemento HTML na tela.
   * @param hostElement - Elemento HTML que será capturado o valor de sua posição superior (top) na tela.
   * @returns Valor da posição superior (top) de um determinado elemento HTML.
   */
  getPositionTop(hostElement) {
    const boundingHost = hostElement === null || hostElement === void 0 ? void 0 : hostElement.getBoundingClientRect();
    if (boundingHost == undefined) {
      return;
    }
    return boundingHost.y + "px";
  }
  /**
   * Método responsável por retornar a posição direita (right) de um elemento HTML na tela.
   * @param hostElement - Elemento HTML que será capturado o valor de sua posição direita (right) na tela.
   * @returns Valor da posição direita (right) de um determinado elemento HTML.
   */
  getPositionRight(hostElement) {
    const boundingHost = hostElement === null || hostElement === void 0 ? void 0 : hostElement.getBoundingClientRect();
    if (boundingHost == undefined) {
      return;
    }
    return (boundingHost.x + boundingHost.width) + "px";
  }
  /**
   * Método responsável por retornar a posição esquerda (left) de um elemento HTML desconsiderando a largura de outro elemento HTML.
   * @param hostElement - Elemento HTML que será capturado o valor de sua posição esquerda (left) na tela.
   * @param targetElement - Elemento HTML que será capturado o valor de sua largura (width).
   * @returns Valor da posição esquerda (left) de um determinado elemento HTML desconsiderando a largura de outro elemento HTML.
   */
  getPositionLeft(hostElement, targetElement) {
    const boundingHost = hostElement === null || hostElement === void 0 ? void 0 : hostElement.getBoundingClientRect();
    const boundingTarget = targetElement === null || targetElement === void 0 ? void 0 : targetElement.getBoundingClientRect();
    if (boundingHost == undefined || boundingTarget == undefined) {
      return;
    }
    return (boundingHost.x - boundingTarget.width) + "px";
  }
  /**
   * Método responsável por atualizar a posição de um elemento HTML que renderizou fora da tela.
   * @param hostElement - Elemento HTML que será a referência de posição dentro da tela.
   * @param targetElement - Elemento HTML que será reposicionado na tela.
   */
  updatePosition(hostElement, targetElement) {
    const boundingHost = hostElement === null || hostElement === void 0 ? void 0 : hostElement.getBoundingClientRect();
    const boundingTarget = targetElement === null || targetElement === void 0 ? void 0 : targetElement.getBoundingClientRect();
    if (boundingHost == undefined || boundingTarget == undefined) {
      return;
    }
    if (boundingHost.x < boundingTarget.right) {
      targetElement.style.left = this.getPositionLeft(hostElement, targetElement);
      this.updatePosition(hostElement, targetElement);
    }
  }
}

const ezDropdownCss = ":host{--ez-dropdown--z-index:var(--more-visible, 2);--ez-dropdown--padding:var(--space--small, 6px);--ez-dropdown--box-shadow:var(--shadow--medium, 0px 8px 24px rgba(0, 38, 111, 0.1));--ez-dropdown--border-radius:var(--border--radius-medium, 12px);--ez-dropdown--background-color:var(--background--xlight, #fff);--ez-dropdown--font-family:var(--font-pattern, 'Roboto');--ez-dropdown--max-height:415px;--ez-dropdown__item--padding:var(--space--small, 6px);--ez-dropdown__item--gap:var(--space--small, 6px);--ez-dropdown__item--border-radius:var(--border--radius-small, 6px);--ez-dropdown__item--color:var(--title--primary, #2b3a54);--ez-dropdown__item--font-weight:var(--text-weight--medium, 400);--ez-dropdown__item--font-size:var(--text--medium, 14px);--ez-dropdown__item--line-height:calc(var(--ez-dropdown__item--font-size) + 4px);--ez-dropdown__item--background-color:var(--background--medium, #f0f3f7);--ez-dropdown__item--transition:var(--transition, .2s linear);--ez-dropdown__item-label--margin-right:var(--space--medium, 12px);--ez-dropdown__icon--size:var(--icon--medium, 18px);--ez-dropdown__divider--background-color:var(--color--disable-secondary, #f2f5f8);--ez-dropdown__divider--margin:var(--space--extra-small, 3px) 0;--ez-dropdown__group-label--color:var(--text--secondary, #A2ABB9);--ez-dropdown__group-label--font-weight:var(--text-weight--large, 600);--ez-dropdown__group-label--font-size:var(--text--small, 12px);--ez-dropdown__group-label--line-height:var(--text--medium, 14px);--ez-dropdown__group-label--padding:var(--space--small, 6px);--ez-dropdown__submenu--z-index:var(--most-visible, 3);--ez-dropdown__link--font-weight:var(--text-weight--large, 600);--ez-dropdown__link--primary--color:var(--color--primary, #008561);--ez-dropdown__link--critical--color:var(--color-alert--error-800, #BD0025);--ez-dropdown__scrollbar--color-default:var(--scrollbar--default, #626e82);--ez-dropdown__scrollbar--color-background:var(--scrollbar--background, #E5EAF0);--ez-dropdown__scrollbar--color-hover:var(--scrollbar--hover, #2B3A54);--ez-dropdown__scrollbar--color-clicked:var(--scrollbar--clicked, #a2abb9);--ez-dropdown__scrollbar--border-radius:var(--border--radius-small, 6px);--ez-dropdown__scrollbar--width:var(--space--small, 6px);--ez-dropdown__scrollbar--padding-right:var(--space--extra-small, 3px);display:flex;flex-direction:column;height:fit-content;user-select:none;box-sizing:border-box;position:fixed;z-index:var(--ez-dropdown--z-index)}:host *{box-sizing:border-box}.ez-dropdown{display:flex;padding:var(--ez-dropdown--padding);box-shadow:var(--ez-dropdown--box-shadow);border-radius:var(--ez-dropdown--border-radius);background-color:var(--ez-dropdown--background-color);max-width:var(--ez-dropdown--max-width)}.ez-dropdown__max-height{max-height:var(--ez-dropdown--max-height)}.ez-dropdown *{font-family:var(--ez-dropdown--font-family)}.ez-dropdown__container{display:flex;flex-direction:column;overflow-y:auto;scrollbar-width:thin;flex:auto;scrollbar-color:var(--ez-dropdown__scrollbar--color-clicked) var(--ez-dropdown__scrollbar--color-background)}.ez-dropdown__container::-webkit-scrollbar{background-color:var(--ez-dropdown__scrollbar--color-background);width:var(--ez-dropdown__scrollbar--width);max-width:var(--ez-dropdown__scrollbar--width);min-width:var(--ez-dropdown__scrollbar--width)}.ez-dropdown__container::-webkit-scrollbar-track{background-color:var(--ez-dropdown__scrollbar--color-background);border-radius:var(--ez-dropdown__scrollbar--border-radius)}.ez-dropdown__container::-webkit-scrollbar-thumb{background-color:var(--ez-dropdown__scrollbar--color-default);border-radius:var(--ez-dropdown__scrollbar--border-radius)}.ez-dropdown__container::-webkit-scrollbar-thumb:vertical:hover,.ez-dropdown__container::-webkit-scrollbar-thumb:horizontal:hover{background-color:var(--ez-dropdown__scrollbar--color-hover)}.ez-dropdown__container::-webkit-scrollbar-thumb:vertical:active,.ez-dropdown__container::-webkit-scrollbar-thumb:horizontal:active{background-color:var(--ez-dropdown__scrollbar--color-clicked)}.ez-dropdown__container--spacer{padding-right:var(--ez-dropdown__scrollbar--padding-right)}.ez-dropdown__item{display:flex;align-items:center;background-color:transparent;border-radius:var(--ez-dropdown__item--border-radius);transition:var(--ez-dropdown__item--transition)}.ez-dropdown__item:hover{background-color:var(--ez-dropdown__item--background-color)}.ez-dropdown__item-wrapper{display:flex;align-items:center;position:relative;cursor:pointer;width:100%;margin:0;white-space:nowrap;gap:var(--ez-dropdown__item--gap);color:var(--ez-dropdown__item--color);font-weight:var(--ez-dropdown__item--font-weight);font-size:var(--ez-dropdown__item--font-size);line-height:var(--ez-dropdown__item--line-height);padding:var(--ez-dropdown__item--padding)}.ez-dropdown__item-wrapper ez-icon{display:flex;justify-content:center;align-items:center;width:var(--ez-dropdown__icon--size);height:var(--ez-dropdown__icon--size);min-width:var(--ez-dropdown__icon--size);min-height:var(--ez-dropdown__icon--size)}.ez-dropdown__item-content{display:flex;align-items:center;flex:auto;overflow:hidden;gap:var(--ez-dropdown__item--gap)}.ez-dropdown__item-label{text-align:left;text-overflow:ellipsis;overflow:hidden;flex:auto}.ez-dropdown__item-label:not(:last-child){margin-right:var(--ez-dropdown__item-label--margin-right)}.ez-dropdown__item-content+.ez-dropdown__link{margin-left:var(--ez-dropdown__item-label--margin-right);margin-right:var(--ez-dropdown__item--padding)}.ez-dropdown__item-builder{flex:auto}.ez-dropdown__divider{width:100%;height:2px;border-radius:1px;border:none;display:block;background-color:var(--ez-dropdown__divider--background-color);margin:var(--ez-dropdown__divider--margin)}.ez-dropdown__hidden{visibility:hidden}.ez-dropdown__group{display:flex;flex-direction:column}.ez-dropdown__group-label{display:block;width:100%;text-align:left;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ez-dropdown__group-label--color);font-weight:var(--ez-dropdown__group-label--font-weight);font-size:var(--ez-dropdown__group-label--font-size);line-height:var(--ez-dropdown__group-label--line-height);padding:var(--ez-dropdown__group-label--padding)}.ez-dropdown__icon-right{margin-left:auto}.ez-dropdown__submenu{position:fixed;z-index:var(--ez-dropdown__submenu--z-index);margin-top:calc(var(--ez-dropdown__item--padding) * -1)}.ez-dropdown__submenu--hide{display:none}.ez-dropdown__link{display:block;margin-left:auto;cursor:pointer;text-overflow:ellipsis;overflow:hidden;font-weight:var(--ez-dropdown__link--font-weight);max-width:calc(var(--ez-dropdown--max-width) * 0.43)}.ez-dropdown__link--primary{color:var(--ez-dropdown__link--primary--color)}.ez-dropdown__link--critical{color:var(--ez-dropdown__link--critical--color)}.ez-dropdown__link:hover{text-decoration:underline}";

const EzDropdown = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.ezClick = createEvent(this, "ezClick", 7);
    this.ezSubActionClick = createEvent(this, "ezSubActionClick", 7);
    this.ezOutsideClick = createEvent(this, "ezOutsideClick", 7);
    this.ezHover = createEvent(this, "ezHover", 7);
    this._itemList = {};
    this._submenuList = [];
    this._openedMenuList = {};
    /**
     * Limitador de níveis de menu + submenu.
     * Valor 0, null ou undefined desativa o limitador.
     */
    this._levelLimits = 3;
    this.items = [];
    this.value = undefined;
    this.itemBuilder = undefined;
  }
  handleClickOutside(event) {
    if (!this._element.contains(event.target)) {
      this.ezOutsideClick.emit();
    }
  }
  //---------------------------------------------
  // Private methods
  //---------------------------------------------
  defaultItemBuilder(item, isLockedLevels, hasIcon, hasChildren) {
    return (h(DropdownItem, { item: item, hasIcon: hasIcon, hasChildren: hasChildren, isLockedLevels: isLockedLevels, onSubActionClick: this.onSubActionClick.bind(this) }));
  }
  getMaxOrder(items) {
    if (items == undefined || items.length === 0) {
      return -1;
    }
    return Math.max(...items.map((item) => {
      var _a;
      const order = (_a = item.group) === null || _a === void 0 ? void 0 : _a["order"];
      return order != undefined && order >= 0 ? order : -1;
    }));
  }
  hasIcon(items) {
    return items === null || items === void 0 ? void 0 : items.some((item) => (item.iconName || "") !== "");
  }
  hasGroup(items) {
    return items === null || items === void 0 ? void 0 : items.some((item) => (item.group || "") !== "");
  }
  hasChildren(items) {
    return items === null || items === void 0 ? void 0 : items.some((item) => (item.children || []).length > 0);
  }
  isLockedLevels(level) {
    if (!this._levelLimits) {
      return false;
    }
    return level === (this._levelLimits + 1);
  }
  getItemsByGroup(items, level) {
    let itemsByGroup = {};
    const maxOrder = this.getMaxOrder(items);
    items.forEach((item) => {
      const label = item.group && item.group["label"] != undefined ? item.group["label"] || "noGroup" : item.group || "noGroup";
      const order = item.group && item.group["order"] != undefined ? item.group["order"] : item.group ? (maxOrder + 1) : (maxOrder + 2);
      let groupObj = itemsByGroup[label];
      if (groupObj == undefined) {
        groupObj = {
          items: [],
          order
        };
      }
      this.validateItem(item, level);
      groupObj.items.push(item);
      itemsByGroup[label] = groupObj;
    });
    return ObjectUtils.sortByProperty(itemsByGroup, "order");
  }
  validateItem(item, level) {
    if (this._itemList == undefined) {
      this._itemList = {};
    }
    if (item.type == undefined) {
      item.type = "item";
    }
    if (item.id == undefined) {
      const itemId = `level_${level}_${item.type}`;
      const counter = Object.keys(this._itemList).filter((key) => key.includes(itemId)).length;
      item.id = `${itemId}_${counter + 1}`;
    }
    if (item.label == undefined) {
      item.label = "";
    }
    if (item.subAction != undefined) {
      if (item.subAction.id == undefined) {
        const subId = `subAction_${item.id}`;
        item.subAction.id = subId;
      }
      if (item.subAction.label == undefined) {
        item.subAction.label = "";
      }
    }
    if (this._itemList[item.id] == undefined) {
      this._itemList[item.id] = {};
    }
  }
  getContainerItemBuilder(item, level, isLockedLevels, hasIcon, hasChildren) {
    if (this.itemBuilder == undefined) {
      return;
    }
    const customContent = this.itemBuilder(item, level);
    if (customContent == undefined) {
      return this.defaultItemBuilder(item, isLockedLevels, hasIcon, hasChildren);
    }
    if (typeof customContent !== "string") {
      return (h("div", { class: "ez-dropdown__item-builder" }, customContent));
    }
    return (h("div", { class: "ez-dropdown__item-builder", innerHTML: customContent }));
  }
  getItemsRender(groupItems, level, hasIcon, hasChildren) {
    if (groupItems == undefined) {
      return;
    }
    let counterLevel = level;
    let isLockedLevels = false;
    if (hasChildren) {
      counterLevel++;
      isLockedLevels = this.isLockedLevels(counterLevel);
    }
    return groupItems.map((item) => {
      var _a;
      switch (item.type) {
        case "loading":
          return (h("div", { class: "ez-dropdown__item" }, h("ez-skeleton", { width: '200px' })));
        case "divider":
          return (h("hr", Object.assign({ class: "ez-dropdown__divider" }, { [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: ElementIDUtils.getInternalIDInfo(`${item.id}_ezDropdownDivider`) })));
        default:
          return (h("div", Object.assign({ ref: (ref) => this._itemList[item.id] = ref, class: "ez-dropdown__item", "data-level": level }, { [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: ElementIDUtils.getInternalIDInfo(`${item.id}_ezDropdownItem`) }), h("div", { class: "ez-dropdown__item-content", onClick: (evt) => this.onItemClick(evt, item), onMouseOver: (evt) => this.onShowSubmenu(evt, item), onMouseEnter: () => this.ezHover.emit(item) }, this.itemBuilder
            ? this.getContainerItemBuilder(item, level, isLockedLevels, hasIcon, hasChildren)
            : this.defaultItemBuilder(item, isLockedLevels, hasIcon, hasChildren)), ((_a = item.children) === null || _a === void 0 ? void 0 : _a.length) > 0 &&
            !isLockedLevels &&
            hasChildren &&
            h("div", { ref: (ref) => this._submenuList.push(ref), class: "ez-dropdown__submenu ez-dropdown__submenu--hide" }, this.renderDropdown(item.children, counterLevel))));
      }
    });
  }
  renderDropdown(branchItems = this.items, level = 1) {
    if (branchItems == undefined || this.isLockedLevels(level)) {
      return;
    }
    const itemsByGroup = this.getItemsByGroup(branchItems, level);
    const hasGroup = this.hasGroup(branchItems);
    const hasIcon = this.hasIcon(branchItems);
    const hasChildren = this.hasChildren(branchItems);
    return (h("div", { class: "ez-dropdown ez-dropdown__max-height", "data-level": level }, h("div", { class: "ez-dropdown__container" }, Object.keys(itemsByGroup)
      .map((groupLabel) => {
      return (h("div", Object.assign({ class: "ez-dropdown__group" }, { [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: ElementIDUtils.getInternalIDInfo(`${groupLabel}_ezDropdownGroup`) }), groupLabel !== "noGroup" &&
        h("label", { class: "ez-dropdown__group-label", title: groupLabel }, groupLabel), hasGroup &&
        groupLabel === "noGroup" &&
        h("hr", Object.assign({ class: "ez-dropdown__divider" }, { [ElementIDUtils.DATA_ELEMENT_ID_ATTRIBUTE_NAME]: ElementIDUtils.getInternalIDInfo(`${groupLabel}_ezDropdownDivider`) })), this.getItemsRender(itemsByGroup[groupLabel].items, level, hasIcon, hasChildren)));
    }))));
  }
  hasOpenedSubmenu(level) {
    const openedLevels = Object.keys(this._openedMenuList);
    return openedLevels.includes(level.toString())
      || openedLevels.some((openedLevel) => Number(openedLevel) > level);
  }
  hasSubmenuOpened() {
    var _a;
    return (_a = this._submenuList) === null || _a === void 0 ? void 0 : _a.some((submenu) => !submenu.classList.contains("ez-dropdown__submenu--hide"));
  }
  setEvents() {
    document.removeEventListener('click', this.onHideAllSubmenu.bind(this));
    document.addEventListener('click', this.onHideAllSubmenu.bind(this));
    document.removeEventListener('scroll', this.onSubmenuReposition.bind(this));
    document.addEventListener('scroll', this.onSubmenuReposition.bind(this));
  }
  //---------------------------------------------
  // Event handlers
  //---------------------------------------------
  onShowSubmenu(evt, item) {
    var _a;
    if (evt == undefined) {
      return;
    }
    const menu = this._itemList[item.id];
    if (!(menu === null || menu === void 0 ? void 0 : menu.classList.contains("ez-dropdown__item"))) {
      return;
    }
    const level = Number(menu.dataset.level || "0");
    if (this.hasOpenedSubmenu(level)) {
      this._submenuControl.hide(this._openedMenuList[level]);
      delete this._openedMenuList[level];
    }
    if (!((_a = item.children) === null || _a === void 0 ? void 0 : _a.length)) {
      return;
    }
    this._openedMenuList[menu.dataset.level] = menu;
    this._submenuControl.show(menu);
  }
  onItemClick(evt, item) {
    const target = evt === null || evt === void 0 ? void 0 : evt.target;
    if (target === null || target === void 0 ? void 0 : target.classList.contains("ez-dropdown__link")) {
      return;
    }
    this.value = item;
    this.ezClick.emit(item);
  }
  onSubActionClick(item) {
    this.ezSubActionClick.emit(item.subAction);
  }
  onHideAllSubmenu(evt = undefined) {
    const target = evt === null || evt === void 0 ? void 0 : evt.target;
    if (this.hasSubmenuOpened() && (target == undefined || (!target.closest(".ez-dropdown") && target.tagName !== "EZ-DROPDOWN"))) {
      this._openedMenuList = {};
      this._submenuList.forEach(this._submenuControl.reset.bind(this._submenuControl));
    }
  }
  onSubmenuReposition() {
    if (this._openedMenuList != undefined) {
      Object.keys(this._openedMenuList).forEach((key) => {
        const menu = this._openedMenuList[key];
        this._submenuControl.setPosition(menu);
      });
    }
  }
  //---------------------------------------------
  // Lifecycle web component
  //---------------------------------------------
  componentDidLoad() {
    ElementIDUtils.addIDInfo(this._element);
    this._submenuControl = new SubmenuControl();
    this._submenuControl.setMaxHeight(this._element);
  }
  componentDidUpdate() {
    this._submenuControl.setMaxHeight(this._element);
  }
  componentDidRender() {
    this.setEvents();
  }
  render() {
    return (h(Host, null, this.renderDropdown()));
  }
  get _element() { return getElement(this); }
};
EzDropdown.style = ezDropdownCss;

export { EzDropdown as ez_dropdown };
