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, Fragment } from "@stencil/core";
import { globalExportedParts } from "../../utils/utils";
import { startMoi } from "@klevu/core";
import { KlevuInit } from "../klevu-init/klevu-init";
/**
 * 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.showClose = false;
    this.apiKey = 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() {
    var _a;
    await KlevuInit.ready();
    const config = await ((_a = this.el.closest("klevu-init")) === null || _a === void 0 ? void 0 : _a.getConfig());
    const init = async () => {
      this.session = await startMoi({
        onMessage: this.onMessage.bind(this),
        // Do nothing on redirect as we have our own system
        onRedirect: (url) => { },
        configOverride: config,
      });
      this.messages = this.session.messages;
    };
    init();
  }
  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;
    return (h(Host, null, h("klevu-chat-layout", { exportparts: globalExportedParts, onKlevuChatLayoutMessageSent: (e) => __classPrivateFieldGet(this, _KlevuMoi_instances, "m", _KlevuMoi_sendMessage).call(this, e.detail), ref: (el) => {
        __classPrivateFieldSet(this, _KlevuMoi_layoutRef, el, "f");
      }, showClose: this.showClose }, this.renderChatContent(), this.loading && h("klevu-loading-indicator", null), h("br", null), 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", { exportparts: globalExportedParts, ref: (el) => (__classPrivateFieldSet(this, _KlevuMoi_modalRef, el, "f")) }, h("klevu-product", { product: this.currentProduct }))));
  }
  renderChatContent() {
    return (h(Fragment, null, this.messages.map((message, index) => {
      var _a;
      if ("message" in message) {
        return (h(Fragment, null, h("klevu-chat-bubble", { remote: true, exportparts: globalExportedParts }, message.message.value), message.message.note && (h("klevu-typography", { style: {
            "--klevu-typography-color": "var(--klevu-color-neutral-6)",
          }, variant: "body-xs" }, message.message.note))));
      }
      if ("filter" in message) {
        return (h(Fragment, null, message.filter.settings.label && (h("klevu-chat-bubble", { remote: true, exportparts: globalExportedParts }, message.filter.settings.label)), h("div", { class: "filteractions" }, message.filter.options.map((o) => (h("klevu-button", { isSecondary: true, disabled: this.messages.length - 1 !== index, onClick: () => {
            if (this.messages.length - 1 === index) {
              __classPrivateFieldGet(this, _KlevuMoi_instances, "m", _KlevuMoi_sendFilter).call(this, o.value, __classPrivateFieldGet(this, _KlevuMoi_instances, "m", _KlevuMoi_buildChatFormat).call(this, o, message.filter.settings));
            }
          } }, o.name)))), message.filter.note && (h("klevu-typography", { style: {
            "--klevu-typography-color": "var(--klevu-color-neutral-6)",
          }, variant: "body-xs" }, message.filter.note))));
      }
      if ("productData" in message) {
        return (h("div", null, h("klevu-slides", { exportparts: globalExportedParts, style: {
            "--klevu-slides-item-width": "200px;",
          } }, message.productData.products.map((product) => (h("klevu-product", { product: product, hideSwatches: true, onKlevuProductClick: (event) => {
            event.preventDefault();
            event.stopPropagation();
            __classPrivateFieldGet(this, _KlevuMoi_instances, "m", _KlevuMoi_productClick).call(this, product);
            return false;
          } }, h("div", { slot: "bottom", class: "productactions" }, product.options.map((option) => (h("klevu-button", { fullWidth: true, isSecondary: true, onClick: () => {
            var _a;
            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();
            }
          } }, option.name)))))))), message.productData.note && (h("klevu-typography", { style: {
            "--klevu-typography-color": "var(--klevu-color-neutral-6)",
          }, variant: "body-xs" }, message.productData.note))));
      }
      if ("local" in message) {
        return h("klevu-chat-bubble", { exportparts: globalExportedParts }, (_a = message.local) === null || _a === void 0 ? void 0 : _a.message);
      }
    })));
  }
  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 {
      "showClose": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Show close button"
        },
        "attribute": "show-close",
        "reflect": false,
        "defaultValue": "false"
      },
      "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
      }
    };
  }
  static get states() {
    return {
      "currentProduct": {},
      "messages": {},
      "loading": {}
    };
  }
  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": "local",
              "path": "/home/runner/work/frontend-sdk/frontend-sdk/packages/klevu-ui/src/components/klevu-moi/klevu-moi.tsx"
            }
          }
        }
      }];
  }
  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
