var __classPrivateFieldGet = (this && this.__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 _KlevuProduct_instances, _KlevuProduct_formatSKU, _KlevuProduct_click, _KlevuProduct_addToCart, _KlevuProduct_renderRatings, _KlevuProduct_renderSwatch;
import { h, Host, Fragment } from "@stencil/core";
import { getGlobalSettings, renderPrice } from "../../utils/utils";
import { getKMCSettings } from "../../utils/getKMCSettings";
import { getTranslation } from "../../utils/getTranslation";
import { parts } from "../../utils/parts";
import { KlevuInit } from "../klevu-init/klevu-init";
/**
 * Generic product component that renders product based on KlevuRecord of @klevu/core
 * All parts of the component can be replaced with slots.
 *
 * By default the products fill the whole space, but it can be limited
 * with --kleu-product-width and --klevu-product-small-width css variables.
 *
 * @slot top - Empty are before any product content
 * @slot image - Image region of component
 * @slot info - Swatches, titles, brands and prices slot
 * @slot bottom - Empty are after product content
 * @slot addtocart - Add to cart button slot at the end of the component
 *
 * @csspart product-image - The image element of component
 * @csspart product-container - The container element of whole
 * @csspart product-swatch - Single swatch element under the image
 *
 * @cssprop --klevu-product-width - Width of the product
 * @cssprop --klevu-product-small-width - Width of the product when small variant is used
 * @cssprop --klevu-product-image-aspect-ratio - On what aspect the background image will be
 * @cssprop --klevu-product-image-fill - How to fill image to it's space.
 * @cssprop --klevu-product-border none Border style of the product
 */
export class KlevuProduct {
  constructor() {
    _KlevuProduct_instances.add(this);
    this.variant = "default";
    this.product = undefined;
    this.showAddToCart = undefined;
    this.showRatings = undefined;
    this.showRatingsCount = undefined;
    this.tAddToCart = undefined;
    this.hideSwatches = undefined;
    this.hidePrice = undefined;
    this.hideDescription = undefined;
    this.hideName = undefined;
    this.hideImage = undefined;
    this.hideBrand = undefined;
    this.fixedWidth = undefined;
    this.hideHoverImage = undefined;
    this.keyBrand = "brand";
    this.keyName = "name";
    this.keyDescription = "shortDesc";
    this.vatCaption = undefined;
    this.showProductCode = undefined;
    this.outOfStockCaption = undefined;
    this.fallbackProductImageUrl = undefined;
    this.isWrapper = undefined;
    this.hoverImage = undefined;
  }
  async connectedCallback() {
    var _a;
    await KlevuInit.ready();
    const settings = getKMCSettings();
    if (settings) {
      if (this.tAddToCart === undefined) {
        this.tAddToCart = (_a = settings.klevu_uc_userOptions.addToCartButton) !== null && _a !== void 0 ? _a : getTranslation("product.tAddToCart");
      }
      if (this.showAddToCart === undefined) {
        this.showAddToCart = settings.klevu_addToCartEnabled;
      }
      if (this.hideHoverImage === undefined) {
        this.hideHoverImage = !Boolean(settings.klevu_uc_userOptions.showRolloverImage);
      }
      if (this.hideSwatches === undefined) {
        this.hideSwatches = !Boolean(settings.klevu_uc_userOptions.showProductSwatches);
      }
      if (this.vatCaption === undefined) {
        this.vatCaption = settings.klevu_uc_userOptions.vatCaption;
      }
      if (this.showProductCode === undefined) {
        this.showProductCode = settings.klevu_showProductCode;
      }
      if (this.fallbackProductImageUrl === undefined) {
        this.fallbackProductImageUrl = settings.klevu_uc_userOptions.noImageUrl;
      }
      if (this.outOfStockCaption === undefined) {
        this.outOfStockCaption = settings.klevu_uc_userOptions.outOfStockCaption;
      }
    }
  }
  render() {
    var _a, _b;
    if (this.isWrapper) {
      return (h(Host, null, h("div", { onClick: __classPrivateFieldGet(this, _KlevuProduct_instances, "m", _KlevuProduct_click).bind(this) }, h("slot", null))));
    }
    const typeClasses = {
      small: this.variant === "small",
      line: this.variant === "line",
      default: this.variant === "default",
    };
    const containerClasses = Object.assign({ container: true, fixedWidth: Boolean(this.fixedWidth) }, typeClasses);
    if (!this.product) {
      return (h(Host, { class: Object.assign(Object.assign({}, typeClasses), { loading: true }) }, h("div", { class: containerClasses }, h("div", { class: "loading image" }), h("div", { class: "loading content" }, h("div", null), h("div", null), h("div", null)))));
    }
    const settings = getGlobalSettings();
    const isOnSale = this.product.price != this.product.salePrice;
    return (h(Host, { class: { line: this.variant === "line" } }, h("div", { part: "product-container", class: containerClasses }, h("slot", { name: "top" }), h("a", { href: (_a = settings === null || settings === void 0 ? void 0 : settings.generateProductUrl) === null || _a === void 0 ? void 0 : _a.call(settings, this.product), onClick: __classPrivateFieldGet(this, _KlevuProduct_instances, "m", _KlevuProduct_click).bind(this) }, this.hideImage ? null : (h("slot", { name: "image" }, ((_b = this.product) === null || _b === void 0 ? void 0 : _b.image) || this.hoverImage ? (h("div", { class: "image", part: "product-image", style: {
        backgroundImage: `url(${this.hoverImage || this.product.image}), url(${this.fallbackProductImageUrl})`,
      } }, this.hideHoverImage !== true && this.product.imageHover ? (h("div", { class: "hover", style: {
        backgroundImage: `url(${this.product.imageHover}), url(${this.fallbackProductImageUrl})`,
      } })) : null)) : (h("div", { class: "image no-image", part: "product-image" }, h("klevu-icon", { name: "image_not_supported" }))))), h("slot", { name: "info" }, __classPrivateFieldGet(this, _KlevuProduct_instances, "m", _KlevuProduct_renderSwatch).call(this), h("div", { class: "info" }, this.hideBrand || !this.product[this.keyBrand] ? null : (h("klevu-typography", { class: "brandname", variant: "body-s-bold" }, this.product[this.keyBrand])), this.hideName || !this.product[this.keyName] ? null : (h("klevu-typography", { class: "productname", variant: "body-s" }, `${this.product[this.keyName]} ${this.showProductCode ? __classPrivateFieldGet(this, _KlevuProduct_instances, "m", _KlevuProduct_formatSKU).call(this, this.product.sku) : ""}`)), this.hideDescription || !this.product[this.keyDescription] ? null : (h("klevu-typography", { class: "description", variant: "body-xs" }, this.product[this.keyDescription].substring(0, 100))), this.hidePrice ||
      !this.product.salePrice ||
      !this.product.currency ||
      this.product.inStock === "no" ? null : (h(Fragment, null, h("klevu-typography", { variant: "body-l-bold", class: {
        isOnSale,
        price: true,
      } }, renderPrice(this.product.salePrice, this.product.currency)), this.vatCaption && (h("klevu-typography", { class: "vatcaption", variant: "body-s" }, "(", this.vatCaption, ")")))), this.product.inStock === "no" && this.outOfStockCaption && (h("klevu-typography", { class: "outOfStockCaption", variant: "body-s" }, this.outOfStockCaption)))), this.variant !== "line" && h("slot", { name: "ratings" }, __classPrivateFieldGet(this, _KlevuProduct_instances, "m", _KlevuProduct_renderRatings).call(this)), h("slot", { name: "addtocart" }, this.showAddToCart ? (h("klevu-button", { class: "addToCart", onClick: __classPrivateFieldGet(this, _KlevuProduct_instances, "m", _KlevuProduct_addToCart).bind(this), fullWidth: true, exportparts: parts["klevu-button"] }, this.tAddToCart)) : null)), h("slot", { name: "bottom" }), this.variant === "line" && h("slot", { name: "ratings" }, __classPrivateFieldGet(this, _KlevuProduct_instances, "m", _KlevuProduct_renderRatings).call(this)))));
  }
  static get is() { return "klevu-product"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["klevu-product.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["klevu-product.css"]
    };
  }
  static get properties() {
    return {
      "variant": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "KlevuProductVariant",
          "resolved": "\"default\" | \"line\" | \"small\"",
          "references": {
            "KlevuProductVariant": {
              "location": "local",
              "path": "/home/runner/work/frontend-sdk/frontend-sdk/packages/klevu-ui/src/components/klevu-product/klevu-product.tsx",
              "id": "src/components/klevu-product/klevu-product.tsx::KlevuProductVariant"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "What variant of product to render"
        },
        "attribute": "variant",
        "reflect": false,
        "defaultValue": "\"default\""
      },
      "product": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "Partial<KlevuRecord>",
          "resolved": "undefined | { [x: string]: any; brand?: string | undefined; category?: string | undefined; currency?: string | undefined; deliveryInfo?: string | undefined; discount?: string | undefined; freeShipping?: string | undefined; groupPrices?: string | undefined; hideAddToCart?: string | undefined; hideGroupPrices?: string | undefined; id?: string | undefined; image?: string | undefined; imageHover?: string | undefined; imageUrl?: string | undefined; inStock?: string | undefined; itemGroupId?: string | undefined; klevu_category?: string | undefined; klevu_manual_boosting?: number | undefined; klevu_bulk_boosting?: number | undefined; klevu_selflearning_boosting?: number | undefined; name?: string | undefined; price?: string | undefined; rating?: number | undefined; salePrice?: string | undefined; shortDesc?: string | undefined; sku?: string | undefined; score?: number | undefined; startPrice?: string | undefined; storeBaseCurrency?: string | undefined; swatchesInfo?: string | undefined; tags?: string | undefined; toPrice?: string | undefined; totalVariants?: number | undefined; type?: string | undefined; typeOfRecord?: KlevuAnyTypeOfRecord | undefined; url?: string | undefined; weight?: string | undefined; swatches?: { id: string; color: string; swatchImage: string; image: string; numberOfAdditionalVariants: string; }[] | undefined; }",
          "references": {
            "Partial": {
              "location": "global",
              "id": "global::Partial"
            },
            "KlevuRecord": {
              "location": "import",
              "path": "@klevu/core",
              "id": "../klevu-core/dist/cjs/index.d.ts::KlevuRecord"
            }
          }
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Product data"
        }
      },
      "showAddToCart": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Show add to cart button"
        },
        "attribute": "show-add-to-cart",
        "reflect": false
      },
      "showRatings": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Show ratings"
        },
        "attribute": "show-ratings",
        "reflect": false
      },
      "showRatingsCount": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Show ratings"
        },
        "attribute": "show-ratings-count",
        "reflect": false
      },
      "tAddToCart": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Text for add to cart button"
        },
        "attribute": "t-add-to-cart",
        "reflect": false
      },
      "hideSwatches": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Do not show swatches in products"
        },
        "attribute": "hide-swatches",
        "reflect": false
      },
      "hidePrice": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Hides price from info"
        },
        "attribute": "hide-price",
        "reflect": false
      },
      "hideDescription": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Hides description from info"
        },
        "attribute": "hide-description",
        "reflect": false
      },
      "hideName": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Hides name from info"
        },
        "attribute": "hide-name",
        "reflect": false
      },
      "hideImage": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Hides image"
        },
        "attribute": "hide-image",
        "reflect": false
      },
      "hideBrand": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Hides brand information"
        },
        "attribute": "hide-brand",
        "reflect": false
      },
      "fixedWidth": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Force certain width for product. Do not use max-width"
        },
        "attribute": "fixed-width",
        "reflect": false
      },
      "hideHoverImage": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "When mousing over product, show hover image if available"
        },
        "attribute": "hide-hover-image",
        "reflect": false
      },
      "keyBrand": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "What key to use for brand value"
        },
        "attribute": "key-brand",
        "reflect": false,
        "defaultValue": "\"brand\""
      },
      "keyName": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "What key to use for name value"
        },
        "attribute": "key-name",
        "reflect": false,
        "defaultValue": "\"name\""
      },
      "keyDescription": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "What key to use for description value"
        },
        "attribute": "key-description",
        "reflect": false,
        "defaultValue": "\"shortDesc\""
      },
      "vatCaption": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Text to be added after the price. Usually used to indicate that does the price include VAT or not."
        },
        "attribute": "vat-caption",
        "reflect": false
      },
      "showProductCode": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "To show the product code next to product name."
        },
        "attribute": "show-product-code",
        "reflect": false
      },
      "outOfStockCaption": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Caption to show if product is out of stock"
        },
        "attribute": "out-of-stock-caption",
        "reflect": false
      },
      "fallbackProductImageUrl": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Fallback image url to be used when the product image fails to load."
        },
        "attribute": "fallback-product-image-url",
        "reflect": false
      },
      "isWrapper": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Turns the component into a product wrapper that handles events\nautomatically. It assumes that whole product is clickable.\n\nComponent has only one main slot that can contain any content.\n\nTo prevent product clicking use `event.stopPropagation()` in your\nevents.\n\nComponent still requires the product parameter as it's data is used\nsend correct data to Klevu analytics"
        },
        "attribute": "is-wrapper",
        "reflect": false
      }
    };
  }
  static get states() {
    return {
      "hoverImage": {}
    };
  }
  static get events() {
    return [{
        "method": "klevuProductClick",
        "name": "klevuProductClick",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": "When products has been clicked"
        },
        "complexType": {
          "original": "KlevuProductOnProductClick",
          "resolved": "{ product: Partial<KlevuRecord>; originalEvent: MouseEvent; }",
          "references": {
            "KlevuProductOnProductClick": {
              "location": "local",
              "path": "/home/runner/work/frontend-sdk/frontend-sdk/packages/klevu-ui/src/components/klevu-product/klevu-product.tsx",
              "id": "src/components/klevu-product/klevu-product.tsx::KlevuProductOnProductClick"
            }
          }
        }
      }];
  }
}
_KlevuProduct_instances = new WeakSet(), _KlevuProduct_formatSKU = function _KlevuProduct_formatSKU(sku) {
  if (!sku) {
    return "";
  }
  let formattedSKU = sku.toUpperCase();
  if (sku.includes(";;;;")) {
    formattedSKU = formattedSKU.split(";;;;")[0];
  }
  if (formattedSKU.startsWith("(") && formattedSKU.endsWith(")")) {
    return formattedSKU;
  }
  else {
    return "(" + formattedSKU + ")";
  }
}, _KlevuProduct_click = function _KlevuProduct_click(ev) {
  const settings = getGlobalSettings();
  if (!this.product) {
    return;
  }
  const sentEvent = this.klevuProductClick.emit({
    product: this.product,
    originalEvent: ev,
  });
  if (sentEvent.defaultPrevented) {
    ev.preventDefault();
    return false;
  }
  if (settings === null || settings === void 0 ? void 0 : settings.onItemClick) {
    try {
      const result = settings.onItemClick(this.product, ev);
      if (result === false) {
        ev.preventDefault();
        return false;
      }
    }
    catch (e) {
      console.error(e);
      ev.preventDefault();
      return false;
    }
  }
}, _KlevuProduct_addToCart = function _KlevuProduct_addToCart(event) {
  event.stopPropagation();
  const settings = getGlobalSettings();
  if (!this.product || !(settings === null || settings === void 0 ? void 0 : settings.addToCart)) {
    return;
  }
  settings.addToCart(this.product, event);
}, _KlevuProduct_renderRatings = function _KlevuProduct_renderRatings() {
  var _a;
  return (this.showRatings && (h("div", { class: "ratings" }, ((_a = this.product) === null || _a === void 0 ? void 0 : _a.rating) ? (h(Fragment, null, h("klevu-rating", { rating: this.product.rating }), this.showRatingsCount && this.product.ratingCount && h("span", null, "(", this.product.ratingCount, ")"))) : (h("span", null, "\u00A0")))));
}, _KlevuProduct_renderSwatch = function _KlevuProduct_renderSwatch() {
  var _a, _b;
  if (this.hideSwatches) {
    return null;
  }
  const swatches = [];
  if (!this.hideSwatches) {
    const swatchesParts = (_b = (_a = this.product) === null || _a === void 0 ? void 0 : _a.swatchesInfo) === null || _b === void 0 ? void 0 : _b.split(" ;;;; ");
    for (const sPart of swatchesParts !== null && swatchesParts !== void 0 ? swatchesParts : []) {
      const splitPos = sPart.indexOf(":");
      const key = sPart.substring(0, splitPos);
      const value = sPart.substring(splitPos + 1);
      for (const keyStart of ["variantId", "variantColor", "variantImage", "variantSwatchImage"]) {
        if (key.startsWith(keyStart)) {
          const index = parseInt(key.substring(keyStart.length)) - 1;
          if (!swatches[index]) {
            swatches[index] = {};
          }
          // @ts-expect-error
          swatches[index][keyStart.substring("variant".length)] = value;
        }
      }
    }
  }
  if (swatches.length === 0) {
    return null;
  }
  return (h("div", { class: "swatches", onMouseLeave: () => (this.hoverImage = undefined) }, swatches.map((swatch) => (h("div", { part: "product-swatch", style: {
      backgroundColor: swatch.Color
        ? CSS.supports("color", swatch.Color)
          ? swatch.Color
          : "lightgray"
        : "lightgray",
      backgroundImage: swatch.SwatchImage || swatch.Image ? `url(${swatch.SwatchImage || swatch.Image})` : undefined,
    }, onMouseEnter: () => (this.hoverImage = swatch.Image) })))));
};
//# sourceMappingURL=klevu-product.js.map
