var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
  if (kind === "a" && !f)
    throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
    throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
  if (kind === "m")
    throw new TypeError("Private method is not writable");
  if (kind === "a" && !f)
    throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
    throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var _KlevuPopup_instances, _KlevuPopup_stopUpdatePos, _KlevuPopup_originElement, _KlevuPopup_contentElement, _KlevuPopup_closeEvent, _KlevuPopup_internalOpen, _KlevuPopup_updatePopupPosition, _KlevuPopup_childItemClicked, _KlevuPopup_childItemFocussed, _KlevuPopup_backdropClick, _KlevuPopup_attachBackdropClick, _KlevuPopup_detachBackdropClick;
import { autoUpdate, computePosition, offset, shift, size } from "@floating-ui/dom";
import { h, Host } from "@stencil/core";
/**
 * Popup component where clicking origin component popups the the content
 *
 * @slot origin - Popoup origin that opens content of popup
 * @slot content - Content of the popup
 *
 * @csspart popup-base The container for the popup
 * @csspart popup-content Content component
 */
export class KlevuPopup {
  constructor() {
    _KlevuPopup_instances.add(this);
    _KlevuPopup_stopUpdatePos.set(this, void 0);
    _KlevuPopup_originElement.set(this, void 0);
    _KlevuPopup_contentElement.set(this, void 0);
    this.startOpen = undefined;
    this.toggle = undefined;
    this.openAtFocus = true;
    this.closeAtOutsideClick = true;
    this.anchor = "left-end";
    this.elevation = 1;
    this.offset = 16;
    this.useBackground = false;
    this.originElement = undefined;
    this.fullscreenOnMobileSize = undefined;
    this.fullWidthOrigin = undefined;
  }
  /**
   * Opens the popup
   */
  async openModal() {
    __classPrivateFieldGet(this, _KlevuPopup_instances, "m", _KlevuPopup_internalOpen).call(this);
  }
  /**
   * Closes the popup
   */
  async closeModal() {
    var _a;
    const event = this.klevuPopupClose.emit();
    if (!event.defaultPrevented) {
      __classPrivateFieldGet(this, _KlevuPopup_instances, "m", _KlevuPopup_detachBackdropClick).call(this);
      (_a = this.dialogRef) === null || _a === void 0 ? void 0 : _a.close();
    }
  }
  componentDidLoad() {
    var _a, _b, _c, _d;
    if (this.originElement) {
      this.originElement.addEventListener("click", (event) => {
        this.openModal();
        event.preventDefault();
        event.stopPropagation();
        return false;
      });
    }
    __classPrivateFieldSet(this, _KlevuPopup_originElement, this.originElement || ((_b = (_a = this.el) === null || _a === void 0 ? void 0 : _a.shadowRoot) === null || _b === void 0 ? void 0 : _b.querySelector("#origin")), "f");
    __classPrivateFieldSet(this, _KlevuPopup_contentElement, (_d = (_c = this.el) === null || _c === void 0 ? void 0 : _c.shadowRoot) === null || _d === void 0 ? void 0 : _d.querySelector("dialog"), "f");
    if (this.startOpen) {
      this.openModal();
    }
    if (__classPrivateFieldGet(this, _KlevuPopup_originElement, "f") && __classPrivateFieldGet(this, _KlevuPopup_contentElement, "f")) {
      __classPrivateFieldSet(this, _KlevuPopup_stopUpdatePos, autoUpdate(__classPrivateFieldGet(this, _KlevuPopup_originElement, "f"), __classPrivateFieldGet(this, _KlevuPopup_contentElement, "f"), __classPrivateFieldGet(this, _KlevuPopup_instances, "m", _KlevuPopup_updatePopupPosition).bind(this)), "f");
    }
  }
  detachedCallback() {
    var _a;
    __classPrivateFieldGet(this, _KlevuPopup_instances, "m", _KlevuPopup_detachBackdropClick).call(this);
    (_a = __classPrivateFieldGet(this, _KlevuPopup_stopUpdatePos, "f")) === null || _a === void 0 ? void 0 : _a.call(this);
  }
  render() {
    const popupClasses = {
      popup: true,
    };
    popupClasses[`elevation-${this.elevation}`] = true;
    const originClasses = {
      originContainer: true,
      fullWidthOrigin: Boolean(this.fullWidthOrigin),
    };
    return (h(Host, null, h("div", { id: "origin", part: "popup-base", onClick: __classPrivateFieldGet(this, _KlevuPopup_instances, "m", _KlevuPopup_childItemClicked).bind(this), onFocus: __classPrivateFieldGet(this, _KlevuPopup_instances, "m", _KlevuPopup_childItemFocussed).bind(this), class: originClasses }, h("slot", { name: "origin" })), h("dialog", { part: "popup-content", open: this.startOpen, ref: (el) => (this.dialogRef = el), class: popupClasses }, h("slot", { name: "content" }))));
  }
  static get is() { return "klevu-popup"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["klevu-popup.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["klevu-popup.css"]
    };
  }
  static get properties() {
    return {
      "startOpen": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Initially show the popup"
        },
        "attribute": "start-open",
        "reflect": false
      },
      "toggle": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Clicking origin again will close the popup"
        },
        "attribute": "toggle",
        "reflect": false
      },
      "openAtFocus": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Open content when origin component is focused"
        },
        "attribute": "open-at-focus",
        "reflect": false,
        "defaultValue": "true"
      },
      "closeAtOutsideClick": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Close popup when clicking outside content area"
        },
        "attribute": "close-at-outside-click",
        "reflect": false,
        "defaultValue": "true"
      },
      "anchor": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "Placement",
          "resolved": "\"bottom\" | \"bottom-end\" | \"bottom-start\" | \"left\" | \"left-end\" | \"left-start\" | \"right\" | \"right-end\" | \"right-start\" | \"top\" | \"top-end\" | \"top-start\"",
          "references": {
            "Placement": {
              "location": "import",
              "path": "@floating-ui/dom",
              "id": ""
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Anchor popup to left or right of page"
        },
        "attribute": "anchor",
        "reflect": false,
        "defaultValue": "\"left-end\""
      },
      "elevation": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Elevation of the popup. 0-3."
        },
        "attribute": "elevation",
        "reflect": false,
        "defaultValue": "1"
      },
      "offset": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "How many pixels to offset the popup from origin"
        },
        "attribute": "offset",
        "reflect": false,
        "defaultValue": "16"
      },
      "useBackground": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Darken background when popup is open"
        },
        "attribute": "use-background",
        "reflect": false,
        "defaultValue": "false"
      },
      "originElement": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "HTMLElement",
          "resolved": "HTMLElement | undefined",
          "references": {
            "HTMLElement": {
              "location": "global",
              "id": "global::HTMLElement"
            }
          }
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Element to anchor popup to. If not set popup is anchored to origin slot"
        }
      },
      "fullscreenOnMobileSize": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Expand popup to full size of the screen when popup is smaller that requested width"
        },
        "attribute": "fullscreen-on-mobile-size",
        "reflect": false
      },
      "fullWidthOrigin": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Sets origin element to full width of the container"
        },
        "attribute": "full-width-origin",
        "reflect": false
      }
    };
  }
  static get events() {
    return [{
        "method": "klevuPopupOpen",
        "name": "klevuPopupOpen",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "When popup is opened this event is emitted"
        },
        "complexType": {
          "original": "void",
          "resolved": "void",
          "references": {}
        }
      }, {
        "method": "klevuPopupClose",
        "name": "klevuPopupClose",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "void",
          "resolved": "void",
          "references": {}
        }
      }];
  }
  static get methods() {
    return {
      "openModal": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global",
              "id": "global::Promise"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Opens the popup",
          "tags": []
        }
      },
      "closeModal": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global",
              "id": "global::Promise"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Closes the popup",
          "tags": []
        }
      }
    };
  }
  static get elementRef() { return "el"; }
}
_KlevuPopup_stopUpdatePos = new WeakMap(), _KlevuPopup_originElement = new WeakMap(), _KlevuPopup_contentElement = new WeakMap(), _KlevuPopup_instances = new WeakSet(), _KlevuPopup_closeEvent = function _KlevuPopup_closeEvent(event) {
  if (!event.composedPath().some((el) => {
    const elem = el;
    return elem.tagName === "klevu-popup".toLocaleUpperCase();
  }) &&
    event.target !== __classPrivateFieldGet(this, _KlevuPopup_originElement, "f")) {
    this.closeModal();
  }
}, _KlevuPopup_internalOpen = async function _KlevuPopup_internalOpen() {
  var _a, _b, _c;
  if (this.toggle && ((_a = this.dialogRef) === null || _a === void 0 ? void 0 : _a.open)) {
    this.closeModal();
    return;
  }
  if (this.useBackground) {
    (_b = this.dialogRef) === null || _b === void 0 ? void 0 : _b.showModal();
  }
  else {
    (_c = this.dialogRef) === null || _c === void 0 ? void 0 : _c.show();
  }
  __classPrivateFieldGet(this, _KlevuPopup_instances, "m", _KlevuPopup_updatePopupPosition).call(this);
  __classPrivateFieldGet(this, _KlevuPopup_instances, "m", _KlevuPopup_attachBackdropClick).call(this);
  this.klevuPopupOpen.emit();
}, _KlevuPopup_updatePopupPosition = async function _KlevuPopup_updatePopupPosition() {
  var _a;
  if (!__classPrivateFieldGet(this, _KlevuPopup_originElement, "f") || !__classPrivateFieldGet(this, _KlevuPopup_contentElement, "f") || !((_a = this.dialogRef) === null || _a === void 0 ? void 0 : _a.open)) {
    return;
  }
  let popupWidth = parseInt(getComputedStyle(this.dialogRef).getPropertyValue("--width"));
  if (isNaN(popupWidth)) {
    popupWidth = undefined;
  }
  const smallScreen = (popupWidth !== null && popupWidth !== void 0 ? popupWidth : 390) > document.body.clientWidth;
  if (smallScreen && this.fullscreenOnMobileSize) {
    Object.assign(__classPrivateFieldGet(this, _KlevuPopup_contentElement, "f").style, {
      left: "0px",
      top: "0px",
      position: "fixed",
      maxHeight: "100dvh",
      maxWidth: "100%",
      width: "100%",
      height: "100dvh",
    });
  }
  else {
    const { x, y } = await computePosition(__classPrivateFieldGet(this, _KlevuPopup_originElement, "f"), __classPrivateFieldGet(this, _KlevuPopup_contentElement, "f"), {
      strategy: "fixed",
      placement: this.anchor,
      middleware: [
        offset(this.offset),
        shift(),
        size({
          apply: ({ availableWidth, elements }) => {
            let maxWidth = availableWidth;
            if (popupWidth && popupWidth < availableWidth) {
              maxWidth = popupWidth;
            }
            Object.assign(elements.floating.style, {
              maxWidth: `${maxWidth}px`,
            });
          },
        }),
      ],
    });
    Object.assign(__classPrivateFieldGet(this, _KlevuPopup_contentElement, "f").style, {
      left: `${x}px`,
      top: `${y}px`,
      position: null,
      height: null,
      width: null,
    });
  }
}, _KlevuPopup_childItemClicked = function _KlevuPopup_childItemClicked(event) {
  if (event.defaultPrevented) {
    return;
  }
  __classPrivateFieldGet(this, _KlevuPopup_instances, "m", _KlevuPopup_internalOpen).call(this);
  event.preventDefault();
  event.stopPropagation();
  return false;
}, _KlevuPopup_childItemFocussed = function _KlevuPopup_childItemFocussed(event) {
  if (!this.openAtFocus) {
    return;
  }
  if (event.defaultPrevented) {
    return;
  }
  __classPrivateFieldGet(this, _KlevuPopup_instances, "m", _KlevuPopup_internalOpen).call(this);
  event.preventDefault();
  event.stopPropagation();
  return false;
}, _KlevuPopup_backdropClick = function _KlevuPopup_backdropClick(event) {
  if (!this.dialogRef || !this.dialogRef.open) {
    return;
  }
  const rect = this.dialogRef.getBoundingClientRect();
  const isInDialog = rect.top <= event.clientY &&
    event.clientY <= rect.top + rect.height &&
    rect.left <= event.clientX &&
    event.clientX <= rect.left + rect.width;
  const eventTarget = event.target;
  if (!isInDialog && (eventTarget === null || eventTarget === void 0 ? void 0 : eventTarget.tagName) === "DIALOG") {
    this.dialogRef.close();
  }
}, _KlevuPopup_attachBackdropClick = function _KlevuPopup_attachBackdropClick() {
  var _a;
  if (this.closeAtOutsideClick && this.useBackground) {
    (_a = this.dialogRef) === null || _a === void 0 ? void 0 : _a.addEventListener("click", __classPrivateFieldGet(this, _KlevuPopup_instances, "m", _KlevuPopup_backdropClick).bind(this));
  }
  else if (this.closeAtOutsideClick) {
    document.addEventListener("click", __classPrivateFieldGet(this, _KlevuPopup_instances, "m", _KlevuPopup_closeEvent).bind(this));
  }
}, _KlevuPopup_detachBackdropClick = function _KlevuPopup_detachBackdropClick() {
  var _a;
  if (this.closeAtOutsideClick && this.useBackground) {
    (_a = this.dialogRef) === null || _a === void 0 ? void 0 : _a.removeEventListener("click", __classPrivateFieldGet(this, _KlevuPopup_instances, "m", _KlevuPopup_backdropClick).bind(this));
  }
  else if (this.closeAtOutsideClick) {
    document.removeEventListener("click", __classPrivateFieldGet(this, _KlevuPopup_instances, "m", _KlevuPopup_closeEvent));
  }
};
//# sourceMappingURL=klevu-popup.js.map
