'use strict';

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

const index = require('./index-6b50a234.js');
const klevuInit = require('./klevu-init-0ddd3486.js');
const getTranslation = require('./getTranslation-2fac1f2e.js');
const getKMCSettings = require('./getKMCSettings-7c5e857d.js');
const partsExports = require('./partsExports-67956c7b.js');
const filterManager = require('./filterManager-31f4956d.js');
const categoryMerchandising = require('./categoryMerchandising-308e65d5.js');
const listFilters = require('./listFilters-cd8c83a9.js');
const klevuFetch = require('./klevuFetch-cb6905ea.js');
const personalisation = require('./personalisation-2ed36bb0.js');
const isBrowser = require('./isBrowser-e8e10249.js');
require('./KlevuDomEvents-f5b92150.js');
require('./KlevuApiRawResponse-7801506a.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_TS_KEY = "abtest-data-ts";
const STORAGE_KEY = "abtest-data";
const STORAGE_PERMANENT_KEY = "abtest-permanent-data";
const HALF_HOUR = 1800000;
/**
 * Enables AB test functionality. This will make extra request to Klevu servers and it is recommended only if you wish to use A/B testing feature.
 *
 * Currently not supported in server side rendering.
 *
 * @category Modifier
 * @returns
 */
function abTest() {
    return {
        klevuModifierId: "abtest",
        modifyAfter: (queries, func) => __awaiter(this, void 0, void 0, function* () {
            var _a, _b, _c;
            // A/B test is not supported in the serverside
            if (!isBrowser.isBrowser()) {
                return Array.from(queries);
            }
            const data = yield fetchAbTestInfo();
            const permanent = JSON.parse((_a = window.localStorage.getItem(STORAGE_PERMANENT_KEY)) !== null && _a !== void 0 ? _a : "[]");
            if (!data) {
                throw new Error("Failed to fetch AB test data");
            }
            // clean permanent data
            const newpermanent = [];
            for (const perm of permanent) {
                if (data.assigned.some((a) => a.abTestId === perm.abTestId && a.sourceId === perm.sourceId)) {
                    newpermanent.push(perm);
                }
            }
            const copy = Array.from(queries);
            for (const q of copy) {
                if (q.typeOfRequest !== klevuFetch.KlevuTypeOfRequest.CategoryNavigation) {
                    throw new Error("abtest can only be applied to category navigation");
                }
                const path = (_c = (_b = q.settings) === null || _b === void 0 ? void 0 : _b.query) === null || _c === void 0 ? void 0 : _c.categoryPath;
                if (!path) {
                    throw new Error("missing category path from abtest");
                }
                const perm = newpermanent.find((a) => a.sourceId.toLocaleLowerCase() === path.toLocaleLowerCase());
                if (!func.params) {
                    func.params = {};
                }
                if (perm) {
                    q.abTestId = perm.abTestId;
                    q.abTestVariantId = perm.abTestVariantId;
                    func.params.abtest = perm;
                    continue;
                }
                const test = data.assigned.find((a) => a.sourceId.toLocaleLowerCase() === path.toLocaleLowerCase());
                if (!test) {
                    continue;
                }
                if (!newpermanent.some((a) => a.abTestId === test.abTestId && a.sourceId === test.sourceId)) {
                    newpermanent.push(test);
                    klevuInit.post(`https://config-cdn.ksearchnet.com/abtest/public/usage/${klevuInit.KlevuConfig.getDefault().apiKey}`, test, true);
                }
                q.abTestId = test.abTestId;
                q.abTestVariantId = test.abTestVariantId;
                func.params.abtest = test;
            }
            window.localStorage.setItem(STORAGE_PERMANENT_KEY, JSON.stringify(newpermanent));
            return copy;
        }),
    };
}
/**
 * This function never wait for result if there is one in cache. Returns new results on next time.
 *
 * @returns
 */
function fetchAbTestInfo() {
    return __awaiter(this, void 0, void 0, function* () {
        const ts = window.localStorage.getItem(STORAGE_TS_KEY);
        const res = window.localStorage.getItem(STORAGE_KEY);
        const fetch = () => __awaiter(this, void 0, void 0, function* () {
            const data = yield klevuInit.post(`https://config-cdn.ksearchnet.com/abtest/public/allocation/${klevuInit.KlevuConfig.getDefault().apiKey}/`, {});
            window.localStorage.setItem(STORAGE_TS_KEY, new Date().getTime().toString());
            window.localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
            return data;
        });
        if (res && ts) {
            if (new Date().getTime() - parseInt(ts, 10) > HALF_HOUR) {
                // do not wait
                fetch();
            }
            return JSON.parse(res);
        }
        return fetch();
    });
}

const klevuMerchandisingCss = ".header{display:flex;justify-content:space-between;width:100%}.footer{display:flex;justify-content:center}.footer .klevu-pagination{padding:var(--klevu-spacing-03) 0}";

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 _KlevuMerchandising_instances, _KlevuMerchandising_viewportUtil, _KlevuMerchandising_layoutElement, _KlevuMerchandising_facetListElement, _KlevuMerchandising_resultObject, _KlevuMerchandising_fetchData, _KlevuMerchandising_loadMore, _KlevuMerchandising_paginationChange, _KlevuMerchandising_emitChanges, _KlevuMerchandising_sortChanged, _KlevuMerchandising_sizeChange, _KlevuMerchandising_applyFilters, _KlevuMerchandising_isMobile, _KlevuMerchandising_mobileDrawerOpened;
const KlevuMerchandising = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.klevuData = index.createEvent(this, "klevuData", 7);
    _KlevuMerchandising_instances.add(this);
    _KlevuMerchandising_viewportUtil.set(this, void 0);
    _KlevuMerchandising_layoutElement.set(this, void 0);
    _KlevuMerchandising_facetListElement.set(this, void 0);
    _KlevuMerchandising_resultObject.set(this, void 0);
    this.usePagination = undefined;
    this.useInfiniteScroll = undefined;
    this.limit = 24;
    this.category = undefined;
    this.categoryTitle = undefined;
    this.tLoadMore = getTranslation.getTranslation("merchandising.tLoadMore");
    this.sort = undefined;
    this.filterCount = undefined;
    this.options = undefined;
    this.filterCustomOrder = undefined;
    this.sortOptions = undefined;
    this.showRatings = undefined;
    this.showRatingsCount = undefined;
    this.usePersonalisation = undefined;
    this.useABTest = undefined;
    this.currentViewPortSize = undefined;
    this.results = [];
    this.manager = new filterManager.FilterManager();
    this.loading = false;
    this.infiniteScrollingPaused = false;
    this.searchResultTopBanners = [];
    this.searchResultBottomBanners = [];
  }
  async connectedCallback() {
    var _a, _b;
    await klevuInit.KlevuInit.ready();
    const settings = getKMCSettings.getKMCSettings();
    if (settings) {
      if (this.showRatings === undefined) {
        this.showRatings = ((_a = settings.klevu_uc_userOptions) === null || _a === void 0 ? void 0 : _a.showRatingsOnCategoryPage) || false;
      }
      if (this.showRatingsCount === undefined) {
        this.showRatingsCount = ((_b = settings.klevu_uc_userOptions) === null || _b === void 0 ? void 0 : _b.showRatingsCountOnCategoryPage) || false;
      }
      if (this.usePersonalisation === undefined && (settings === null || settings === void 0 ? void 0 : settings.klevu_uc_userOptions.enablePersonalisationInCatNav)) {
        this.usePersonalisation = true;
      }
      if (this.useABTest === undefined) {
        this.useABTest = settings.klevu_abTestActive;
      }
    }
    await __classPrivateFieldGet(this, _KlevuMerchandising_instances, "m", _KlevuMerchandising_fetchData).call(this);
  }
  async watchPropHandler(newValue, oldValue) {
    if (newValue !== oldValue) {
      this.manager.clear();
      await __classPrivateFieldGet(this, _KlevuMerchandising_instances, "m", _KlevuMerchandising_fetchData).call(this);
    }
  }
  infiniteScrollLoadMoreHandler() {
    __classPrivateFieldGet(this, _KlevuMerchandising_instances, "m", _KlevuMerchandising_loadMore).call(this);
  }
  infiniteLoadPausedHandler() {
    this.infiniteScrollingPaused = true;
  }
  productClickHandler(event) {
    var _a, _b;
    if (!event.detail.product.id) {
      return;
    }
    if ((_a = __classPrivateFieldGet(this, _KlevuMerchandising_resultObject, "f")) === null || _a === void 0 ? void 0 : _a.categoryMerchandisingClickEvent) {
      (_b = __classPrivateFieldGet(this, _KlevuMerchandising_resultObject, "f")) === null || _b === void 0 ? void 0 : _b.categoryMerchandisingClickEvent({
        productId: event.detail.product.id,
        variantId: event.detail.product.variantId,
        categoryTitle: this.categoryTitle,
      });
    }
  }
  async componentDidLoad() {
    this.currentViewPortSize = await __classPrivateFieldGet(this, _KlevuMerchandising_viewportUtil, "f").getCurrentSize();
  }
  filterManagerFiltersUpdated() {
    if (__classPrivateFieldGet(this, _KlevuMerchandising_instances, "m", _KlevuMerchandising_isMobile).call(this)) {
      return;
    }
    __classPrivateFieldGet(this, _KlevuMerchandising_instances, "m", _KlevuMerchandising_fetchData).call(this);
  }
  render() {
    var _a, _b, _c;
    const showInfiniteScroll = this.useInfiniteScroll &&
      !this.infiniteScrollingPaused &&
      this.results.length > 0 &&
      ((_a = __classPrivateFieldGet(this, _KlevuMerchandising_resultObject, "f")) === null || _a === void 0 ? void 0 : _a.hasNextPage());
    return (index.h(index.Host, null, index.h("klevu-util-viewport", { onKlevuSizeChanged: __classPrivateFieldGet(this, _KlevuMerchandising_instances, "m", _KlevuMerchandising_sizeChange).bind(this), ref: (el) => (__classPrivateFieldSet(this, _KlevuMerchandising_viewportUtil, el, "f")) }), index.h("klevu-layout-results", { onKlevuDrawerOpened: __classPrivateFieldGet(this, _KlevuMerchandising_instances, "m", _KlevuMerchandising_mobileDrawerOpened).bind(this), ref: (el) => (__classPrivateFieldSet(this, _KlevuMerchandising_layoutElement, el, "f")) }, index.h("slot", { name: "facets", slot: "sidebar" }, index.h("div", { part: "merchandising-sidebar" }, index.h("klevu-facet-list", { ref: (el) => (__classPrivateFieldSet(this, _KlevuMerchandising_facetListElement, el, "f")), accordion: true, customOrder: this.filterCustomOrder, manager: this.manager, useApplyButton: __classPrivateFieldGet(this, _KlevuMerchandising_instances, "m", _KlevuMerchandising_isMobile).call(this), onKlevuApplyFilters: __classPrivateFieldGet(this, _KlevuMerchandising_instances, "m", _KlevuMerchandising_applyFilters).bind(this) }))), index.h("div", { slot: "header", class: "header", part: "merchandising-header" }, index.h("klevu-typography", { variant: "h1" }, this.categoryTitle), index.h("klevu-sort", { variant: "inline", onKlevuSortChanged: __classPrivateFieldGet(this, _KlevuMerchandising_instances, "m", _KlevuMerchandising_sortChanged).bind(this), options: this.sortOptions })), index.h("slot", { name: "content", slot: "content" }, index.h("div", { part: "merchandising-content" }, index.h("slot", { name: "topbanners" }, this.searchResultTopBanners.map((b) => (index.h("klevu-banner", { imageUrl: b.bannerImg, linkUrl: b.redirectUrl, altText: b.bannerAltTag })))), index.h("klevu-product-grid", null, this.results.map((p) => (index.h("klevu-product", { product: p, fixedWidth: true, exportparts: partsExports.partsExports("klevu-product"), showRatings: this.showRatings, showRatingsCount: this.showRatingsCount })))), this.loading && !this.infiniteScrollingPaused && (index.h("klevu-loading-indicator", { exportparts: partsExports.partsExports("klevu-loading-indicator") })), index.h("slot", { name: "bottombanners" }, this.searchResultBottomBanners.map((b) => (index.h("klevu-banner", { imageUrl: b.bannerImg, linkUrl: b.redirectUrl, altText: b.bannerAltTag })))))), index.h("div", { slot: "footer", class: "footer", part: "merchandising-footer" }, showInfiniteScroll ? (index.h("klevu-util-infinite-scroll", { infiniteScrollPauseThreshold: 3, enabled: !!((_b = __classPrivateFieldGet(this, _KlevuMerchandising_resultObject, "f")) === null || _b === void 0 ? void 0 : _b.hasNextPage()) && !this.loading })) : this.usePagination && __classPrivateFieldGet(this, _KlevuMerchandising_resultObject, "f") ? (index.h("klevu-pagination", { exportparts: partsExports.partsExports("klevu-pagination"), queryResult: __classPrivateFieldGet(this, _KlevuMerchandising_resultObject, "f"), onKlevuPaginationChange: __classPrivateFieldGet(this, _KlevuMerchandising_instances, "m", _KlevuMerchandising_paginationChange).bind(this) })) : ((_c = __classPrivateFieldGet(this, _KlevuMerchandising_resultObject, "f")) === null || _c === void 0 ? void 0 : _c.hasNextPage()) ? (index.h("klevu-button", { onClick: __classPrivateFieldGet(this, _KlevuMerchandising_instances, "m", _KlevuMerchandising_loadMore).bind(this) }, this.tLoadMore)) : null))));
  }
  get el() { return index.getElement(this); }
  static get watchers() { return {
    "category": ["watchPropHandler"]
  }; }
};
_KlevuMerchandising_viewportUtil = new WeakMap(), _KlevuMerchandising_layoutElement = new WeakMap(), _KlevuMerchandising_facetListElement = new WeakMap(), _KlevuMerchandising_resultObject = new WeakMap(), _KlevuMerchandising_instances = new WeakSet(), _KlevuMerchandising_fetchData = async function _KlevuMerchandising_fetchData() {
  var _a, _b;
  this.loading = true;
  const modifiers = [
    categoryMerchandising.sendMerchandisingViewEvent(this.categoryTitle),
    listFilters.listFilters({
      filterManager: this.manager,
      limit: this.filterCount,
      rangeFilterSettings: [
        {
          key: "klevu_price",
          minMax: true,
        },
      ],
    }),
    klevuFetch.applyFilterWithManager(this.manager),
  ];
  if (this.usePersonalisation) {
    modifiers.push(personalisation.personalisation());
  }
  if (this.useABTest) {
    modifiers.push(abTest());
  }
  const result = await klevuFetch.KlevuFetch(categoryMerchandising.categoryMerchandising(this.category, Object.assign({ limit: this.limit, sort: this.sort }, this.options), ...modifiers));
  __classPrivateFieldSet(this, _KlevuMerchandising_resultObject, result.queriesById("categoryMerchandising"), "f");
  this.results = (_b = (_a = __classPrivateFieldGet(this, _KlevuMerchandising_resultObject, "f")) === null || _a === void 0 ? void 0 : _a.records) !== null && _b !== void 0 ? _b : [];
  const allBanners = await __classPrivateFieldGet(this, _KlevuMerchandising_resultObject, "f").getBanners();
  this.searchResultTopBanners = allBanners.filter((b) => b.position === "top");
  this.searchResultBottomBanners = allBanners.filter((b) => b.position === "bottom");
  __classPrivateFieldGet(this, _KlevuMerchandising_instances, "m", _KlevuMerchandising_emitChanges).call(this);
  this.loading = false;
}, _KlevuMerchandising_loadMore = async function _KlevuMerchandising_loadMore() {
  var _a, _b, _c;
  if (!((_a = __classPrivateFieldGet(this, _KlevuMerchandising_resultObject, "f")) === null || _a === void 0 ? void 0 : _a.getPage)) {
    return;
  }
  this.loading = true;
  const nextResultObject = await __classPrivateFieldGet(this, _KlevuMerchandising_resultObject, "f").getPage();
  __classPrivateFieldSet(this, _KlevuMerchandising_resultObject, nextResultObject === null || nextResultObject === void 0 ? void 0 : nextResultObject.queriesById("categoryMerchandising"), "f");
  this.results = [...this.results, ...((_c = (_b = __classPrivateFieldGet(this, _KlevuMerchandising_resultObject, "f")) === null || _b === void 0 ? void 0 : _b.records) !== null && _c !== void 0 ? _c : [])];
  __classPrivateFieldGet(this, _KlevuMerchandising_instances, "m", _KlevuMerchandising_emitChanges).call(this);
  this.loading = false;
}, _KlevuMerchandising_paginationChange = async function _KlevuMerchandising_paginationChange(event) {
  var _a, _b, _c;
  if (!((_a = __classPrivateFieldGet(this, _KlevuMerchandising_resultObject, "f")) === null || _a === void 0 ? void 0 : _a.getPage)) {
    return;
  }
  this.loading = true;
  const nextResultObject = await __classPrivateFieldGet(this, _KlevuMerchandising_resultObject, "f").getPage({ pageIndex: event.detail - 1 });
  __classPrivateFieldSet(this, _KlevuMerchandising_resultObject, nextResultObject === null || nextResultObject === void 0 ? void 0 : nextResultObject.queriesById("categoryMerchandising"), "f");
  this.results = (_c = (_b = __classPrivateFieldGet(this, _KlevuMerchandising_resultObject, "f")) === null || _b === void 0 ? void 0 : _b.records) !== null && _c !== void 0 ? _c : [];
  __classPrivateFieldGet(this, _KlevuMerchandising_instances, "m", _KlevuMerchandising_emitChanges).call(this);
  this.loading = false;
}, _KlevuMerchandising_emitChanges = function _KlevuMerchandising_emitChanges() {
  if (!__classPrivateFieldGet(this, _KlevuMerchandising_resultObject, "f")) {
    return;
  }
  this.klevuData.emit({
    resultObject: __classPrivateFieldGet(this, _KlevuMerchandising_resultObject, "f"),
    records: this.results,
    manager: this.manager,
  });
  this.infiniteScrollingPaused = false;
}, _KlevuMerchandising_sortChanged = async function _KlevuMerchandising_sortChanged(event) {
  this.sort = event.detail;
  await __classPrivateFieldGet(this, _KlevuMerchandising_instances, "m", _KlevuMerchandising_fetchData).call(this);
}, _KlevuMerchandising_sizeChange = function _KlevuMerchandising_sizeChange(event) {
  this.currentViewPortSize = event.detail;
}, _KlevuMerchandising_applyFilters = function _KlevuMerchandising_applyFilters() {
  __classPrivateFieldGet(this, _KlevuMerchandising_instances, "m", _KlevuMerchandising_fetchData).call(this);
  __classPrivateFieldGet(this, _KlevuMerchandising_layoutElement, "f").closeDrawer();
}, _KlevuMerchandising_isMobile = function _KlevuMerchandising_isMobile() {
  var _a, _b;
  return ((_a = this.currentViewPortSize) === null || _a === void 0 ? void 0 : _a.name) === "xs" || ((_b = this.currentViewPortSize) === null || _b === void 0 ? void 0 : _b.name) === "sm";
}, _KlevuMerchandising_mobileDrawerOpened = function _KlevuMerchandising_mobileDrawerOpened() {
  __classPrivateFieldGet(this, _KlevuMerchandising_facetListElement, "f").updateApplyFilterState();
};
KlevuMerchandising.style = klevuMerchandisingCss;

exports.klevu_merchandising = KlevuMerchandising;

//# sourceMappingURL=klevu-merchandising.cjs.entry.js.map