import { r as registerInstance, h, H as Host } from './index-89bb9d20.js';
import { g as globalExportedParts } from './utils-d0a0ba1d.js';
import { K as KlevuInit } from './klevu-init-c76243a7.js';
import { p as parts } from './parts-a86835f2.js';
import { b as KlevuEvents, c as KlevuTypeOfRequest, K as KlevuFetch } from './applyFilterWithManager-7edd4c12.js';
import { k as kmcRecommendation } from './kmcRecommendation-195deb93.js';
import './KlevuSearchSorting-18fcc39a.js';
import './isBrowser-0ab0def8.js';

const recommendationTypeOfRequests = [
    KlevuTypeOfRequest.AlsoBought,
    KlevuTypeOfRequest.AlsoViewed,
    KlevuTypeOfRequest.NewArrivals,
    KlevuTypeOfRequest.SimilarProducts,
    KlevuTypeOfRequest.Trending,
];
/**
 * This modifier should be used with all recommendation requests. It sends
 * correct event data to klevu backend on recommendation view
 *
 * @category Modifier
 * @returns
 */
function sendRecommendationViewEvent(title, eventData, override) {
    return {
        klevuModifierId: "sendMerchandisingViewEvent",
        onResult: (res, f) => {
            var _a, _b, _c, _d, _e, _f;
            // is used with kmcRecommendation query
            if (f.klevuFunctionId === "kmcRecommendation") {
                const products = (_c = res.queriesById((_b = (_a = f.queries) === null || _a === void 0 ? void 0 : _a[0].id) !== null && _b !== void 0 ? _b : "")) === null || _c === void 0 ? void 0 : _c.records;
                if (!products) {
                    console.warn("No result in recommendations. Can't send recommendationViewEvent");
                    return res;
                }
                const kmcData = (_d = f.params) === null || _d === void 0 ? void 0 : _d.kmcConfig;
                if (!kmcData) {
                    console.warn("Problem with kmcData fetching. Can't send recommendationViewEvent");
                    return res;
                }
                if (products.length === 0) {
                    return res;
                }
                KlevuEvents.recommendationView({
                    recommendationMetadata: Object.assign(Object.assign({}, kmcData.metadata), { title }),
                    products,
                    override,
                });
                return res;
            }
            if (!eventData) {
                throw new Error("Need to provider eventData parameter for custom view events");
            }
            const queries = (_e = f.queries) === null || _e === void 0 ? void 0 : _e.filter((q) => recommendationTypeOfRequests.includes(q.typeOfRequest));
            if (!queries || (queries === null || queries === void 0 ? void 0 : queries.length) == 0) {
                return res;
            }
            const products = (_f = res.queriesById(queries[0].id)) === null || _f === void 0 ? void 0 : _f.records;
            if (!products) {
                console.warn("No products in result. Can't send recommendationViewEvent");
                return res;
            }
            KlevuEvents.recommendationView({
                recommendationMetadata: Object.assign(Object.assign({}, eventData), { title }),
                products,
            });
            return res;
        },
    };
}

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

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 _KlevuRecommendations_instances, _KlevuRecommendations_internalRenderProductSlot, _KlevuRecommendations_productClick;
const KlevuRecommendations = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    _KlevuRecommendations_instances.add(this);
    this.recommendationTitle = undefined;
    this.recommendationId = undefined;
    this.cartProductIds = undefined;
    this.categoryPath = undefined;
    this.currentProductId = undefined;
    this.itemGroupId = undefined;
    this.products = [undefined, undefined, undefined, undefined, undefined, undefined];
    this.clickEvent = undefined;
    this.renderProductSlot = undefined;
  }
  async connectedCallback() {
    await KlevuInit.ready();
    if (!this.recommendationId) {
      throw new Error("recommendationId is required");
    }
    const res = await KlevuFetch(kmcRecommendation(this.recommendationId, {
      id: "recommendation",
      cartProductIds: this.cartProductIds,
      categoryPath: this.categoryPath,
      currentProductId: this.currentProductId,
      itemGroupId: this.itemGroupId,
    }, sendRecommendationViewEvent(this.recommendationTitle)));
    const resultObject = res.queriesById("recommendation");
    if (resultObject) {
      this.products = resultObject.records;
      if (resultObject.getRecommendationClickSendEvent) {
        this.clickEvent = resultObject.getRecommendationClickSendEvent();
      }
    }
  }
  render() {
    if (this.products.length === 0) {
      return null;
    }
    return (h(Host, null, h("klevu-slides", { exportparts: globalExportedParts, heading: this.recommendationTitle }, this.products.map((product) => (h("klevu-product", { exportparts: parts["klevu-product"], fixedWidth: true, onKlevuProductClick: __classPrivateFieldGet(this, _KlevuRecommendations_instances, "m", _KlevuRecommendations_productClick).bind(this), product: product, style: {
        "--klevu-product-width": "300px",
      } }, __classPrivateFieldGet(this, _KlevuRecommendations_instances, "m", _KlevuRecommendations_internalRenderProductSlot).call(this, product, "top"), __classPrivateFieldGet(this, _KlevuRecommendations_instances, "m", _KlevuRecommendations_internalRenderProductSlot).call(this, product, "image"), __classPrivateFieldGet(this, _KlevuRecommendations_instances, "m", _KlevuRecommendations_internalRenderProductSlot).call(this, product, "info"), __classPrivateFieldGet(this, _KlevuRecommendations_instances, "m", _KlevuRecommendations_internalRenderProductSlot).call(this, product, "bottom")))))));
  }
};
_KlevuRecommendations_instances = new WeakSet(), _KlevuRecommendations_internalRenderProductSlot = function _KlevuRecommendations_internalRenderProductSlot(product, slot) {
  if (!this.renderProductSlot || !product) {
    return null;
  }
  const content = this.renderProductSlot(product, slot);
  if (content === null) {
    return null;
  }
  if (typeof content === "string") {
    return h("div", { slot: slot, innerHTML: content });
  }
  return (h("div", { slot: slot, ref: (el) => {
      if (!el) {
        return;
      }
      el.innerHTML = "";
      el.appendChild(content);
    } }));
}, _KlevuRecommendations_productClick = function _KlevuRecommendations_productClick(event) {
  if (this.clickEvent && event.detail.product.id) {
    this.clickEvent(event.detail.product.id, event.detail.product.itemGroupId || event.detail.product.id);
  }
};
KlevuRecommendations.style = klevuRecommendationsCss;

export { KlevuRecommendations as klevu_recommendations };

//# sourceMappingURL=klevu-recommendations.entry.js.map