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 _KlevuInit_instances, _KlevuInit_renderPriceKMCSettings;
import { KlevuConfig, KlevuKMCSettings } from "@klevu/core";
import { h, Host } from "@stencil/core";
/**
 *
 * `klevu-init` is the most important component of the whole library. Place one in your document. It should be
 * one of the first ones in the `<body>` tag. Currently only one `klevu-init` per page is supported. It is used to define
 * configuration for all components on the page and provide few global settings for all components:
 *
 * - **onItemClick:** what happens when product is clicked. Typically this places default action of
 *   _klevu-product_ click. For example you can make your own frontend router to act in this function. Is
 *   provided with product and click event as attributes. Remember to preventDefault and return false to prevent anchor
 *   link following.
 * - **generateProductUrl:** what kind of URL's should be generated for products. If _onItemClick_
 *   is not used this can be used for it. Has product as attribute.
 * - **renderPrice:** generic function for price rendering. If you wish to have your own formatting for price
 *   rendering then this is the place. Has two attribute amount and currency of item.
 * Initializes components to fetch data from correct Klevu backend
 *
 *
 * **Note: All global CSS variables are documented in `klevu-init` even thought they are not defined in it.**
 *
 */
export class KlevuInit {
  constructor() {
    _KlevuInit_instances.add(this);
    this.apiKey = undefined;
    this.url = undefined;
    this.eventsV1Url = undefined;
    this.eventsV2Url = undefined;
    this.recommendationsApiUrl = undefined;
    this.settings = undefined;
    this.language = "en";
    this.translation = undefined;
    this.translationUrlPrefix = undefined;
    this.kmcLoadDefaults = undefined;
  }
  async connectedCallback() {
    var _a, _b;
    KlevuConfig.init({
      apiKey: this.apiKey,
      url: this.url,
      eventsApiV1Url: this.eventsV1Url,
      eventsApiV2Url: this.eventsV2Url,
      recommendationsApiUrl: this.recommendationsApiUrl,
    });
    if (this.translation) {
      window["klevu_ui_translations"] = this.translation;
    }
    else if (this.language && this.language != "en") {
      window["klevu_ui_translations"] = await fetchTranslation(this.language, this.translationUrlPrefix);
    }
    if (this.kmcLoadDefaults) {
      const data = await KlevuKMCSettings();
      window["klevu_ui_kmc_settings"] = data.root;
      if (((_a = this.settings) === null || _a === void 0 ? void 0 : _a.renderPrice) === undefined) {
        const priceSettings = (_b = data.root) === null || _b === void 0 ? void 0 : _b.klevu_uc_userOptions.priceFormatter;
        if (priceSettings) {
          this.settings = Object.assign(Object.assign({}, (this.settings || {})), { renderPrice: (...params) => __classPrivateFieldGet(this, _KlevuInit_instances, "m", _KlevuInit_renderPriceKMCSettings).call(this, ...params, priceSettings) });
        }
      }
    }
    if (this.settings) {
      window["klevu_ui_settings"] = this.settings;
    }
  }
  /**
   *
   * @returns KlevuConfig, but due to typescript problems it is any
   */
  async getConfig() {
    return KlevuConfig.getDefault();
  }
  /**
   * Get settings defined in klevu-init
   *
   * @returns
   */
  async getSettings() {
    return this.settings;
  }
  /**
   * To make sure that components in the page wait for klevu-init to run and set the settings this method is required to use.
   * In `connectedCallback()` function should call this method. So for example:
   *
   * ```
   * async connectedCallback() {
   *   await KlevuInit.ready()
   * }
   * ```
   *
   * @returns Promise when klevu-init is loaded
   */
  static ready() {
    var _a;
    return (_a = document.querySelector("klevu-init")) === null || _a === void 0 ? void 0 : _a.componentOnReady();
  }
  render() {
    return (h(Host, null, h("slot", null)));
  }
  static get is() { return "klevu-init"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["klevu-init.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["klevu-init.css"]
    };
  }
  static get properties() {
    return {
      "apiKey": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": true,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Read only API key to Klevu"
        },
        "attribute": "api-key",
        "reflect": false
      },
      "url": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": true,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Klevu Server URL"
        },
        "attribute": "url",
        "reflect": false
      },
      "eventsV1Url": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Override the default events v1 URL"
        },
        "attribute": "events-v-1-url",
        "reflect": false
      },
      "eventsV2Url": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Override the default events v2 URL"
        },
        "attribute": "events-v-2-url",
        "reflect": false
      },
      "recommendationsApiUrl": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Override the default recommendations API URL"
        },
        "attribute": "recommendations-api-url",
        "reflect": false
      },
      "settings": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "KlevuUIGlobalSettings",
          "resolved": "undefined | ({ onItemClick?: ((item: Partial<KlevuRecord>, event: MouseEvent) => boolean) | undefined; generateProductUrl?: ((product: Partial<KlevuRecord>) => string) | undefined; renderPrice?: ((amount: string | number, currency: string) => string) | undefined; icons?: { [key: string]: string; } | undefined; useNativeScrollbars?: boolean | undefined; })",
          "references": {
            "KlevuUIGlobalSettings": {
              "location": "import",
              "path": "../../utils/utils",
              "id": "src/utils/utils.ts::KlevuUIGlobalSettings"
            }
          }
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Global settings"
        }
      },
      "language": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "Translations",
          "resolved": "\"en\" | \"fi\"",
          "references": {
            "Translations": {
              "location": "local",
              "path": "/home/runner/work/frontend-sdk/frontend-sdk/packages/klevu-ui/src/components/klevu-init/klevu-init.tsx",
              "id": "src/components/klevu-init/klevu-init.tsx::Translations"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": "Which language to load"
        },
        "attribute": "language",
        "reflect": false,
        "defaultValue": "\"en\""
      },
      "translation": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "Translation",
          "resolved": "undefined | { chatBubble: { tRatingReason: string; }; cmsList: { tCaption: string; }; facet: { tMore: string; tAll: string; }; latestSearches: { tCaption: string; }; merchandising: { tLoadMore: string; }; popularSearches: { tCaption: string; }; product: { tAddToCart: string; }; productQueryPopup: { tTextFieldPlaceholder: string; tPopuptitle: string; tButtonText: string; tFinePrint: string; tLoadingSorry: string; tRateExperienceTitle: string; tRateExperienceText: string; tDataProtectionNotice: string; }; quicksearch: { tSearchResults: string; tStartChat: string; tCategoriesCaption: string; tTrendingCaption: string; tPopularProductsTitle: string; tLastClickedProductsCaption: string; }; searchField: { tPlaceholder: string; tSearchText: string; }; searchLandingPage: { tSearchTitle: string; tLoadMore: string; tNoResultsFound: string; }; sort: { tRelevance: string; tNameAsc: string; tNameDesc: string; tNewArrivalsAsc: string; tNewArrivalsDesc: string; tPriceAsc: string; tPriceDesc: string; tRatingAsc: string; tRatingDesc: string; }; }",
          "references": {
            "Translation": {
              "location": "local",
              "path": "/home/runner/work/frontend-sdk/frontend-sdk/packages/klevu-ui/src/components/klevu-init/klevu-init.tsx",
              "id": "src/components/klevu-init/klevu-init.tsx::Translation"
            }
          }
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Provide your own translations"
        }
      },
      "translationUrlPrefix": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Override the default translation URL prefix. Will use format of\n`${translationUrlPrefix}/translations/${lang}.json`"
        },
        "attribute": "translation-url-prefix",
        "reflect": false
      },
      "kmcLoadDefaults": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "kmc-load-defaults",
        "reflect": false
      }
    };
  }
  static get methods() {
    return {
      "getConfig": {
        "complexType": {
          "signature": "() => Promise<any>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global",
              "id": "global::Promise"
            }
          },
          "return": "Promise<any>"
        },
        "docs": {
          "text": "",
          "tags": [{
              "name": "returns",
              "text": "KlevuConfig, but due to typescript problems it is any"
            }]
        }
      },
      "getSettings": {
        "complexType": {
          "signature": "() => Promise<KlevuUIGlobalSettings | undefined>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global",
              "id": "global::Promise"
            },
            "KlevuUIGlobalSettings": {
              "location": "import",
              "path": "../../utils/utils",
              "id": "src/utils/utils.ts::KlevuUIGlobalSettings"
            }
          },
          "return": "Promise<KlevuUIGlobalSettings | undefined>"
        },
        "docs": {
          "text": "Get settings defined in klevu-init",
          "tags": [{
              "name": "returns",
              "text": undefined
            }]
        }
      }
    };
  }
}
_KlevuInit_instances = new WeakSet(), _KlevuInit_renderPriceKMCSettings = function _KlevuInit_renderPriceKMCSettings(amount, currency, priceSettings) {
  // Format amount to decimal
  let formattedAmount = new Intl.NumberFormat(undefined, {
    maximumFractionDigits: parseInt(priceSettings.decimalPlaces, 10),
  }).format(parseFloat(amount.toString()));
  let [integerPart, decimalPart = ""] = formattedAmount.split(".");
  // Replace thousands separator
  formattedAmount = integerPart.replace(/,/, priceSettings.thousandSeparator);
  // Combine back with decimal separator if exists
  if (decimalPart) {
    formattedAmount += priceSettings.decimalSeparator + decimalPart;
  }
  if (priceSettings.appendCurrencyAtLast) {
    formattedAmount = `${formattedAmount} ${priceSettings.currencySymbol}`;
  }
  else {
    formattedAmount = `${priceSettings.currencySymbol} ${formattedAmount}`;
  }
  return formattedAmount;
};
async function fetchTranslation(lang, urlPrefix) {
  // when not provided try loading translations from two folders up in the url
  if (!urlPrefix) {
    const parts = import.meta.url.split("/");
    parts.splice(-2, 2);
    urlPrefix = parts.join("/");
  }
  return new Promise((resolve, reject) => {
    fetch(`${urlPrefix}/translations/${lang}.json`).then((result) => {
      if (result.ok)
        resolve(result.json());
      else
        reject();
    }, () => reject());
  });
}
//# sourceMappingURL=klevu-init.js.map
