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 _KlevuMoi_instances, _KlevuMoi_layoutRef, _KlevuMoi_modalRef, _KlevuMoi_sendMessage, _KlevuMoi_sendFilter, _KlevuMoi_buildChatFormat, _KlevuMoi_productClick;
import { Host, h } from "@stencil/core";
import { startMoi } from "@klevu/core";
import { KlevuInit } from "../klevu-init/klevu-init";
import { partsExports } from "../../utils/partsExports";
/**
 * Klevu MOI Application
 */
export class KlevuMoi {
  constructor() {
    _KlevuMoi_instances.add(this);
    _KlevuMoi_layoutRef.set(this, void 0);
    _KlevuMoi_modalRef.set(this, void 0);
    this.currentProduct = undefined;
    this.messages = [];
    this.loading = false;
    this.isShow = false;
    this.isOpen = false;
    this.apiKey = undefined;
    this.startOpen = undefined;
  }
  /** By default redirect the page if product click is not cancelled */
  onKlevuMoiProductClick(event) {
    setTimeout(() => {
      if (!event.defaultPrevented) {
        window.location.href = event.detail.url;
      }
    }, 1);
  }
  async connectedCallback() {
    await KlevuInit.ready();
    if (this.startOpen) {
      this.open();
    }
  }
  /**
   * Initialize the MOI session and open window
   */
  async open() {
    var _a;
    if (!this.session) {
      const config = await ((_a = this.el.closest("klevu-init")) === null || _a === void 0 ? void 0 : _a.getConfig());
      this.session = await startMoi({
        onMessage: this.onMessage.bind(this),
        // Do nothing on redirect as we have our own system
        onRedirect: (url) => { },
        settings: {
          configOverride: config,
        },
      });
    }
    this.messages = this.session.messages;
    this.isShow = true;
    this.klevuMoiVisibilityChange.emit("open");
    setTimeout(async () => {
      var _a;
      this.isOpen = true;
      await ((_a = __classPrivateFieldGet(this, _KlevuMoi_layoutRef, "f")) === null || _a === void 0 ? void 0 : _a.scrollMainToBottom("instant"));
    }, 50);
  }
  async close() {
    if (!this.isOpen) {
      return;
    }
    this.isOpen = false;
    this.klevuMoiVisibilityChange.emit("close");
    setTimeout(() => {
      this.isShow = false;
    }, 300);
  }
  onMessage() {
    var _a;
    if (!this.session) {
      return;
    }
    this.messages = this.session.messages;
    (_a = __classPrivateFieldGet(this, _KlevuMoi_layoutRef, "f")) === null || _a === void 0 ? void 0 : _a.scrollMainToBottom();
  }
  render() {
    var _a, _b, _c, _d;
    const popupClasses = {
      popup: true,
      show: this.isShow,
      open: this.isOpen,
    };
    if (!this.isShow) {
      return null;
    }
    return (h(Host, null, h("div", { class: popupClasses }, this.session && (h("klevu-chat-layout", { slot: "content", onKlevuChatLayoutMessageSent: (e) => __classPrivateFieldGet(this, _KlevuMoi_instances, "m", _KlevuMoi_sendMessage).call(this, e.detail), ref: (el) => {
        __classPrivateFieldSet(this, _KlevuMoi_layoutRef, el, "f");
      } }, h("div", { slot: "header" }, h("klevu-typography", { variant: "body-m-bold" }, "MOI"), h("klevu-button", { onClick: () => this.close(), size: "small", icon: "close", isSecondary: true })), h("klevu-chat-messages", { onKlevuSelectFilter: (event) => {
        __classPrivateFieldGet(this, _KlevuMoi_instances, "m", _KlevuMoi_sendFilter).call(this, event.detail.filter.value, __classPrivateFieldGet(this, _KlevuMoi_instances, "m", _KlevuMoi_buildChatFormat).call(this, event.detail.filter, event.detail.message.filter.settings));
      }, onKlevuSelectProductOption: (event) => {
        var _a;
        const option = event.detail.option;
        const product = event.detail.product;
        if (option.intent === "show-similar-products") {
          __classPrivateFieldGet(this, _KlevuMoi_instances, "m", _KlevuMoi_sendMessage).call(this, option.chat, {
            context: {
              url: product.url,
            },
            id: product.id,
            intent: option.intent,
          });
        }
        else if (option.intent === "quick-view") {
          this.currentProduct = product;
          (_a = __classPrivateFieldGet(this, _KlevuMoi_modalRef, "f")) === null || _a === void 0 ? void 0 : _a.openModal();
        }
      }, onKlevuChatProductClick: (event) => {
        event.preventDefault();
        event.stopPropagation();
        __classPrivateFieldGet(this, _KlevuMoi_instances, "m", _KlevuMoi_productClick).call(this, event.detail.product);
        return false;
      }, messages: this.messages }), this.loading && (h("klevu-loading-indicator", { exportparts: partsExports("klevu-loading-indicator") })), h("div", { slot: "actions", class: "genericactions" }, (_b = (_a = this.session) === null || _a === void 0 ? void 0 : _a.genericOptions) === null || _b === void 0 ? void 0 : _b.options.map((item) => (h("klevu-button", { size: "small", isSecondary: true, onClick: () => {
        var _a;
        if (item.type === "message") {
          __classPrivateFieldGet(this, _KlevuMoi_instances, "m", _KlevuMoi_sendMessage).call(this, item.chat);
        }
        else if (item.type === "clearChat") {
          (_a = this.session) === null || _a === void 0 ? void 0 : _a.clear();
        }
      } }, item.name)))), h("div", { slot: "menu", class: "menu" }, (_d = (_c = this.session) === null || _c === void 0 ? void 0 : _c.menu) === null || _d === void 0 ? void 0 : _d.options.filter((i) => i.type === "message").map((item) => (h("klevu-button", { onClick: () => {
        var _a;
        if (item.type === "message") {
          __classPrivateFieldGet(this, _KlevuMoi_instances, "m", _KlevuMoi_sendMessage).call(this, item.chat);
        }
        else {
          console.error("Not implemented yet");
        }
        (_a = __classPrivateFieldGet(this, _KlevuMoi_layoutRef, "f")) === null || _a === void 0 ? void 0 : _a.closePopup();
      } }, item.name))))))), h("klevu-modal", { ref: (el) => (__classPrivateFieldSet(this, _KlevuMoi_modalRef, el, "f")) }, h("klevu-product", { exportparts: partsExports("klevu-product"), product: this.currentProduct }))));
  }
  static get is() { return "klevu-moi"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["klevu-moi.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["klevu-moi.css"]
    };
  }
  static get properties() {
    return {
      "apiKey": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Override default API key"
        },
        "attribute": "api-key",
        "reflect": false
      },
      "startOpen": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Start the MOI window open"
        },
        "attribute": "start-open",
        "reflect": false
      }
    };
  }
  static get states() {
    return {
      "currentProduct": {},
      "messages": {},
      "loading": {},
      "isShow": {},
      "isOpen": {}
    };
  }
  static get events() {
    return [{
        "method": "klevuMoiProductClick",
        "name": "klevuMoiProductClick",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [{
              "name": "param",
              "text": "product"
            }],
          "text": "When a product is clicked. By default does a full page redirect to product url if event is not cancelled.\n\nUse `event.preventDefault()` to cancel the redirect."
        },
        "complexType": {
          "original": "MoiProduct",
          "resolved": "{ id: string; currency: string; image: string; itemGroupId: string; name: string; noOfVariants: number; options: { chat: string; intent: string; name: string; }[]; originalContent: string | null; price: string; salePrice: string; shortDesc: string; url: string; }",
          "references": {
            "MoiProduct": {
              "location": "import",
              "path": "@klevu/core",
              "id": "../klevu-core/dist/cjs/index.d.ts::MoiProduct"
            }
          }
        }
      }, {
        "method": "klevuMoiVisibilityChange",
        "name": "klevuMoiVisibilityChange",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "When the visibility of Moi window changes"
        },
        "complexType": {
          "original": "\"open\" | \"close\"",
          "resolved": "\"close\" | \"open\"",
          "references": {}
        }
      }];
  }
  static get methods() {
    return {
      "open": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global",
              "id": "global::Promise"
            },
            "KlevuConfig": {
              "location": "import",
              "path": "@klevu/core",
              "id": "../klevu-core/dist/cjs/index.d.ts::KlevuConfig"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "Initialize the MOI session and open window",
          "tags": []
        }
      },
      "close": {
        "complexType": {
          "signature": "() => Promise<void>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global",
              "id": "global::Promise"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      }
    };
  }
  static get elementRef() { return "el"; }
  static get listeners() {
    return [{
        "name": "klevuMoiProductClick",
        "method": "onKlevuMoiProductClick",
        "target": undefined,
        "capture": false,
        "passive": false
      }];
  }
}
_KlevuMoi_layoutRef = new WeakMap(), _KlevuMoi_modalRef = new WeakMap(), _KlevuMoi_instances = new WeakSet(), _KlevuMoi_sendMessage = async function _KlevuMoi_sendMessage(msg, product) {
  var _a;
  if (!this.session) {
    return;
  }
  this.loading = true;
  await this.session.query({
    message: msg,
    product,
  });
  this.loading = false;
  (_a = __classPrivateFieldGet(this, _KlevuMoi_layoutRef, "f")) === null || _a === void 0 ? void 0 : _a.scrollMainToBottom();
}, _KlevuMoi_sendFilter = async function _KlevuMoi_sendFilter(filterValue, message) {
  var _a;
  if (!this.session) {
    return;
  }
  await this.session.query({
    message,
    filter: {
      value: filterValue,
    },
  });
  (_a = __classPrivateFieldGet(this, _KlevuMoi_layoutRef, "f")) === null || _a === void 0 ? void 0 : _a.scrollMainToBottom();
}, _KlevuMoi_buildChatFormat = function _KlevuMoi_buildChatFormat(target, settings) {
  if (settings.key && (target === null || target === void 0 ? void 0 : target.value) === `${settings.key}:klevu_any`) {
    return settings.chatFormatEmpty;
  }
  if (target && target.name && settings.chatFormat) {
    return settings.chatFormat.replace(`$VALUE$`, target.name);
  }
  return undefined;
}, _KlevuMoi_productClick = async function _KlevuMoi_productClick(product) {
  if (!this.session || !product.id || !product.url) {
    return;
  }
  this.loading = true;
  await this.session.query({
    product: {
      id: product.id,
      context: {
        url: product.url,
      },
      intent: "redirect",
    },
  });
  this.loading = false;
  this.klevuMoiProductClick.emit(product);
};
//# sourceMappingURL=klevu-moi.js.map
