import { r as registerInstance, c as createEvent, h, H as Host, F as Fragment, g as getElement } from './index-5c6903aa.js';
import { g as getTranslation } from './getTranslation-a535e72f.js';
import { p as partsExports } from './partsExports-0d62f7d7.js';
import { h as KlevuLastSearches, g as KlevuTypeOfRecord, b as KlevuFetch, i as KlevuSearchSorting } from './klevuFetch-ffde321a.js';
import { K as KlevuInit, j as KlevuKMCSettings } from './klevu-init-4a9f3a02.js';
import { s as startMoi } from './moi-d90e0705.js';
import { d as debounce, s as stripTags } from './utils-116b40b3.js';
import { g as getKMCSettings } from './getKMCSettings-cd5894f5.js';
import { s as search } from './search-a264065d.js';
import { s as suggestions } from './suggestions-3da30fa9.js';
import { s as sendSearchEvent } from './sendSearchEvent-6749f29a.js';
import { p as personalisation } from './personalisation-6d5babaa.js';
import { k as klaviyo } from './klaviyo-b33033fa.js';
import './KlevuApiRawResponse-82e24d1e.js';
import './isBrowser-38d37bdf.js';
import './KlevuDomEvents-a1ecbf7c.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());
    });
};
/**
 * 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(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;
        }),
    };
}

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

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

const klevuImagePickerCss = ":host{display:block}.container{display:block;padding:var(--klevu-spacing-02) var(--klevu-spacing-04);border-radius:0.3rem;border:1px solid var(--klevu-color-neutral-7)}.info{margin:var(--klevu-spacing-04) 0;display:flex;gap:var(--klevu-spacing-04)}klevu-accordion{border:0;padding:0}label{background-color:var(--klevu-color-neutral-7);color:white;font-size:var(--klevu-body-xs-size);padding:0.5rem;border-radius:0.3rem;cursor:pointer;margin-top:1rem;display:flex;align-items:center;width:max-content;gap:var(--klevu-spacing-02)}klevu-loading-indicator{--klevu-loading-indicator-color:var(--klevu-color-neutral-2)}";

var __classPrivateFieldGet$7 = (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 _KlevuImagePicker_instances, _KlevuImagePicker_handleImageSelection;
const KlevuImagePicker = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.klevuImageSelected = createEvent(this, "klevuImageSelected", 7);
    _KlevuImagePicker_instances.add(this);
    this.isLoading = false;
    this.maxFileSize = 5;
  }
  render() {
    return (h(Host, null, h("div", { class: "container", onClick: (e) => {
        e.stopPropagation();
      }, onFocus: (e) => {
        e.stopPropagation();
      } }, h("p", null, h("klevu-typography", { variant: "h4" }, "Visual Image Search")), h("label", { htmlFor: "select-image" }, this.isLoading ? (h("klevu-loading-indicator", { exportparts: partsExports("klevu-loading-indicator") })) : (h(Fragment, null, h("klevu-icon", { name: "upload" }), h("span", null, "Upload a photo")))), h("input", { hidden: true, id: "select-image", type: "file", onClick: (e) => {
        e.stopPropagation();
      }, onFocus: (e) => {
        e.stopPropagation();
      }, onChange: __classPrivateFieldGet$7(this, _KlevuImagePicker_instances, "m", _KlevuImagePicker_handleImageSelection).bind(this) }), h("p", { class: "info" }, h("klevu-icon", { name: "info" }), h("klevu-typography", { variant: "body-xs" }, "Your privacy is of utmost importance to us. Any images uploaded will only be used to provide relevant results and improve the general search experience. However, we recommend not uploading images containing people or sensitive information.")), h("klevu-accordion", { exportparts: partsExports("klevu-accordion") }, h("span", { slot: "header" }, "How does this work?"), h("div", { slot: "content" }, h("klevu-typography", { variant: "body-xs" }, "After you take or upload a photo, we'll analyse it and recommend the closest matches."))))));
  }
};
_KlevuImagePicker_instances = new WeakSet(), _KlevuImagePicker_handleImageSelection = function _KlevuImagePicker_handleImageSelection(e) {
  e.preventDefault();
  e.stopPropagation();
  const target = e.target;
  if ((target === null || target === void 0 ? void 0 : target.files) && (target === null || target === void 0 ? void 0 : target.files.length) > 0) {
    var fileSize = target.files[0].size / 1024 / 1024;
    if (fileSize > this.maxFileSize) {
      alert(`File size exceeds ${this.maxFileSize} MiB`);
    }
    else {
      this.klevuImageSelected.emit({ image: target.files[0], name: target.files[0].name });
    }
  }
};
KlevuImagePicker.style = klevuImagePickerCss;

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

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

const klevuModalCss = ":host{display:block}dialog{border:none !important;border-radius:var(--klevu-border-radius-m);padding:0;box-shadow:var(--klevu-elevation-1)}main{padding:var(--klevu-spacing-04)}header{padding:var(--klevu-spacing-04);display:flex;justify-content:space-between;align-items:center}button{border:none;background-color:transparent;appearance:none;border-radius:100%;height:30px;width:30px}";

var __classPrivateFieldGet$5 = (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$3 = (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 _KlevuModal_instances, _KlevuModal_dialogRef, _KlevuModal_close;
const KlevuModal = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.klevuCloseModal = createEvent(this, "klevuCloseModal", 7);
    _KlevuModal_instances.add(this);
    _KlevuModal_dialogRef.set(this, void 0);
    this.startOpen = false;
  }
  componentDidLoad() {
    if (this.startOpen) {
      this.openModal();
    }
  }
  /**
   * Opens the modal.
   */
  async openModal() {
    var _a;
    (_a = __classPrivateFieldGet$5(this, _KlevuModal_dialogRef, "f")) === null || _a === void 0 ? void 0 : _a.showModal();
  }
  /**
   * Closes the modal.
   */
  async closeModal() {
    var _a;
    (_a = __classPrivateFieldGet$5(this, _KlevuModal_dialogRef, "f")) === null || _a === void 0 ? void 0 : _a.close();
  }
  render() {
    return (h(Host, null, h("div", { part: "modal-base" }, h("dialog", { ref: (el) => (__classPrivateFieldSet$3(this, _KlevuModal_dialogRef, el, "f")), onCancel: __classPrivateFieldGet$5(this, _KlevuModal_instances, "m", _KlevuModal_close).bind(this), part: "modal-dialog" }, h("header", { part: "modal-header" }, h("slot", { name: "header" }), h("form", { method: "dialog", onSubmit: __classPrivateFieldGet$5(this, _KlevuModal_instances, "m", _KlevuModal_close).bind(this) }, h("button", null, h("klevu-icon", { name: "close" })))), h("main", { part: "modal-body" }, h("slot", null))))));
  }
};
_KlevuModal_dialogRef = new WeakMap(), _KlevuModal_instances = new WeakSet(), _KlevuModal_close = function _KlevuModal_close(e) {
  const event = this.klevuCloseModal.emit();
  if (event.defaultPrevented) {
    e.preventDefault();
  }
};
KlevuModal.style = klevuModalCss;

const klevuMoiCss = ":host{display:block;--klevu-slides-item-width:var(--klevu-moi-slides-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$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 __classPrivateFieldSet$2 = (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) {
    registerInstance(this, hostRef);
    this.klevuMoiProductClick = createEvent(this, "klevuMoiProductClick", 7);
    this.klevuMoiVisibilityChange = 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.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$4(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$4(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$4(this, _KlevuMoi_instances, "m", _KlevuMoi_sendMessage).call(this, e.detail), ref: (el) => {
        __classPrivateFieldSet$2(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$4(this, _KlevuMoi_instances, "m", _KlevuMoi_sendFilter).call(this, event.detail.filter.value, __classPrivateFieldGet$4(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$4(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$4(this, _KlevuMoi_modalRef, "f")) === null || _a === void 0 ? void 0 : _a.openModal();
        }
      }, onKlevuChatProductClick: (event) => {
        event.preventDefault();
        event.stopPropagation();
        __classPrivateFieldGet$4(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$4(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$4(this, _KlevuMoi_instances, "m", _KlevuMoi_sendMessage).call(this, item.chat);
        }
        else {
          console.error("Not implemented yet");
        }
        (_a = __classPrivateFieldGet$4(this, _KlevuMoi_layoutRef, "f")) === null || _a === void 0 ? void 0 : _a.closePopup();
      } }, item.name))))))), h("klevu-modal", { ref: (el) => (__classPrivateFieldSet$2(this, _KlevuMoi_modalRef, el, "f")) }, h("klevu-product", { exportparts: partsExports("klevu-product"), product: this.currentProduct }))));
  }
  get el() { return 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$4(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$4(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 klevuPaginationCss = ":host{--selected-color:var(--klevu-pagination-selected-color, var(--klevu-color-primary))}:host div{display:flex;gap:var(--klevu-spacing-03);justify-content:center;flex-wrap:wrap}span,klevu-icon{display:flex;height:32px;width:32px;color:var(--klevu-color-neutral-8);border-radius:var(--klevu-border-radius-m);justify-content:center;align-items:center;font-size:var(--klevu-body-s-size);box-sizing:border-box}span.current{font-weight:bold;cursor:inherit;border:1px solid var(--selected-color);color:var(--selected-color)}span:not(.disabled):not(.current):hover,klevu-icon:not(.disabled):not(.current):hover{color:var(--selected-color);background-color:var(--klevu-color-neutral-2);cursor:pointer}span.disabled,klevu-icon.disabled{opacity:var(--klevu-opacity-disabled);cursor:inherit}span.dots{width:auto}@media (max-width: 600px){:host{gap:var(--klevu-spacing-02)}}";

const KlevuPagination = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.klevuPaginationChange = createEvent(this, "klevuPaginationChange", 7);
    this.current = undefined;
    this.min = undefined;
    this.max = undefined;
    this.queryResult = undefined;
  }
  render() {
    let min, max, current;
    if (this.queryResult) {
      min = 1;
      max = Math.floor(this.queryResult.meta.totalResultsFound / this.queryResult.meta.noOfResults) + 1;
      current = Math.floor(this.queryResult.meta.offset / this.queryResult.meta.noOfResults) + 1;
    }
    else {
      if ([this.current, this.max, this.min].some((i) => i === undefined)) {
        throw new Error("queryResult or current, min & max needs to be defined");
      }
      min = this.min;
      max = this.max;
      current = this.current;
    }
    let pages = [];
    for (let i = min; i <= max; i++) {
      pages.push(i);
    }
    if (pages.length > 8) {
      let startIndex = min + 1;
      let endIndex = max - 1;
      let currentStartIndex = current > 3 ? current - 1 : 0;
      let currentEndIndex = current < endIndex - 1 ? currentStartIndex + 2 : endIndex - 1;
      if (currentStartIndex < startIndex) {
        currentStartIndex = startIndex + 1;
        currentEndIndex = currentStartIndex + 2;
      }
      pages = [];
      for (let i = min; i <= startIndex; i++) {
        pages.push(i);
      }
      if (startIndex + 1 < currentStartIndex) {
        pages.push(-1);
      }
      for (let i = currentStartIndex; i <= currentEndIndex; i++) {
        pages.push(i);
      }
      if (currentEndIndex + 1 < endIndex) {
        pages.push(-1);
      }
      for (let i = endIndex; i <= max; i++) {
        pages.push(i);
      }
    }
    return (h(Host, null, h("div", { part: "pagination-base" }, h("klevu-icon", { class: {
        disabled: current === min,
      }, onClick: () => current !== min && this.klevuPaginationChange.emit(current - 1), name: "navigate_before", part: "pagination-navigation-previous" }), pages.map((i) => {
      if (i == -1) {
        return h("span", { class: "disabled dots" }, "...");
      }
      return (h("span", { class: {
          current: current === i,
        }, onClick: () => current !== i && this.klevuPaginationChange.emit(i), part: "pagination-page-number" }, i));
    }), h("klevu-icon", { class: {
        disabled: current === max,
      }, onClick: () => current !== max && this.klevuPaginationChange.emit(current + 1), name: "navigate_next", part: "pagination-navigation-next" }))));
  }
};
KlevuPagination.style = klevuPaginationCss;

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

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 _KlevuPopularSearches_instances, _KlevuPopularSearches_popularSearchClick;
const KlevuPopularSearches = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.klevuPopularSearchClicked = createEvent(this, "klevuPopularSearchClicked", 7);
    _KlevuPopularSearches_instances.add(this);
    this.tCaption = getTranslation("popularSearches.tCaption");
    this.popularSearches = [];
  }
  async connectedCallback() {
    var _a, _b;
    await 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 (h(Host, null, h("div", { part: "popular-searches-base" }, h("klevu-typography", { class: "caption", variant: "h3", part: "popular-searches-caption" }, this.tCaption), this.popularSearches.map((s) => (h("klevu-list", { condensed: true, noXPadding: true, onClick: () => __classPrivateFieldGet$3(this, _KlevuPopularSearches_instances, "m", _KlevuPopularSearches_popularSearchClick).call(this, s), exportparts: partsExports("klevu-list") }, h("span", { part: "popular-searches-list-item", slot: "primary" }, s)))))));
  }
};
_KlevuPopularSearches_instances = new WeakSet(), _KlevuPopularSearches_popularSearchClick = function _KlevuPopularSearches_popularSearchClick(suggestion) {
  this.klevuPopularSearchClicked.emit(suggestion);
};
KlevuPopularSearches.style = klevuPopularSearchesCss;

const klevuProductGridCss = ":host{--spacing:var(--klevu-product-grid-spacing, var(--klevu-spacing-05));--product-width:var(--klevu-product-grid-product-width, 250px)}.gridcontainer{display:grid;grid-gap:var(--grid-spacing);grid-template-columns:repeat(auto-fill, minmax(var(--product-width), 1fr))}";

const KlevuProductGrid = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.itemsPerRow = undefined;
  }
  render() {
    const style = {};
    if (this.itemsPerRow) {
      style.gridTemplateColumns = `repeat(${this.itemsPerRow}, 1fr)`;
    }
    return (h(Host, null, h("div", { class: "gridcontainer", style: style, part: "product-grid-base" }, h("slot", null))));
  }
};
KlevuProductGrid.style = klevuProductGridCss;

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

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 __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 _KlevuSearchField_lastQueryResult, _KlevuSearchField_doSearch, _KlevuSearchField_handleChange, _KlevuSearchField_handleSearchClick;
const KlevuSearchField = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.klevuSearchResults = createEvent(this, "klevuSearchResults", 7);
    this.klevuSearchSuggestions = createEvent(this, "klevuSearchSuggestions", 7);
    this.klevuSearchClick = createEvent(this, "klevuSearchClick", 7);
    _KlevuSearchField_lastQueryResult.set(this, void 0);
    _KlevuSearchField_doSearch.set(this, 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(this.fallbackTerm, {
          limit: this.limit,
        })));
      }
      if (this.sendAnalytics) {
        searchModifiers.push(sendSearchEvent());
      }
      if (this.usePersonalisation) {
        searchModifiers.push(personalisation());
      }
      if (this.useKlaviyo) {
        console.log("pushing klaviyo");
        searchModifiers.push(klaviyo());
      }
      const allSearchQueries = [];
      if (this.searchProducts) {
        allSearchQueries.push(search(term, { limit: this.limit, typeOfRecords: [KlevuTypeOfRecord.Product], sort: this.sort }, ...searchModifiers));
      }
      if (this.searchCmsPages) {
        allSearchQueries.push(search(term, { id: "cmsSearch", limit: this.limit, typeOfRecords: [KlevuTypeOfRecord.Cms], sort: this.sort }));
      }
      if (this.searchCategories) {
        allSearchQueries.push(search(term, {
          id: "categorySearch",
          limit: this.limit,
          typeOfRecords: [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(...allSearchQueries);
      __classPrivateFieldSet$1(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$2(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;
    });
    _KlevuSearchField_handleSearchClick.set(this, () => {
      this.klevuSearchClick.emit(this.term);
    });
    this.term = "";
    this.tPlaceholder = getTranslation("searchField.tPlaceholder");
    this.tSearchText = getTranslation("searchField.tSearchText");
    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";
    this.usePersonalisation = undefined;
    this.useKlaviyo = undefined;
  }
  async connectedCallback() {
    await KlevuInit.ready();
    const settings = getKMCSettings();
    if (this.usePersonalisation === undefined && (settings === null || settings === void 0 ? void 0 : settings.klevu_uc_userOptions.enablePersonalisationInSearch)) {
      this.usePersonalisation = true;
    }
    if (this.term !== undefined) {
      await __classPrivateFieldGet$2(this, _KlevuSearchField_doSearch, "f").call(this, this.term);
    }
  }
  /**
   * Programmatically trigger search
   *
   * @param term What to search
   */
  async makeSearch(term) {
    this.term = term;
    await __classPrivateFieldGet$2(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$2(this, _KlevuSearchField_lastQueryResult, "f")) {
      throw new Error("No search results to get page from");
    }
    switch (type) {
      case "search": {
        const res = __classPrivateFieldGet$2(this, _KlevuSearchField_lastQueryResult, "f").search;
        if (res && res.getPage) {
          const result = await res.getPage({ pageIndex });
          __classPrivateFieldGet$2(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$2(this, _KlevuSearchField_lastQueryResult, "f").category;
        if (res && res.getPage) {
          const result = await res.getPage({ pageIndex });
          __classPrivateFieldGet$2(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$2(this, _KlevuSearchField_lastQueryResult, "f").cms;
        if (res && res.getPage) {
          const result = await res.getPage({ pageIndex });
          __classPrivateFieldGet$2(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$2(this, _KlevuSearchField_lastQueryResult, "f")) {
      throw new Error("No search results to get query results");
    }
    return __classPrivateFieldGet$2(this, _KlevuSearchField_lastQueryResult, "f")[type];
  }
  async propsChanged() {
    __classPrivateFieldGet$2(this, _KlevuSearchField_doSearch, "f").call(this, this.term);
  }
  async termChanged() {
    __classPrivateFieldGet$2(this, _KlevuSearchField_doSearch, "f").call(this, this.term);
  }
  render() {
    return (h(Host, null, h("klevu-textfield", { exportparts: partsExports("klevu-textfield"), value: this.term, placeholder: this.tPlaceholder, onKlevuTextChanged: __classPrivateFieldGet$2(this, _KlevuSearchField_handleChange, "f").bind(this), onKlevuTextEnterPressed: __classPrivateFieldGet$2(this, _KlevuSearchField_handleSearchClick, "f").bind(this), "aria-role": "search", variant: this.variant, icon: "search" }, h("slot", { name: "end-of-input", slot: "end" })), this.variant !== "pill" && (h("klevu-button", { onClick: __classPrivateFieldGet$2(this, _KlevuSearchField_handleSearchClick, "f").bind(this) }, this.tSearchText))));
  }
  static get watchers() { return {
    "sort": ["propsChanged"],
    "term": ["termChanged"]
  }; }
};
_KlevuSearchField_lastQueryResult = new WeakMap(), _KlevuSearchField_doSearch = new WeakMap(), _KlevuSearchField_handleChange = new WeakMap(), _KlevuSearchField_handleSearchClick = new WeakMap();
KlevuSearchField.style = klevuSearchFieldCss;

const klevuSortCss = ":host{display:block}";

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 _KlevuSort_instances, _KlevuSort_selected, _KlevuSort_onChange;
const KlevuSort = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.klevuSortChanged = createEvent(this, "klevuSortChanged", 7);
    _KlevuSort_instances.add(this);
    _KlevuSort_selected.set(this, KlevuSearchSorting.Relevance);
    this.variant = "default";
    this.options = [
      { value: KlevuSearchSorting.Relevance, text: getTranslation("sort.tRelevance") },
      { value: KlevuSearchSorting.NameAsc, text: getTranslation("sort.tNameAsc") },
      { value: KlevuSearchSorting.NameDesc, text: getTranslation("sort.tNameDesc") },
      { value: KlevuSearchSorting.NewArrivalAsc, text: getTranslation("sort.tNewArrivalsAsc") },
      { value: KlevuSearchSorting.NewArrivalDesc, text: getTranslation("sort.tNewArrivalsDesc") },
      { value: KlevuSearchSorting.PriceAsc, text: getTranslation("sort.tPriceAsc") },
      { value: KlevuSearchSorting.PriceDesc, text: getTranslation("sort.tPriceDesc") },
      { value: KlevuSearchSorting.RatingAsc, text: getTranslation("sort.tRatingAsc") },
      { value: KlevuSearchSorting.RatingDesc, text: getTranslation("sort.tRatingDesc") },
    ];
  }
  render() {
    return (h(Host, null, h("klevu-dropdown", { exportparts: partsExports("klevu-dropdown"), name: "sort", options: this.options, selected: __classPrivateFieldGet$1(this, _KlevuSort_selected, "f"), variant: this.variant, onKlevuDropdownChanged: __classPrivateFieldGet$1(this, _KlevuSort_instances, "m", _KlevuSort_onChange).bind(this) })));
  }
};
_KlevuSort_selected = new WeakMap(), _KlevuSort_instances = new WeakSet(), _KlevuSort_onChange = function _KlevuSort_onChange(event) {
  const newSort = event.detail;
  __classPrivateFieldSet(this, _KlevuSort_selected, newSort, "f");
  this.klevuSortChanged.emit(newSort);
};
KlevuSort.style = klevuSortCss;

const klevuSuggestionsListCss = ":host{display:block}klevu-typography.caption{display:block;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) {
    registerInstance(this, hostRef);
    this.klevuSuggestionClicked = createEvent(this, "klevuSuggestionClicked", 7);
    _KlevuSuggestionsList_instances.add(this);
    this.caption = "Search suggestions";
    this.suggestions = [];
  }
  render() {
    if (this.suggestions.length === 0)
      return null;
    return (h(Host, null, h("klevu-typography", { class: "caption", variant: "h3", part: "suggestions-list-caption" }, this.caption), this.suggestions.map((s) => (h("klevu-list", { condensed: true, noXPadding: true, exportparts: partsExports("klevu-list") }, h("span", { slot: "primary", innerHTML: s, onClick: () => __classPrivateFieldGet(this, _KlevuSuggestionsList_instances, "m", _KlevuSuggestionsList_suggestionClick).call(this, 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;--color:var(--klevu-tab-color, var(--klevu-color-primary));--padding:var(--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(--padding) * 2);height:calc(100% - 4px);display:flex;align-items:center}button:focus{outline:0}button.active{border-bottom:2px solid var(--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(--color)}";

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

export { KlevuCmsList as klevu_cms_list, KlevuImagePicker as klevu_image_picker, KlevuLatestSearches as klevu_latest_searches, KlevuModal as klevu_modal, KlevuMoi as klevu_moi, KlevuPagination as klevu_pagination, KlevuPopularSearches as klevu_popular_searches, KlevuProductGrid as klevu_product_grid, KlevuSearchField as klevu_search_field, KlevuSort as klevu_sort, KlevuSuggestionsList as klevu_suggestions_list, KlevuTab as klevu_tab };

//# sourceMappingURL=klevu-cms-list_12.entry.js.map