import { computePosition, flip, shift } from "@floating-ui/dom";
import { h, Host } from "@stencil/core";
export class EzPopoverCore {
  constructor() {
    this.autoClose = true;
    this.boxWidth = "fit-content";
    this.opened = false;
    this.overlayType = "light";
    this.anchorElement = undefined;
    this.options = { horizontalGap: 0, verticalGap: 0, fromRight: false };
    this.useAnchorSize = false;
    this.minWidth = 150;
  }
  observeOpened(newValue, oldValue) {
    if (newValue === oldValue) {
      return;
    }
    if (newValue) {
      this.openPopover();
    }
    else {
      this.hidePopover();
    }
  }
  /**
   * Atualiza a posição do popover.
   */
  async updatePosition(top, left) {
    this.updateOptionPosition(top, left);
    await this.updatePositionPopover();
  }
  /**
   * Exibe o ez-popover.
   */
  async show(top, left) {
    this.updateOptionPosition(top, left);
    this.opened = true;
  }
  /**
   * Ancora a exibição do popOver a um elemento HTML.
   */
  async showUnder(element, options) {
    if (options) {
      this.options = options;
    }
    this.anchorElement = element;
    this.opened = true;
  }
  /**
   * Oculta o ez-popover.
   */
  async hide() {
    this.opened = false;
  }
  /**
   * Altera as opções.
  */
  async setOptions(options) {
    Object.assign(this.options, options);
  }
  /**
   * Altera o elemento de ancoragem.
  */
  async setAnchorElement(anchor) {
    this.anchorElement = anchor;
  }
  parseSizePixel(sizePixel, defaultValue) {
    if (!sizePixel) {
      return defaultValue !== null && defaultValue !== void 0 ? defaultValue : 0;
    }
    if (typeof sizePixel === "string") {
      return Number(sizePixel.replace("px", ""));
    }
    return sizePixel !== null && sizePixel !== void 0 ? sizePixel : 0;
  }
  updateOptionPosition(top, left) {
    Object.assign(this.options, {
      horizontalGap: this.parseSizePixel(left, this.options.horizontalGap),
      verticalGap: this.parseSizePixel(top, this.options.verticalGap),
    });
  }
  getElement(element) {
    if (typeof element === 'string') {
      return document.getElementById(element);
    }
    return element;
  }
  getAnchorElement() {
    if (!this.anchorElement) {
      return this._host;
    }
    if (Array.isArray(this.anchorElement)) {
      for (const element of this.anchorElement) {
        const htmlElement = this.getElement(element);
        if (htmlElement) {
          return htmlElement;
        }
      }
      return this._host;
    }
    return this.getElement(this.anchorElement);
  }
  async updatePositionPopover() {
    if (!this._box || !this.opened) {
      return;
    }
    const currentAnchorElement = this.getAnchorElement();
    await computePosition(currentAnchorElement, this._box, {
      placement: this.options.fromRight ? 'bottom-end' : 'bottom-start',
      middleware: [flip(), shift({ padding: 5 })],
      strategy: 'fixed',
    }).then(({ x, y, placement }) => {
      const newTop = placement.includes("bottom") ? y + this.options.verticalGap : y - this.options.verticalGap;
      const newLeft = placement.includes("start") ? x + this.options.horizontalGap : x - this.options.horizontalGap;
      Object.assign(this._box.style, {
        top: `${newTop}px`,
        left: `${newLeft}px`,
      });
    });
  }
  hidePopover() {
    if (!this._box) {
      return;
    }
    this._box.style.display = '';
    this.hideOverlay();
    this.ezVisibilityChange.emit(false);
  }
  async openPopover() {
    if (!this._box || !this.opened) {
      return;
    }
    this._box.style.display = 'flex';
    this._box.style.visibility = 'hidden';
    if (this.useAnchorSize) {
      const currentAnchorElement = this.getAnchorElement();
      const anchorSize = currentAnchorElement.getBoundingClientRect().width;
      const width = anchorSize < this.minWidth ? this.minWidth : anchorSize;
      this._box.style.width = `${width}px`;
    }
    await this.updatePositionPopover();
    this.openOverlay();
    this.ezVisibilityChange.emit(true);
    this._box.style.visibility = 'visible';
  }
  openOverlay() {
    if (!this._overlay || !this._overlayIsActive) {
      return;
    }
    this._overlay.style.display = 'block';
  }
  hideOverlay() {
    if (!this._overlay) {
      return;
    }
    this._overlay.style.display = 'none';
  }
  checkStatusOverlay() {
    if (this.overlayType !== "none") {
      return true;
    }
    if (this.overlayType === "none" && this.autoClose) {
      return true;
    }
    return false;
  }
  handlePositionUpdate() {
    if (!this.opened) {
      return;
    }
    this.updatePositionPopover();
  }
  componentWillLoad() {
    window.addEventListener('scroll', this.handlePositionUpdate.bind(this), true);
    window.addEventListener('resize', this.handlePositionUpdate.bind(this), true);
  }
  componentDidLoad() {
    this._overlayIsActive = this.checkStatusOverlay();
    this._resizeObserver = new ResizeObserver(this.updatePositionPopover.bind(this));
    this._resizeObserver.observe(this._box);
    this.openPopover();
  }
  disconnectedCallback() {
    window.removeEventListener('scroll', this.handlePositionUpdate.bind(this), true);
    window.removeEventListener('resize', this.handlePositionUpdate.bind(this), true);
    this._resizeObserver.disconnect();
  }
  render() {
    return (h(Host, null, h("div", { ref: el => this._overlay = el, onClick: () => this.hide(), class: `popover__overlay popover__overlay--${this.overlayType}` }), h("section", { ref: el => this._box = el, class: {
        "popover__box": true,
        "popover__box--fit-content": this.boxWidth === "fit-content",
        "popover__box--full-width": this.boxWidth !== "fit-content",
      } }, h("slot", null))));
  }
  static get is() { return "ez-popover-core"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["ez-popover-core.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["ez-popover-core.css"]
    };
  }
  static get properties() {
    return {
      "autoClose": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se 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,
        "defaultValue": "false"
      },
      "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\""
      },
      "anchorElement": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "Array<HTMLElement | string> | HTMLElement | string",
          "resolved": "(string | HTMLElement)[] | HTMLElement | string",
          "references": {
            "Array": {
              "location": "global"
            },
            "HTMLElement": {
              "location": "global"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define o elemento de ancoragem."
        },
        "attribute": "anchor-element",
        "reflect": true
      },
      "options": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "IEzPopoverAnchorOptions",
          "resolved": "IEzPopoverAnchorOptions",
          "references": {
            "IEzPopoverAnchorOptions": {
              "location": "local"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define as op\u00E7\u00F5es do elemento."
        },
        "defaultValue": "{ horizontalGap: 0, verticalGap: 0, fromRight: false }"
      },
      "useAnchorSize": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define se o elemento manter\u00E1 o mesmo tamanho do componente de ancora."
        },
        "attribute": "use-anchor-size",
        "reflect": true,
        "defaultValue": "false"
      },
      "minWidth": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Define a largura m\u00EDnima do elemento (apenas ser\u00E1 considerada caso a propriedade useAnchorSize seja verdadeira)."
        },
        "attribute": "min-width",
        "reflect": true,
        "defaultValue": "150"
      }
    };
  }
  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 | number, left?: string | number) => 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 | string, 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": []
        }
      },
      "setOptions": {
        "complexType": {
          "signature": "(options: IEzPopoverAnchorOptions) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "IEzPopoverAnchorOptions": {
              "location": "local"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Altera as op\u00E7\u00F5es.",
          "tags": []
        }
      },
      "setAnchorElement": {
        "complexType": {
          "signature": "(anchor: HTMLElement | string) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global"
            },
            "HTMLElement": {
              "location": "global"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Altera o elemento de ancoragem.",
          "tags": []
        }
      }
    };
  }
  static get elementRef() { return "_host"; }
  static get watchers() {
    return [{
        "propName": "opened",
        "methodName": "observeOpened"
      }];
  }
}
