import { h, Host } from "@stencil/core";
import { FloatingManager } from "@sankhyalabs/core";
export class EzPopover {
  constructor() {
    this._firstRender = true;
    this.innerClickTest = (_popOvercontainer, node, eventOrigin) => {
      const innerContainers = [_popOvercontainer];
      if (this.innerElement) {
        if (typeof (this.innerElement) == "string") {
          innerContainers.push(document.querySelector(`#${this.innerElement}`));
        }
        else {
          this.innerElement.forEach(comp => {
            innerContainers.push(document.querySelector(`#${comp}`));
          });
        }
      }
      const eventPath = (eventOrigin === null || eventOrigin === void 0 ? void 0 : eventOrigin.composedPath()) || [];
      for (var i = 0; i < innerContainers.length; i++) {
        let _container = innerContainers[i];
        if (_container != undefined) {
          if (eventPath.includes(_container)) {
            return true;
          }
          if (_container.contains(node)) {
            return true;
          }
          if (eventOrigin && "nodeType" in (eventOrigin === null || eventOrigin === void 0 ? void 0 : eventOrigin.target) && _container.contains(eventOrigin.target)) {
            return true;
          }
          if (_container.shadowRoot && _container.shadowRoot.contains(node)) {
            return true;
          }
          _container = this._host;
          if (!_container.lastElementChild.shadowRoot ? _container.contains(node) : _container.lastElementChild.shadowRoot.contains(node)) {
            return true;
          }
        }
      }
      return false;
    };
    this.backClickListener = () => {
      this.ezVisibilityChange.emit(false);
    };
    this.autoClose = true;
    this.boxWidth = "fit-content";
    this.opened = undefined;
    this.innerElement = undefined;
    this.overlayType = "light";
  }
  observeOpened(newValue, oldValue) {
    if (newValue != oldValue) {
      if (oldValue) {
        this.hide();
      }
      else {
        this.show();
      }
      this.ezVisibilityChange.emit(newValue);
    }
  }
  /**
   * Atualiza a posição do popover.
   */
  async updatePosition(top, left) {
    const floatingOptions = {
      autoClose: this.autoClose,
      top,
      left,
      innerClickTest: this.innerClickTest,
      backClickListener: this.backClickListener
    };
    FloatingManager.updateFloatPosition(this._box, this._container, floatingOptions);
  }
  /**
   * Exibe o ez-popover.
   */
  async show(top, left) {
    this.float({ top, left });
  }
  /**
   * Ancora a exibição do popOver a um elemento HTML.
   */
  async showUnder(element, options) {
    if (element && this._host) {
      this.float(this.calculatePosition(element, Object.assign({ verticalGap: 0, horizontalGap: 0, fromRight: false }, options)));
    }
    else {
      const top = (options === null || options === void 0 ? void 0 : options.verticalGap) ? `${options.verticalGap}px` : undefined;
      const left = (options === null || options === void 0 ? void 0 : options.horizontalGap) ? `${options.horizontalGap}px` : undefined;
      this.show(top, left);
    }
  }
  calculatePosition(element, options) {
    const boxRect = this._host.getBoundingClientRect();
    const anchorRect = element.getBoundingClientRect();
    const yOffset = anchorRect.bottom - boxRect.y;
    const xOffset = options.fromRight ? boxRect.right - anchorRect.right : anchorRect.x - boxRect.x;
    const yProperty = `${yOffset + options.verticalGap}px`;
    const xProperty = `${xOffset + options.horizontalGap}px`;
    return {
      top: yProperty,
      left: options.fromRight ? "" : xProperty,
      right: options.fromRight ? xProperty : ""
    };
  }
  float(position) {
    this._box.style.top = "";
    this._box.style.left = "";
    this._box.style.right = "";
    const useOverlay = this.overlayType !== "none";
    const overlayClassName = `ez-scrim ez-scrim--${this.overlayType}`;
    let floatingOptions = Object.assign(Object.assign({}, position), { autoClose: this.autoClose, innerClickTest: this.innerClickTest, backClickListener: this.backClickListener });
    if (useOverlay) {
      floatingOptions = Object.assign(Object.assign({}, floatingOptions), { autoClose: true, useOverlay,
        overlayClassName });
    }
    this._floatingID = FloatingManager.float(this._box, this._container, floatingOptions);
    this.opened = true;
  }
  /**
   * Oculta o ez-popover.
   */
  async hide() {
    if (this._floatingID !== undefined) {
      FloatingManager.close(this._floatingID);
      this._floatingID = undefined;
      this.opened = false;
    }
  }
  componentDidRender() {
    if (this._firstRender) {
      this._box.remove();
      this._firstRender = false;
    }
  }
  render() {
    return (h(Host, null, h("section", { ref: el => this._container = el }, h("div", { class: `popover__box ${this.boxWidth === "fit-content" ? "popover__box--fit-content" : "popover__box--full-width"}`, ref: el => this._box = el }, h("slot", null)))));
  }
  static get is() { return "ez-popover"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["ez-popover.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["ez-popover.css"]
    };
  }
  static get properties() {
    return {
      "autoClose": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define que ser\u00E1 fechado automaticamente quando o usu\u00E1rio clicar fora do conte\u00FAdo."
        },
        "attribute": "auto-close",
        "reflect": true,
        "defaultValue": "true"
      },
      "boxWidth": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "\"full-width\" | \"fit-content\"",
          "resolved": "\"fit-content\" | \"full-width\"",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Ajusta o comportamento da largura do popover."
        },
        "attribute": "box-width",
        "reflect": true,
        "defaultValue": "\"fit-content\""
      },
      "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
      },
      "innerElement": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "Array<string> | string",
          "resolved": "string | string[]",
          "references": {
            "Array": {
              "location": "global"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define as tags que ser\u00E3o consideradas conte\u00FAdo."
        },
        "attribute": "inner-element",
        "reflect": true
      },
      "overlayType": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "\"medium\" | \"light\" | \"none\"",
          "resolved": "\"light\" | \"medium\" | \"none\"",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o tipo de overlay do popover."
        },
        "attribute": "overlay-type",
        "reflect": true,
        "defaultValue": "\"light\""
      }
    };
  }
  static get events() {
    return [{
        "method": "ezVisibilityChange",
        "name": "ezVisibilityChange",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "Emitido quando acontece a altera\u00E7\u00E3o de estado do componente."
        },
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        }
      }];
  }
  static get methods() {
    return {
      "updatePosition": {
        "complexType": {
          "signature": "(top?: string, left?: string) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Atualiza a posi\u00E7\u00E3o do popover.",
          "tags": []
        }
      },
      "show": {
        "complexType": {
          "signature": "(top?: string, left?: string) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Exibe o ez-popover.",
          "tags": []
        }
      },
      "showUnder": {
        "complexType": {
          "signature": "(element: HTMLElement, options?: IEzPopoverAnchorOptions) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }, {
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "HTMLElement": {
              "location": "global"
            },
            "IEzPopoverAnchorOptions": {
              "location": "local"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Ancora a exibi\u00E7\u00E3o do popOver a um elemento HTML.",
          "tags": []
        }
      },
      "hide": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Oculta o ez-popover.",
          "tags": []
        }
      }
    };
  }
  static get elementRef() { return "_host"; }
  static get watchers() {
    return [{
        "propName": "opened",
        "methodName": "observeOpened"
      }];
  }
}
