'use strict';

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

const index = require('./index-6b50a234.js');
const klevuInit = require('./klevu-init-0ddd3486.js');
const partsExports = require('./partsExports-67956c7b.js');
const klevuFetch = require('./klevuFetch-cb6905ea.js');
const kmcRecommendation = require('./kmcRecommendation-7a1d804c.js');
require('./KlevuDomEvents-f5b92150.js');
require('./isBrowser-e8e10249.js');
require('./KlevuApiRawResponse-7801506a.js');
require('./personalisation-2ed36bb0.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(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") {
                let products;
                if (res.queryExists((_c = (_b = (_a = f.queries) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : "")) {
                    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;
                }
                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;
                }
                klevuFetch.KlevuEvents.recommendationView({
                    recommendationMetadata: Object.assign({}, kmcData.metadata),
                    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;
            }
            klevuFetch.KlevuEvents.recommendationView({
                recommendationMetadata: eventData,
                products,
            });
            return res;
        },
    };
}

const klevuRecommendationsCss = ":host{display:block}.staticImage klevu-banner::part(banner-image){max-width:1100px;max-height:265px}.staticImage.isMobile klevu-banner::part(banner-image){max-width:375px;max-height:115px}";

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 _KlevuRecommendations_instances, _KlevuRecommendations_responseObject, _KlevuRecommendations_staticContent, _KlevuRecommendations_sizeChange, _KlevuRecommendations_isMobile, _KlevuRecommendations_setCurrentImageDetails, _KlevuRecommendations_staticBannerClick;
const KlevuRecommendations = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.klevuData = index.createEvent(this, "klevuData", 7);
    _KlevuRecommendations_instances.add(this);
    _KlevuRecommendations_responseObject.set(this, void 0);
    _KlevuRecommendations_staticContent.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];
    this.currentViewPortSize = undefined;
    this.imageDetails = undefined;
  }
  async connectedCallback() {
    var _a;
    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()));
    if (res.queryExists("recommendation")) {
      __classPrivateFieldSet(this, _KlevuRecommendations_responseObject, res.queriesById("recommendation"), "f");
      const kmcConfig = (_a = __classPrivateFieldGet(this, _KlevuRecommendations_responseObject, "f").getQueryParameters()) === null || _a === void 0 ? void 0 : _a.kmcConfig;
      if (kmcConfig) {
        if (this.recommendationTitle === undefined) {
          this.recommendationTitle = kmcConfig.metadata.title;
        }
        __classPrivateFieldSet(this, _KlevuRecommendations_staticContent, kmcConfig.staticContent, "f");
        __classPrivateFieldGet(this, _KlevuRecommendations_instances, "m", _KlevuRecommendations_setCurrentImageDetails).call(this);
      }
      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.variantId || event.detail.product.id,
      });
    }
  }
  render() {
    if (!__classPrivateFieldGet(this, _KlevuRecommendations_staticContent, "f") && this.products.length === 0) {
      return null;
    }
    return (index.h(index.Host, null, index.h("slot", null, index.h("klevu-util-viewport", { onKlevuSizeChanged: __classPrivateFieldGet(this, _KlevuRecommendations_instances, "m", _KlevuRecommendations_sizeChange).bind(this) }), __classPrivateFieldGet(this, _KlevuRecommendations_staticContent, "f") && __classPrivateFieldGet(this, _KlevuRecommendations_staticContent, "f").length > 0 && this.imageDetails ? (index.h("div", { class: { staticImage: true, isMobile: __classPrivateFieldGet(this, _KlevuRecommendations_instances, "m", _KlevuRecommendations_isMobile).call(this) } }, index.h("klevu-banner", { exportparts: partsExports.partsExports("klevu-banner"), onKlevuBannerClick: __classPrivateFieldGet(this, _KlevuRecommendations_instances, "m", _KlevuRecommendations_staticBannerClick).bind(this), altText: this.imageDetails.altTag, imageUrl: this.imageDetails.url, linkUrl: __classPrivateFieldGet(this, _KlevuRecommendations_staticContent, "f")[0].targetUrl, target: "_self" }))) : this.products ? (index.h("klevu-slides", { exportparts: partsExports.partsExports("klevu-slides"), heading: this.recommendationTitle }, this.products.map((product) => (index.h("klevu-product", { exportparts: partsExports.partsExports("klevu-product"), fixedWidth: true, product: product, style: {
        "--klevu-product-width": "300px",
      } }))))) : null)));
  }
};
_KlevuRecommendations_responseObject = new WeakMap(), _KlevuRecommendations_staticContent = new WeakMap(), _KlevuRecommendations_instances = new WeakSet(), _KlevuRecommendations_sizeChange = function _KlevuRecommendations_sizeChange(event) {
  this.currentViewPortSize = event.detail;
  __classPrivateFieldGet(this, _KlevuRecommendations_instances, "m", _KlevuRecommendations_setCurrentImageDetails).call(this);
}, _KlevuRecommendations_isMobile = function _KlevuRecommendations_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";
}, _KlevuRecommendations_setCurrentImageDetails = function _KlevuRecommendations_setCurrentImageDetails() {
  if (!__classPrivateFieldGet(this, _KlevuRecommendations_staticContent, "f") || __classPrivateFieldGet(this, _KlevuRecommendations_staticContent, "f").length === 0) {
    return;
  }
  let image;
  if (__classPrivateFieldGet(this, _KlevuRecommendations_instances, "m", _KlevuRecommendations_isMobile).call(this)) {
    image = __classPrivateFieldGet(this, _KlevuRecommendations_staticContent, "f")[0].image.find((i) => i.resolution === "mobile");
    if (!image) {
      image = __classPrivateFieldGet(this, _KlevuRecommendations_staticContent, "f")[0].image.find((i) => i.resolution === "desktop");
    }
  }
  else {
    image = __classPrivateFieldGet(this, _KlevuRecommendations_staticContent, "f")[0].image.find((i) => i.resolution === "desktop");
  }
  if (!image) {
    return;
  }
  this.imageDetails = {
    url: image.url,
    altTag: image.altTag,
  };
}, _KlevuRecommendations_staticBannerClick = function _KlevuRecommendations_staticBannerClick() {
  var _a, _b;
  (_b = (_a = __classPrivateFieldGet(this, _KlevuRecommendations_responseObject, "f")) === null || _a === void 0 ? void 0 : _a.recommendationBannerClickEvent) === null || _b === void 0 ? void 0 : _b.call(_a, {
    resolution: __classPrivateFieldGet(this, _KlevuRecommendations_instances, "m", _KlevuRecommendations_isMobile).call(this) ? "mobile" : "desktop",
  });
};
KlevuRecommendations.style = klevuRecommendationsCss;

exports.klevu_recommendations = KlevuRecommendations;

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