import { proxyCustomElement, HTMLElement, h, Host } from '@stencil/core/internal/client';
import { K as KlevuInit } from './klevu-init2.js';
import { p as parts } from './parts.js';
import { d as defineCustomElement$7 } from './klevu-button2.js';
import { d as defineCustomElement$6 } from './klevu-icon2.js';
import { d as defineCustomElement$5 } from './klevu-product2.js';
import { d as defineCustomElement$4 } from './klevu-slides2.js';
import { d as defineCustomElement$3 } from './klevu-typography2.js';
import { d as defineCustomElement$2 } from './klevu-util-scrollbars2.js';
import { b as KlevuEvents, c as KlevuTypeOfRequest, K as KlevuFetch } from './klevuFetch.js';
import { k as kmcRecommendation } from './kmcRecommendation.js';
import './KlevuDomEvents.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 __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_instances, _KlevuRecommendations_responseObject, _KlevuRecommendations_internalRenderProductSlot, _KlevuRecommendations_productClick;
const KlevuRecommendations$1 = /*@__PURE__*/ proxyCustomElement(class KlevuRecommendations extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.__attachShadow();
    _KlevuRecommendations_instances.add(this);
    _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];
    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)));
    __classPrivateFieldSet(this, _KlevuRecommendations_responseObject, res.queriesById("recommendation"), "f");
    if (__classPrivateFieldGet(this, _KlevuRecommendations_responseObject, "f")) {
      this.products = __classPrivateFieldGet(this, _KlevuRecommendations_responseObject, "f").records;
    }
  }
  render() {
    if (this.products.length === 0) {
      return null;
    }
    return (h(Host, null, h("klevu-slides", { 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")))))));
  }
  static get style() { return klevuRecommendationsCss; }
}, [1, "klevu-recommendations", {
    "recommendationTitle": [1, "recommendation-title"],
    "recommendationId": [1, "recommendation-id"],
    "cartProductIds": [16],
    "categoryPath": [1, "category-path"],
    "currentProductId": [1, "current-product-id"],
    "itemGroupId": [1, "item-group-id"],
    "renderProductSlot": [16],
    "products": [32]
  }]);
_KlevuRecommendations_responseObject = new WeakMap(), _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) {
  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,
    });
  }
};
function defineCustomElement$1() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["klevu-recommendations", "klevu-button", "klevu-icon", "klevu-product", "klevu-slides", "klevu-typography", "klevu-util-scrollbars"];
  components.forEach(tagName => { switch (tagName) {
    case "klevu-recommendations":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, KlevuRecommendations$1);
      }
      break;
    case "klevu-button":
      if (!customElements.get(tagName)) {
        defineCustomElement$7();
      }
      break;
    case "klevu-icon":
      if (!customElements.get(tagName)) {
        defineCustomElement$6();
      }
      break;
    case "klevu-product":
      if (!customElements.get(tagName)) {
        defineCustomElement$5();
      }
      break;
    case "klevu-slides":
      if (!customElements.get(tagName)) {
        defineCustomElement$4();
      }
      break;
    case "klevu-typography":
      if (!customElements.get(tagName)) {
        defineCustomElement$3();
      }
      break;
    case "klevu-util-scrollbars":
      if (!customElements.get(tagName)) {
        defineCustomElement$2();
      }
      break;
  } });
}
defineCustomElement$1();

const KlevuRecommendations = KlevuRecommendations$1;
const defineCustomElement = defineCustomElement$1;

export { KlevuRecommendations, defineCustomElement };

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