'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-4ab26f11.js');
const klevuFetch = require('./klevuFetch-912d591d.js');
const klevuInit = require('./klevu-init-e6adb771.js');
const moi = require('./moi-2b5fdc86.js');
const isBrowser = require('./isBrowser-e8e10249.js');
const utils = require('./utils-126dc702.js');
const search = require('./search-ea715f2a.js');
require('./KlevuSearchSorting-abe40432.js');
const sendSearchEvent = require('./sendSearchEvent-a510f690.js');

var __awaiter$1 = (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());
    });
};
/**
 * If original query doesn't return enough results then fallback query is run added to results
 *
 * @category Modifier
 * @param func
 * @returns
 */
function fallback(func, options) {
    var _a;
    if (((_a = func.queries) === null || _a === void 0 ? void 0 : _a.length) !== 1) {
        throw new Error("Fallback modifier can only be applied to single query");
    }
    const fallbackQuery = func.queries[0];
    fallbackQuery.isFallbackQuery = true;
    return {
        klevuModifierId: "fallback",
        modifyAfter: (queries) => __awaiter$1(this, void 0, void 0, function* () {
            const copy = Array.from(queries);
            for (const query of copy) {
                if (!query.id || query.isFallbackQuery === true) {
                    continue;
                }
                fallbackQuery.id = `${query.id}-fallback`;
                if (!query.settings) {
                    query.settings = {};
                }
                query.settings.fallbackQueryId = fallbackQuery.id;
                query.settings.fallbackWhenCountLessThan =
                    options === null || options === void 0 ? void 0 : options.runWhenLessThanResults;
                copy.push(fallbackQuery);
            }
            return copy;
        }),
    };
}

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 url = "https://js.klevu.com/klevu-js-v1/klevu-js-api/";
const STORAGE_KEY = "klevu-kmc-data";
const STORAGE_TS_KEY = "klevu-kmc-data-ts";
const ONE_DAY = 86400000;
/**
 * Fetches KMC settings from server. Caches data for a day.
 *
 * @category KlevuFetch
 * @param ignoreCache If true, will ignore cache and fetch data from server
 * @returns
 */
function KlevuKMCSettings(ignoreCache) {
    return __awaiter(this, void 0, void 0, function* () {
        if (isBrowser.isBrowser() && window.localStorage && ignoreCache !== true) {
            const ts = window.localStorage.getItem(STORAGE_TS_KEY);
            const res = window.localStorage.getItem(STORAGE_KEY);
            if (res && ts && new Date().getTime() - parseInt(ts, 10) < ONE_DAY) {
                return JSON.parse(res);
            }
        }
        const start = `${url}${klevuInit.KlevuConfig.getDefault().apiKey}`;
        const res = yield Promise.all([
            klevuInit.get(`${start}.json`),
            klevuInit.get(`${start}-banner.json`),
            klevuInit.get(`${start}-maps.json`),
        ]);
        const data = {
            root: res[0],
            banner: res[1],
            maps: res[2],
        };
        if (isBrowser.isBrowser() && window.localStorage) {
            window.localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
            window.localStorage.setItem(STORAGE_TS_KEY, new Date().getTime().toString());
        }
        return data;
    });
}

const defaults = {
    id: "suggestions",
    limit: 5,
};
/**
 * Return suggestion on given search term
 *
 * @category Query
 * @param term search term
 * @param options
 * @returns
 */
function suggestions(term, options) {
    const params = Object.assign(Object.assign({}, defaults), options);
    const query = Object.assign({ typeOfRequest: klevuFetch.KlevuTypeOfRequest.Suggestion, query: search.cleanSearchQuery(term) }, params);
    return {
        klevuFunctionId: "suggestions",
        suggestions: [query],
    };
}

const klevuCmsListCss = ":host{display:block}klevu-typography.caption{margin-bottom:var(--klevu-spacing-02)}";

const KlevuCmsList = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.klevuCmsPageClick = index.createEvent(this, "klevuCmsPageClick", 7);
    this.pages = undefined;
    this.link = undefined;
    this.caption = "CMS pages";
  }
  render() {
    var _a;
    return (index.h(index.Host, null, index.h("klevu-typography", { class: "caption", variant: "h3" }, this.caption), (_a = this.pages) === null || _a === void 0 ? void 0 :
      _a.map((page) => {
        if (this.link) {
          return (index.h("klevu-list", { url: page.url, condensed: true, noXPadding: true }, index.h("span", { slot: "primary" }, page.name)));
        }
        return (index.h("klevu-list", { onClick: () => this.klevuCmsPageClick.emit(page), condensed: true, noXPadding: true }, index.h("span", { slot: "primary" }, page.name)));
      })));
  }
};
KlevuCmsList.style = klevuCmsListCss;

const klevuLatestSearchesCss = ":host{display:block}klevu-typography.caption{margin-bottom:var(--klevu-spacing-02)}klevu-list:hover{cursor:pointer;background:var(--klevu-color-neutral-2)}";

var __classPrivateFieldGet$4 = (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 _KlevuLatestSearches_instances, _KlevuLatestSearches_lastSearchClick;
const KlevuLatestSearches = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.klevuLastSearchClicked = index.createEvent(this, "klevuLastSearchClicked", 7);
    _KlevuLatestSearches_instances.add(this);
    this.caption = "Last searches";
    this.lastSearches = [];
  }
  async connectedCallback() {
    this.lastSearches = klevuFetch.KlevuLastSearches.get().map((s) => s.term);
  }
  render() {
    if (this.lastSearches.length === 0) {
      return null;
    }
    return (index.h(index.Host, null, index.h("klevu-typography", { variant: "h3", class: "caption" }, this.caption), this.lastSearches.map((ls) => (index.h("klevu-list", { condensed: true, noXPadding: true, onClick: () => __classPrivateFieldGet$4(this, _KlevuLatestSearches_instances, "m", _KlevuLatestSearches_lastSearchClick).call(this, ls) }, index.h("span", { slot: "primary" }, ls))))));
  }
};
_KlevuLatestSearches_instances = new WeakSet(), _KlevuLatestSearches_lastSearchClick = function _KlevuLatestSearches_lastSearchClick(suggestion) {
  this.klevuLastSearchClicked.emit(suggestion);
};
KlevuLatestSearches.style = klevuLatestSearchesCss;

const klevuMoiCss = ":host{display:block;--klevu-slides-item-width:200px;--container-height:var(--klevu-moi-height, 550px);--container-width:var(--klevu-moi-width, 640px)}.popup{display:none;position:fixed;bottom:-100vh;right:20px;height:var(--container-height);width:var(--container-width);max-height:100vh;max-width:calc(100vw - 20px);background:var(--klevu-color-neutral-1);border-radius:var(--klevu-border-radius-m);box-shadow:var(--klevu-elevation-3);padding:var(--klevu-spacing-04);z-index:100;transition-property:bottom, opacity;transition-duration:0.3s;transition-timing-function:ease-in;opacity:0;box-sizing:border-box}.popup.show{display:block}.popup.open{bottom:20px;right:20px;height:var(--container-height);width:var(--container-width);opacity:1}@media (max-width: 640px){.popup{right:0;bottom:-100vh;max-width:100vw;height:100vh}.popup.open{right:0;bottom:0;max-width:100vw;height:100vh}}klevu-chat-messages{height:calc(var(--container-height) - 250px)}.menu{display:flex;flex-direction:column;gap:var(--klevu-spacing-03)}.genericactions{margin:var(--klevu-spacing-03) 0;display:flex;flex-direction:row;gap:var(--klevu-spacing-03);flex-wrap:wrap;justify-content:center}div[slot=\"header\"]{display:flex;justify-content:space-between;align-items:center;padding:0 var(--klevu-spacing-02) var(--klevu-spacing-02);flex-shrink:0;margin-bottom:var(--klevu-spacing-04);border-bottom:1px solid var(--klevu-color-neutral-4)}";

var __classPrivateFieldGet$3 = (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$1 = (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 = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.klevuMoiProductClick = index.createEvent(this, "klevuMoiProductClick", 7);
    this.klevuMoiVisibilityChange = index.createEvent(this, "klevuMoiVisibilityChange", 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.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.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 moi.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$3(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$3(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 (index.h(index.Host, null, index.h("div", { class: popupClasses }, this.session && (index.h("klevu-chat-layout", { slot: "content", onKlevuChatLayoutMessageSent: (e) => __classPrivateFieldGet$3(this, _KlevuMoi_instances, "m", _KlevuMoi_sendMessage).call(this, e.detail), ref: (el) => {
        __classPrivateFieldSet$1(this, _KlevuMoi_layoutRef, el, "f");
      } }, index.h("div", { slot: "header" }, index.h("klevu-typography", { variant: "body-m-bold" }, "MOI"), index.h("klevu-button", { onClick: () => this.close(), size: "small", icon: "close", isSecondary: true })), index.h("klevu-chat-messages", { onKlevuSelectFilter: (event) => {
        __classPrivateFieldGet$3(this, _KlevuMoi_instances, "m", _KlevuMoi_sendFilter).call(this, event.detail.filter.value, __classPrivateFieldGet$3(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$3(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$3(this, _KlevuMoi_modalRef, "f")) === null || _a === void 0 ? void 0 : _a.openModal();
        }
      }, onKlevuChatProductClick: (event) => {
        event.preventDefault();
        event.stopPropagation();
        __classPrivateFieldGet$3(this, _KlevuMoi_instances, "m", _KlevuMoi_productClick).call(this, event.detail.product);
        return false;
      }, messages: this.messages }), this.loading && index.h("klevu-loading-indicator", null), index.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) => (index.h("klevu-button", { size: "small", isSecondary: true, onClick: () => {
        var _a;
        if (item.type === "message") {
          __classPrivateFieldGet$3(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)))), index.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) => (index.h("klevu-button", { onClick: () => {
        var _a;
        if (item.type === "message") {
          __classPrivateFieldGet$3(this, _KlevuMoi_instances, "m", _KlevuMoi_sendMessage).call(this, item.chat);
        }
        else {
          console.error("Not implemented yet");
        }
        (_a = __classPrivateFieldGet$3(this, _KlevuMoi_layoutRef, "f")) === null || _a === void 0 ? void 0 : _a.closePopup();
      } }, item.name))))))), index.h("klevu-modal", { ref: (el) => (__classPrivateFieldSet$1(this, _KlevuMoi_modalRef, el, "f")) }, index.h("klevu-product", { product: this.currentProduct }))));
  }
  get el() { return index.getElement(this); }
};
_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$3(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$3(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);
};
KlevuMoi.style = klevuMoiCss;

const klevuPopularSearchesCss = ":host{display:block}klevu-typography.caption{margin-bottom:var(--klevu-spacing-02)}klevu-list:hover{cursor:pointer;background:var(--klevu-color-neutral-2)}";

var __classPrivateFieldGet$2 = (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 _KlevuPopularSearches_instances, _KlevuPopularSearches_popularSearchClick;
const KlevuPopularSearches = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.klevuPopularSearchClicked = index.createEvent(this, "klevuPopularSearchClicked", 7);
    _KlevuPopularSearches_instances.add(this);
    this.caption = "Popular searches";
    this.popularSearches = [];
  }
  async connectedCallback() {
    var _a, _b;
    await klevuInit.KlevuInit.ready();
    try {
      const settings = await KlevuKMCSettings();
      this.popularSearches = (_b = (_a = settings.root) === null || _a === void 0 ? void 0 : _a.klevu_webstorePopularTerms) !== null && _b !== void 0 ? _b : [];
    }
    catch (_c) { }
  }
  render() {
    if (this.popularSearches.length == 0) {
      return null;
    }
    return (index.h(index.Host, null, index.h("klevu-typography", { class: "caption", variant: "h3" }, this.caption), this.popularSearches.map((s) => (index.h("klevu-list", { condensed: true, noXPadding: true, onClick: () => __classPrivateFieldGet$2(this, _KlevuPopularSearches_instances, "m", _KlevuPopularSearches_popularSearchClick).call(this, s) }, index.h("span", { slot: "primary" }, s))))));
  }
};
_KlevuPopularSearches_instances = new WeakSet(), _KlevuPopularSearches_popularSearchClick = function _KlevuPopularSearches_popularSearchClick(suggestion) {
  this.klevuPopularSearchClicked.emit(suggestion);
};
KlevuPopularSearches.style = klevuPopularSearchesCss;

const klevuSearchFieldCss = ":host{display:flex}klevu-textfield{width:100%}klevu-button{margin-left:var(--klevu-spacing-04)}";

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 __classPrivateFieldGet$1 = (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 _KlevuSearchField_lastQueryResult, _KlevuSearchField_doSearch, _KlevuSearchField_handleChange, _KlevuSearchField_handleSearchClick;
const KlevuSearchField = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.klevuSearchResults = index.createEvent(this, "klevuSearchResults", 7);
    this.klevuSearchSuggestions = index.createEvent(this, "klevuSearchSuggestions", 7);
    this.klevuSearchClick = index.createEvent(this, "klevuSearchClick", 7);
    _KlevuSearchField_lastQueryResult.set(this, void 0);
    _KlevuSearchField_doSearch.set(this, utils.debounce(async (term) => {
      if (term.length < 3) {
        return;
      }
      const searchModifiers = [];
      // if fallback term is defined use it to search
      if (this.fallbackTerm && this.searchProducts) {
        searchModifiers.push(fallback(search.search(this.fallbackTerm, {
          limit: this.limit,
        })));
      }
      if (this.sendAnalytics) {
        searchModifiers.push(sendSearchEvent.sendSearchEvent());
      }
      const allSearchQueries = [];
      if (this.searchProducts) {
        allSearchQueries.push(search.search(term, { limit: this.limit, typeOfRecords: [klevuFetch.KlevuTypeOfRecord.Product], sort: this.sort }, ...searchModifiers));
      }
      if (this.searchCmsPages) {
        allSearchQueries.push(search.search(term, { id: "cmsSearch", limit: this.limit, typeOfRecords: [klevuFetch.KlevuTypeOfRecord.Cms], sort: this.sort }));
      }
      if (this.searchCategories) {
        allSearchQueries.push(search.search(term, {
          id: "categorySearch",
          limit: this.limit,
          typeOfRecords: [klevuFetch.KlevuTypeOfRecord.Category],
          sort: this.sort,
        }));
      }
      if (this.searchSuggestions) {
        allSearchQueries.push(suggestions(term));
      }
      if (allSearchQueries.length === 0) {
        throw new Error("You need specify at least one thing to search");
      }
      const result = await klevuFetch.KlevuFetch(...allSearchQueries);
      __classPrivateFieldSet(this, _KlevuSearchField_lastQueryResult, {
        fallback: result.queryExists("search-fallback") ? result.queriesById("search-fallback") : undefined,
        search: result.queryExists("search") ? result.queriesById("search") : undefined,
        category: result.queryExists("categorySearch") ? result.queriesById("categorySearch") : undefined,
        cms: result.queryExists("cmsSearch") ? result.queriesById("cmsSearch") : undefined,
      }, "f");
      this.klevuSearchResults.emit(__classPrivateFieldGet$1(this, _KlevuSearchField_lastQueryResult, "f"));
      const suggestionsResult = result.suggestionsById("suggestions");
      if (suggestionsResult) {
        this.klevuSearchSuggestions.emit(suggestionsResult.suggestions.map((s) => s.suggest));
      }
    }, 500)
    /**
     * Fetch next page of results from previous query
     *
     * @param type what type of content to get page from
     * @param pageIndex from what page. If empty next page is fetched
     */
    );
    _KlevuSearchField_handleChange.set(this, (event) => {
      this.term = event.detail;
      __classPrivateFieldGet$1(this, _KlevuSearchField_doSearch, "f").call(this, event.detail);
    });
    _KlevuSearchField_handleSearchClick.set(this, () => {
      this.klevuSearchClick.emit(this.term);
    });
    this.term = "";
    this.placeholder = "Search for products";
    this.searchText = "Search";
    this.limit = 10;
    this.fallbackTerm = undefined;
    this.searchProducts = undefined;
    this.searchSuggestions = undefined;
    this.searchCategories = undefined;
    this.searchCmsPages = undefined;
    this.sendAnalytics = undefined;
    this.sort = undefined;
    this.variant = "default";
  }
  async connectedCallback() {
    await klevuInit.KlevuInit.ready();
  }
  /**
   * Programmatically trigger search
   *
   * @param term What to search
   */
  async makeSearch(term) {
    this.term = term;
    await __classPrivateFieldGet$1(this, _KlevuSearchField_doSearch, "f").call(this, term);
  }
  /**
   * Fetch next page of results from previous query
   *
   * @param type what type of content to get page from
   * @param pageIndex from what page. If empty next page is fetched
   */
  async getPage(type, pageIndex) {
    if (!__classPrivateFieldGet$1(this, _KlevuSearchField_lastQueryResult, "f")) {
      throw new Error("No search results to get page from");
    }
    switch (type) {
      case "search": {
        const res = __classPrivateFieldGet$1(this, _KlevuSearchField_lastQueryResult, "f").search;
        if (res && res.getPage) {
          const result = await res.getPage({ pageIndex });
          __classPrivateFieldGet$1(this, _KlevuSearchField_lastQueryResult, "f").search = result === null || result === void 0 ? void 0 : result.queriesById("search");
          this.klevuSearchResults.emit({
            search: result === null || result === void 0 ? void 0 : result.queriesById("search"),
          });
        }
      }
      case "category": {
        const res = __classPrivateFieldGet$1(this, _KlevuSearchField_lastQueryResult, "f").category;
        if (res && res.getPage) {
          const result = await res.getPage({ pageIndex });
          __classPrivateFieldGet$1(this, _KlevuSearchField_lastQueryResult, "f").category = result === null || result === void 0 ? void 0 : result.queriesById("categorySearch");
          this.klevuSearchResults.emit({
            category: result === null || result === void 0 ? void 0 : result.queriesById("categorySearch"),
          });
        }
      }
      case "cms": {
        const res = __classPrivateFieldGet$1(this, _KlevuSearchField_lastQueryResult, "f").cms;
        if (res && res.getPage) {
          const result = await res.getPage({ pageIndex });
          __classPrivateFieldGet$1(this, _KlevuSearchField_lastQueryResult, "f").cms = result === null || result === void 0 ? void 0 : result.queriesById("cmsSearch");
          this.klevuSearchResults.emit({
            cms: result === null || result === void 0 ? void 0 : result.queriesById("cmsSearch"),
          });
        }
      }
    }
  }
  /**
   * Fetches query result from last request
   *
   * @param type type of query result
   * @returns
   */
  async getQueryResult(type) {
    if (!__classPrivateFieldGet$1(this, _KlevuSearchField_lastQueryResult, "f")) {
      throw new Error("No search results to get query results");
    }
    return __classPrivateFieldGet$1(this, _KlevuSearchField_lastQueryResult, "f")[type];
  }
  async propsChanged() {
    __classPrivateFieldGet$1(this, _KlevuSearchField_doSearch, "f").call(this, this.term);
  }
  render() {
    return (index.h(index.Host, null, index.h("klevu-textfield", { value: this.term, placeholder: this.placeholder, onKlevuTextChanged: __classPrivateFieldGet$1(this, _KlevuSearchField_handleChange, "f").bind(this), onKlevuTextEnterPressed: __classPrivateFieldGet$1(this, _KlevuSearchField_handleSearchClick, "f").bind(this), "aria-role": "search", variant: this.variant, icon: "search" }), this.variant !== "pill" && (index.h("klevu-button", { onClick: __classPrivateFieldGet$1(this, _KlevuSearchField_handleSearchClick, "f").bind(this) }, this.searchText))));
  }
  static get watchers() { return {
    "sort": ["propsChanged"]
  }; }
};
_KlevuSearchField_lastQueryResult = new WeakMap(), _KlevuSearchField_doSearch = new WeakMap(), _KlevuSearchField_handleChange = new WeakMap(), _KlevuSearchField_handleSearchClick = new WeakMap();
KlevuSearchField.style = klevuSearchFieldCss;

const klevuSuggestionsListCss = ":host{display:block}klevu-typography.caption{margin-bottom:var(--klevu-spacing-04)}klevu-list:hover{cursor:pointer;background:var(--klevu-color-neutral-2)}";

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 _KlevuSuggestionsList_instances, _KlevuSuggestionsList_suggestionClick;
const KlevuSuggestionsList = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.klevuSuggestionClicked = index.createEvent(this, "klevuSuggestionClicked", 7);
    _KlevuSuggestionsList_instances.add(this);
    this.caption = "Search suggestions";
    this.suggestions = [];
  }
  render() {
    if (this.suggestions.length === 0)
      return null;
    return (index.h(index.Host, null, index.h("klevu-typography", { class: "caption", variant: "h3" }, this.caption), this.suggestions.map((s) => (index.h("klevu-list", { condensed: true, noXPadding: true }, index.h("span", { slot: "primary", innerHTML: s, onClick: () => __classPrivateFieldGet(this, _KlevuSuggestionsList_instances, "m", _KlevuSuggestionsList_suggestionClick).call(this, utils.stripTags(s)) }))))));
  }
};
_KlevuSuggestionsList_instances = new WeakSet(), _KlevuSuggestionsList_suggestionClick = function _KlevuSuggestionsList_suggestionClick(suggestion) {
  this.klevuSuggestionClicked.emit(suggestion);
};
KlevuSuggestionsList.style = klevuSuggestionsListCss;

const klevuTabCss = ":host{display:inline-block;--klevu-tab-color:var(--klevu-color-primary);--klevu-tab-padding:var(--klevu-spacing-04)}button{display:inline-block;position:relative;transition:transform 100ms;border:0;padding:0;margin:0;height:calc(var(--klevu-size-m) * 2);background:transparent;border-bottom:1px solid var(--klevu-color-neutral-5);padding-bottom:1px}button klevu-typography{border-radius:var(--klevu-border-radius-m);color:var(--klevu-color-neutral-7);display:block;padding:0 calc(var(--klevu-tab-padding) * 2);height:calc(100% - 4px);display:flex;align-items:center}button:focus{outline:0}button.active{border-bottom:2px solid var(--klevu-tab-color);padding-bottom:0}button.active klevu-typography{color:var(--klevu-color-neutral-8)}button:hover klevu-typography{background:var(--klevu-color-neutral-2)}button:disabled klevu-typography{color:var(--klevu-color-neutral-7)}button:focus klevu-typography{outline-offset:-2px;outline:2px solid var(--klevu-tab-color)}";

const KlevuTab = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.caption = undefined;
    this.active = undefined;
    this.disabled = undefined;
  }
  render() {
    return (index.h(index.Host, null, index.h("button", { class: {
        active: Boolean(this.active),
      }, disabled: Boolean(this.disabled) }, index.h("klevu-typography", { variant: "body-s" }, this.caption))));
  }
};
KlevuTab.style = klevuTabCss;

exports.klevu_cms_list = KlevuCmsList;
exports.klevu_latest_searches = KlevuLatestSearches;
exports.klevu_moi = KlevuMoi;
exports.klevu_popular_searches = KlevuPopularSearches;
exports.klevu_search_field = KlevuSearchField;
exports.klevu_suggestions_list = KlevuSuggestionsList;
exports.klevu_tab = KlevuTab;

//# sourceMappingURL=klevu-cms-list_7.cjs.entry.js.map