'use strict';

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

const index = require('./index-97fdbb7d.js');
const klevuInit = require('./klevu-init-57de47f9.js');
const parts = require('./parts-295eb56e.js');
const klevuFetch = require('./klevuFetch-d78ab4d9.js');
const kmcRecommendation = require('./kmcRecommendation-5a444405.js');
require('./KlevuDomEvents-f5b92150.js');
require('./isBrowser-e8e10249.js');
require('./KlevuApiRawResponse-7801506a.js');
require('./personalisation-d44c7770.js');

const recommendationTypeOfRequests = [
    klevuFetch.KlevuTypeOfRequest.AlsoBought,
    klevuFetch.KlevuTypeOfRequest.AlsoViewed,
    klevuFetch.KlevuTypeOfRequest.NewArrivals,
    klevuFetch.KlevuTypeOfRequest.SimilarProducts,
    klevuFetch.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, _g, _h, _j;
            // is used with kmcRecommendation query
            if (f.klevuFunctionId === "kmcRecommendation") {
                if (!title) {
                    title = (_c = (_b = (_a = f.params) === null || _a === void 0 ? void 0 : _a.kmcConfig) === null || _b === void 0 ? void 0 : _b.metadata.title) !== null && _c !== void 0 ? _c : "";
                }
                const products = (_f = res.queriesById((_e = (_d = f.queries) === null || _d === void 0 ? void 0 : _d[0].id) !== null && _e !== void 0 ? _e : "")) === null || _f === void 0 ? void 0 : _f.records;
                if (!products) {
                    console.warn("No result in recommendations. Can't send recommendationViewEvent");
                    return res;
                }
                const kmcData = (_g = f.params) === null || _g === void 0 ? void 0 : _g.kmcConfig;
                if (!kmcData) {
                    console.warn("Problem with kmcData fetching. Can't send recommendationViewEvent");
                    return res;
                }
                if (products.length === 0) {
                    return res;
                }
                klevuFetch.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 = (_h = f.queries) === null || _h === void 0 ? void 0 : _h.filter((q) => recommendationTypeOfRequests.includes(q.typeOfRequest));
            if (!queries || (queries === null || queries === void 0 ? void 0 : queries.length) == 0) {
                return res;
            }
            const products = (_j = res.queriesById(queries[0].id)) === null || _j === void 0 ? void 0 : _j.records;
            if (!products) {
                console.warn("No products in result. Can't send recommendationViewEvent");
                return res;
            }
            eventData.title = title !== null && title !== void 0 ? title : eventData.title;
            klevuFetch.KlevuEvents.recommendationView({
                recommendationMetadata: eventData,
                products,
            });
            return res;
        },
    };
}

const klevuRecommendationsCss = ":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 = (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_responseObject;
const KlevuRecommendations = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.klevuData = index.createEvent(this, "klevuData", 7);
    _KlevuRecommendations_responseObject.set(this, void 0);
    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];
  }
  async connectedCallback() {
    var _a, _b;
    await klevuInit.KlevuInit.ready();
    if (!this.recommendationId) {
      throw new Error("recommendationId is required");
    }
    const res = await klevuFetch.KlevuFetch(kmcRecommendation.kmcRecommendation(this.recommendationId, {
      id: "recommendation",
      cartProductIds: this.cartProductIds,
      categoryPath: this.categoryPath,
      currentProductId: this.currentProductId,
      itemGroupId: this.itemGroupId,
    }, sendRecommendationViewEvent(this.recommendationTitle)));
    __classPrivateFieldSet(this, _KlevuRecommendations_responseObject, res.queriesById("recommendation"), "f");
    if (__classPrivateFieldGet(this, _KlevuRecommendations_responseObject, "f")) {
      if (this.recommendationTitle === undefined) {
        this.recommendationTitle = (_b = (_a = __classPrivateFieldGet(this, _KlevuRecommendations_responseObject, "f").getQueryParameters()) === null || _a === void 0 ? void 0 : _a.kmcConfig) === null || _b === void 0 ? void 0 : _b.metadata.title;
      }
      this.products = __classPrivateFieldGet(this, _KlevuRecommendations_responseObject, "f").records;
      this.klevuData.emit(__classPrivateFieldGet(this, _KlevuRecommendations_responseObject, "f"));
    }
  }
  productClick(event) {
    var _a, _b;
    if (((_a = __classPrivateFieldGet(this, _KlevuRecommendations_responseObject, "f")) === null || _a === void 0 ? void 0 : _a.recommendationClickEvent) && event.detail.product.id) {
      (_b = __classPrivateFieldGet(this, _KlevuRecommendations_responseObject, "f")) === null || _b === void 0 ? void 0 : _b.recommendationClickEvent({
        productId: event.detail.product.id,
        variantId: event.detail.product.itemGroupId || event.detail.product.id,
      });
    }
  }
  render() {
    if (this.products.length === 0) {
      return null;
    }
    return (index.h(index.Host, null, index.h("slot", null, index.h("klevu-slides", { heading: this.recommendationTitle }, this.products.map((product) => (index.h("klevu-product", { exportparts: parts.parts["klevu-product"], fixedWidth: true, product: product, style: {
        "--klevu-product-width": "300px",
      } })))))));
  }
};
_KlevuRecommendations_responseObject = new WeakMap();
KlevuRecommendations.style = klevuRecommendationsCss;

exports.klevu_recommendations = KlevuRecommendations;

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