import { FloatingManager, KeyboardManager } from '@sankhyalabs/core';
import { h, Host } from "@stencil/core";
import initI18n from '../../utils/i18n';
export class EzPopup {
  constructor() {
    this.handleFooterSlotChange = (event) => {
      const slot = event.target;
      this._hasFooterSlotContent = slot.assignedElements().length > 0;
    };
    this._hasFooterSlotContent = false;
    this.size = "medium";
    this.opened = false;
    this.useHeader = true;
    this.heightMode = "full";
    this.ezTitle = undefined;
    this.enabledScroll = true;
    this.autoClose = true;
    this.footerButtons = [];
  }
  observeConfig() {
    this.manageOverflow();
  }
  async componentWillLoad() {
    this.i18n = await initI18n();
  }
  componentDidLoad() {
    this.popUpFocus();
    this._keyboardManager = new KeyboardManager({ propagate: false, element: this._element, enableShadowDom: true })
      .bind("Enter", this.ezPopupAction.emit.bind("OK"))
      .bind("Escape", () => this.closePopup())
      .bind("Esc", () => this.closePopup());
  }
  disconnectedCallback() {
    var _a;
    (_a = this._keyboardManager) === null || _a === void 0 ? void 0 : _a.unbindAllShortcutKeys();
  }
  closePopup() {
    this.opened = false;
    this.manageOverflow();
    this.ezClosePopup.emit();
  }
  manageOverflow() {
    if (this.opened) {
      window.document.body.style.overflow = "hidden";
    }
    else {
      window.document.body.style.overflow = "";
    }
  }
  manageOverlay() {
    if (this.opened) {
      this._overlayId = FloatingManager.subscribeOverlayControl(this._popupRef);
    }
    else {
      FloatingManager.unsubscribeOverlayControl(this._popupRef || this._overlayId);
    }
  }
  popUpFocus() {
    if (!this.opened) {
      return;
    }
    if (this._popupRef) {
      this._popupRef.focus();
    }
  }
  getGridSize() {
    var _a;
    const _sizeClasses = {
      "x-small": "col--sd-3 ez-popup__size-limit--x-small",
      "small": "col--sd-5",
      "medium": "col--sd-6",
      "large": "col--sd-9",
      "x-large": "col--sd-11",
      "default": "ez-popup__size-limit--x-small",
      "auto": "",
    };
    if (!this.size || !_sizeClasses.hasOwnProperty(this.size)) {
      return _sizeClasses["medium"];
    }
    return (_a = _sizeClasses[this.size]) !== null && _a !== void 0 ? _a : _sizeClasses["medium"];
  }
  getDialogClass() {
    let className = 'popup__container';
    if (this.heightMode === 'auto') {
      className += ' popup__container--auto';
    }
    className += ` ${this.getGridSize()}`;
    return className;
  }
  componentDidRender() {
    this.manageOverlay();
    this.popUpFocus();
  }
  handleAutoClose(event) {
    if (!this.opened || !this._popupRef || !this.autoClose) {
      return;
    }
    if (this._popupRef.contains(event.target)) {
      return;
    }
    const slot = this._popupRef.querySelector('slot');
    if (slot && slot.assignedElements().length > 0) {
      const assignedElements = slot.assignedElements();
      for (const element of assignedElements) {
        if (element.contains(event.target)) {
          return;
        }
      }
    }
    if (this._popupRef.shadowRoot && this._popupRef.shadowRoot.contains(event.target)) {
      return;
    }
    this.closePopup();
  }
  handleDefaultPropsButtonsByIndex(index) {
    switch (index) {
      case 0:
        return {
          label: this.i18n ? this.i18n('app.confirm') : 'Confirmar',
          variant: "primary",
          size: "small",
          onClick: () => {
            this.closePopup();
            this.ezPopupAction.emit("OK");
          }
        };
      case 1:
        return {
          label: this.i18n ? this.i18n('app.cancel') : 'Cancelar',
          variant: "secondary",
          size: "small",
          onClick: () => {
            this.closePopup();
          }
        };
      case 2:
        return {
          label: this.i18n ? this.i18n('app.close') : 'Fechar',
          variant: "tertiary",
          size: "small",
          onClick: () => {
            this.closePopup();
          }
        };
    }
  }
  renderFooterButtons() {
    return this.footerButtons.slice(0, 3).map((buttonProps, index) => (h("ez-button", Object.assign({ key: index }, this.handleDefaultPropsButtonsByIndex(index), buttonProps))));
  }
  render() {
    return (h(Host, null, this.opened && (h("div", { class: "overlay", tabIndex: -1, onClick: this.handleAutoClose.bind(this) }, h("dialog", { ref: ref => this._popupRef = ref, class: this.getDialogClass() }, this.useHeader &&
      h("header", { class: "popup__header" }, !!this.ezTitle && h("h1", { class: "popup__title" }, this.ezTitle), h("ez-button", { class: this.ezTitle ? "btn-close" : "btn-close btn-close--solo", variant: "tertiary", mode: "icon", iconName: "close", size: "small", onClick: this.closePopup.bind(this) })), h("main", { class: {
        "popup__expandable-content": true,
        "popup__overflow-y--auto": this.enabledScroll
      } }, h("slot", null)), h("footer", { class: {
        "popup__footer": true,
        "popup_margin-top": this.footerButtons.length > 0 || this._hasFooterSlotContent
      } }, this.footerButtons.length > 0 && (this.renderFooterButtons()), h("slot", { name: 'footer', onSlotchange: this.handleFooterSlotChange })))))));
  }
  static get is() { return "ez-popup"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["ez-popup.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["ez-popup.css"]
    };
  }
  static get properties() {
    return {
      "size": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "\"x-small\" | \"small\" | \"medium\" | \"large\" | \"x-large\" | \"auto\"",
          "resolved": "\"auto\" | \"large\" | \"medium\" | \"small\" | \"x-large\" | \"x-small\"",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define a largura do ez-popup."
        },
        "attribute": "size",
        "reflect": false,
        "defaultValue": "\"medium\""
      },
      "opened": {
        "type": "boolean",
        "mutable": true,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se o ez-popover est\u00E1 aberto."
        },
        "attribute": "opened",
        "reflect": true,
        "defaultValue": "false"
      },
      "useHeader": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se o componente utilizar\u00E1 cabe\u00E7alho."
        },
        "attribute": "use-header",
        "reflect": true,
        "defaultValue": "true"
      },
      "heightMode": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "\"auto\" | \"full\"",
          "resolved": "\"auto\" | \"full\"",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define altura do componente."
        },
        "attribute": "height-mode",
        "reflect": true,
        "defaultValue": "\"full\""
      },
      "ezTitle": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Texto a ser apresentado como t\u00EDtulo do componente."
        },
        "attribute": "ez-title",
        "reflect": false
      },
      "enabledScroll": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Possibilita scroll vertical no conte\u00FAdo interno do componente"
        },
        "attribute": "enabled-scroll",
        "reflect": false,
        "defaultValue": "true"
      },
      "autoClose": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [{
              "name": "default",
              "text": "true"
            }],
          "text": "Define se o popup deve fechar automaticamente ao clicar fora dele."
        },
        "attribute": "auto-close",
        "reflect": false,
        "defaultValue": "true"
      },
      "footerButtons": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "Partial<EzButtonProps>[]",
          "resolved": "Partial<EzButtonProps>[]",
          "references": {
            "Partial": {
              "location": "global"
            },
            "EzButtonProps": {
              "location": "import",
              "path": "./interfaces/EzButtonProps"
            }
          }
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Bot\u00F5es do rodap\u00E9 do popup. Aceita todas as propriedades do ez-button.\nLimitado a at\u00E9 3 bot\u00F5es."
        },
        "defaultValue": "[]"
      }
    };
  }
  static get states() {
    return {
      "_hasFooterSlotContent": {}
    };
  }
  static get events() {
    return [{
        "method": "ezClosePopup",
        "name": "ezClosePopup",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Evento emitido ao clicar no bot\u00E3o de fechar (onEzClosePopup)."
        },
        "complexType": {
          "original": "any",
          "resolved": "any",
          "references": {}
        }
      }, {
        "method": "ezPopupAction",
        "name": "ezPopupAction",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Evento emitido ao clicar no bot\u00E3o de fechar (ezPopupAction = OK)"
        },
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        }
      }];
  }
  static get elementRef() { return "_element"; }
  static get watchers() {
    return [{
        "propName": "opened",
        "methodName": "observeConfig"
      }];
  }
}
