import { Component, Element, Event, Host, Listen, Prop, h } from '@stencil/core';
import { Utils } from '../../utils/utils';
import { IgcContextMenuOrientation } from '../dockmanager/dockmanager.interfaces';
/**
 * @hidden
 */
export class IgcContextMenuComponent {
  constructor() {
    this.activeIndex = 0;
    this.handleDocumentResize = () => {
      this.menuClosed.emit();
    };
    this.handleDocumentMouseDown = (ev) => {
      if (ev.composedPath().every(el => el !== this.elem)) {
        // mousedown outside of context menu
        this.menuClosed.emit();
      }
    };
  }
  emitMenuClosed() {
    this.menuClosed.emit();
  }
  connectedCallback() {
    document.defaultView.addEventListener('resize', this.handleDocumentResize, false);
    document.defaultView.addEventListener('mousedown', this.handleDocumentMouseDown, false);
  }
  disconnectedCallback() {
    document.defaultView.removeEventListener('resize', this.handleDocumentResize, false);
    document.defaultView.removeEventListener('mousedown', this.handleDocumentMouseDown, false);
  }
  componentDidLoad() {
    const menuItemsDivRect = this.menuItemsDiv.getBoundingClientRect();
    const targetRect = this.target.getBoundingClientRect();
    const hostRect = this.elem.getBoundingClientRect();
    let menuLeft = targetRect.right - menuItemsDivRect.width - hostRect.left;
    let menuTop = this.orientation === IgcContextMenuOrientation.bottom ? targetRect.top + targetRect.height - hostRect.top : targetRect.top - menuItemsDivRect.height - hostRect.top;
    const menuBottom = menuTop + menuItemsDivRect.height;
    menuLeft = menuLeft >= 0 ? menuLeft : menuLeft + menuItemsDivRect.width - targetRect.width;
    menuTop = menuTop >= 0 ? menuTop : menuTop + menuItemsDivRect.height + targetRect.height;
    if (this.orientation === IgcContextMenuOrientation.bottom && menuBottom > hostRect.height) {
      menuTop = targetRect.top - menuItemsDivRect.height;
    }
    this.menuItemsDiv.style.left = menuLeft + 'px';
    this.menuItemsDiv.style.top = menuTop + 'px';
    this.menuItemsDiv.style.visibility = 'visible';
    this.focusItemAndSetActiveIndex();
  }
  focusItemAndSetActiveIndex() {
    var _a;
    const firstMenuItem = this.menuItemsDiv.querySelector('div[part="menu-item"]');
    (_a = firstMenuItem) === null || _a === void 0 ? void 0 : _a.focus();
  }
  handleKeyboardEvents(item, ev) {
    const menuItemChildren = this.menuItemsDiv.querySelectorAll('div[part="menu-item"]');
    if (ev.key === 'ArrowDown') {
      if (this.activeIndex < menuItemChildren.length - 1) {
        this.activeIndex++;
        menuItemChildren[this.activeIndex].focus();
      }
    }
    else if (ev.key === 'ArrowUp') {
      if (this.activeIndex > 0) {
        this.activeIndex--;
        menuItemChildren[this.activeIndex].focus();
      }
    }
    else if (ev.key === 'Enter' || ev.key === ' ') {
      item.clickHandler();
      this.emitMenuClosed();
    }
    else if (ev.key === 'Escape') {
      this.emitMenuClosed();
    }
  }
  handleMenuItemClick(item) {
    item.clickHandler();
    this.emitMenuClosed();
  }
  render() {
    return (h(Host, { exportparts: "menu-content: context-menu, menu-item: context-menu-item" },
      h("div", { role: "menu", part: "menu-content", ref: el => this.menuItemsDiv = el, onMouseDown: ev => {
          ev.preventDefault();
        } }, this.items.map(item => {
        const parts = Utils.partNameMap({
          'menu-item': true,
          disabled: item.disabled
        });
        return (h("div", { role: "menuitem", part: parts, tabindex: "-1", onKeyDown: this.handleKeyboardEvents.bind(this, item), onClick: this.handleMenuItemClick.bind(this, item) },
          h("span", { style: {
              flexGrow: '1',
              userSelect: 'none',
            } }, item.displayText),
          item.iconName !== null &&
            h("igc-icon-component", { name: item.iconName })));
      }))));
  }
  static get is() { return "igc-context-menu-component"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() { return {
    "$": ["context-menu-component.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["context-menu-component.css"]
  }; }
  static get properties() { return {
    "orientation": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "IgcContextMenuOrientation",
        "resolved": "IgcContextMenuOrientation.bottom | IgcContextMenuOrientation.top",
        "references": {
          "IgcContextMenuOrientation": {
            "location": "import",
            "path": "../dockmanager/dockmanager.interfaces"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "orientation",
      "reflect": false
    },
    "target": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "HTMLElement",
        "resolved": "HTMLElement",
        "references": {
          "HTMLElement": {
            "location": "global"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "items": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "IgcContextMenuItem[]",
        "resolved": "IgcContextMenuItem[]",
        "references": {
          "IgcContextMenuItem": {
            "location": "import",
            "path": "../dockmanager/dockmanager.interfaces"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "activeIndex": {
      "type": "number",
      "mutable": true,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "active-index",
      "reflect": false,
      "defaultValue": "0"
    }
  }; }
  static get events() { return [{
      "method": "menuClosed",
      "name": "menuClosed",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }]; }
  static get elementRef() { return "elem"; }
  static get listeners() { return [{
      "name": "focusout",
      "method": "emitMenuClosed",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
