import { proxyCustomElement, HTMLElement, createEvent, h, Host, Fragment } from '@stencil/core/internal/client';
import { g as globalExportedParts } from './utils.js';
import { a as KlevuConfig, p as post, K as KlevuInit } from './klevu-init2.js';
import { d as defineCustomElement$b } from './klevu-button2.js';
import { d as defineCustomElement$a } from './klevu-chat-bubble2.js';
import { d as defineCustomElement$9 } from './klevu-chat-layout2.js';
import { d as defineCustomElement$8 } from './klevu-loading-indicator2.js';
import { d as defineCustomElement$7 } from './klevu-modal2.js';
import { d as defineCustomElement$6 } from './klevu-popup2.js';
import { d as defineCustomElement$5 } from './klevu-product2.js';
import { d as defineCustomElement$4 } from './klevu-slides2.js';
import { d as defineCustomElement$3 } from './klevu-textfield2.js';
import { d as defineCustomElement$2 } from './klevu-typography2.js';
import { d as defineCustomElement$1 } from './klevu-util-scrollbars2.js';

var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
const STORAGE_KEY = "klevu-moi-session";
function startMoi({ onMessage, onRedirect, configOverride, } = {}) {
    return __awaiter(this, void 0, void 0, function* () {
        const config = configOverride || KlevuConfig.getDefault();
        const storedSession = yield getStoredSession();
        const result = yield queryMoi({
            context: {
                klevuApiKey: config.apiKey,
                sessionId: storedSession === null || storedSession === void 0 ? void 0 : storedSession.sessionId,
            },
        }, config);
        const ctx = result === null || result === void 0 ? void 0 : result.data[0];
        if (!ctx) {
            throw new Error("No context found");
        }
        const sessionId = ctx.context.sessionId;
        let startingMessages = [];
        if (storedSession) {
            startingMessages = storedSession.messages;
        }
        const { messages, genericOptions, menu } = parseResponse(result);
        startingMessages = [...startingMessages, ...messages];
        const session = {
            query(request) {
                return __awaiter(this, void 0, void 0, function* () {
                    if (request.message) {
                        this.messages = [
                            ...this.messages,
                            { local: { message: request.message } },
                        ];
                        onMessage === null || onMessage === void 0 ? void 0 : onMessage();
                    }
                    const res = yield queryMoi(Object.assign(Object.assign({}, request), { context: {
                            klevuApiKey: config.apiKey,
                            sessionId,
                        } }), config);
                    if (!res) {
                        throw new Error("No response from MOI");
                    }
                    // run actions first
                    for (const obj of res.data) {
                        if ("actions" in obj) {
                            for (const action of obj.actions.actions) {
                                if (action.type === "purgeHistory") {
                                    this.clear();
                                }
                                else if (action.type === "redirectToUrl" && action.context.link) {
                                    if (onRedirect) {
                                        onRedirect(action.context.link);
                                    }
                                    else {
                                        window.location.href = action.context.link;
                                    }
                                }
                            }
                        }
                    }
                    const { messages, genericOptions, menu } = parseResponse(res);
                    this.messages = [...this.messages, ...messages];
                    onMessage === null || onMessage === void 0 ? void 0 : onMessage();
                    this.genericOptions = genericOptions;
                    this.menu = menu;
                    saveSession({
                        sessionId,
                        messages: this.messages,
                    });
                    return res;
                });
            },
            clear() {
                this.messages = [];
                saveSession({
                    sessionId,
                    messages: this.messages,
                });
                onMessage === null || onMessage === void 0 ? void 0 : onMessage();
            },
            messages: startingMessages,
            genericOptions,
            menu,
        };
        return session;
    });
}
function getStoredSession() {
    const storedSession = localStorage.getItem(STORAGE_KEY);
    if (!storedSession) {
        return undefined;
    }
    const session = JSON.parse(storedSession);
    return session;
}
function saveSession(session) {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(session));
}
function queryMoi(request, config) {
    return __awaiter(this, void 0, void 0, function* () {
        return yield post(`${config.moiApiUrl}chat/send`, request);
    });
}
function parseResponse(response) {
    const messages = [];
    let genericOptions = undefined;
    let menu = undefined;
    for (const d of response.data) {
        "message" in d && messages.push(d);
        "filter" in d && messages.push(d);
        "productData" in d && messages.push(d);
        if ("genericOptions" in d) {
            genericOptions = d.genericOptions;
        }
        if ("menuOptions" in d) {
            menu = d.menuOptions;
        }
    }
    return {
        messages,
        menu,
        genericOptions,
    };
}

const klevuMoiCss = ":host{display:block;--klevu-slides-item-width:200px}klevu-chat-layout{height:100%}.filteractions{display:flex;flex-direction:row;flex-wrap:wrap;gap:var(--klevu-spacing-03)}.menu{display:flex;flex-direction:column;gap:var(--klevu-spacing-03)}.productactions{display:flex;flex-direction:column;gap:var(--klevu-spacing-02)}.genericactions{margin:var(--klevu-spacing-03) 0;display:flex;flex-direction:row;gap:var(--klevu-spacing-03);flex-wrap:wrap;justify-content:center}.genericactions klevu-button{--klevu-button-padding:5px}";

var __classPrivateFieldGet = (undefined && undefined.__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 = (undefined && undefined.__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;
const KlevuMoi = /*@__PURE__*/ proxyCustomElement(class KlevuMoi extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.__attachShadow();
    this.klevuMoiProductClick = createEvent(this, "klevuMoiProductClick", 7);
    _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);
      }
    })));
  }
  get el() { return this; }
  static get style() { return klevuMoiCss; }
}, [1, "klevu-moi", {
    "showClose": [4, "show-close"],
    "apiKey": [1, "api-key"],
    "currentProduct": [32],
    "messages": [32],
    "loading": [32]
  }, [[0, "klevuMoiProductClick", "onKlevuMoiProductClick"]]]);
_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);
};
function defineCustomElement() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["klevu-moi", "klevu-button", "klevu-chat-bubble", "klevu-chat-layout", "klevu-loading-indicator", "klevu-modal", "klevu-popup", "klevu-product", "klevu-slides", "klevu-textfield", "klevu-typography", "klevu-util-scrollbars"];
  components.forEach(tagName => { switch (tagName) {
    case "klevu-moi":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, KlevuMoi);
      }
      break;
    case "klevu-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$b();
      }
      break;
    case "klevu-chat-bubble":
      if (!customElements.get(tagName)) {
        defineCustomElement$a();
      }
      break;
    case "klevu-chat-layout":
      if (!customElements.get(tagName)) {
        defineCustomElement$9();
      }
      break;
    case "klevu-loading-indicator":
      if (!customElements.get(tagName)) {
        defineCustomElement$8();
      }
      break;
    case "klevu-modal":
      if (!customElements.get(tagName)) {
        defineCustomElement$7();
      }
      break;
    case "klevu-popup":
      if (!customElements.get(tagName)) {
        defineCustomElement$6();
      }
      break;
    case "klevu-product":
      if (!customElements.get(tagName)) {
        defineCustomElement$5();
      }
      break;
    case "klevu-slides":
      if (!customElements.get(tagName)) {
        defineCustomElement$4();
      }
      break;
    case "klevu-textfield":
      if (!customElements.get(tagName)) {
        defineCustomElement$3();
      }
      break;
    case "klevu-typography":
      if (!customElements.get(tagName)) {
        defineCustomElement$2();
      }
      break;
    case "klevu-util-scrollbars":
      if (!customElements.get(tagName)) {
        defineCustomElement$1();
      }
      break;
  } });
}
defineCustomElement();

export { KlevuMoi as K, defineCustomElement as d };

//# sourceMappingURL=klevu-moi2.js.map