import { proxyCustomElement, HTMLElement, createEvent, h, Host } from '@stencil/core/internal/client';
import { i as isBrowser, K as KlevuStorage, a as KlevuConfig, g as get } from './config.js';

var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
const url = "https://js.klevu.com/klevu-js-v1/klevu-js-api/";
const STORAGE_KEY = "klevu-kmc-data";
const STORAGE_TS_KEY = "klevu-kmc-data-ts";
const ONE_DAY = 86400000;
/**
 * Fetches KMC settings from server. Caches data for a day.
 *
 * @category KlevuFetch
 * @param ignoreCache If true, will ignore cache and fetch data from server
 * @param cacheLength How long to cache data in milliseconds
 * @returns
 */
function KlevuKMCSettings(ignoreCache, cacheLength = ONE_DAY, overrideUrl = "") {
    return __awaiter(this, void 0, void 0, function* () {
        if (isBrowser() && window.localStorage && ignoreCache !== true) {
            const ts = KlevuStorage.getItem(STORAGE_TS_KEY);
            const res = KlevuStorage.getItem(STORAGE_KEY);
            if (res && ts && new Date().getTime() - parseInt(ts, 10) < cacheLength) {
                return JSON.parse(res);
            }
        }
        const start = `${overrideUrl || url}${KlevuConfig.getDefault().apiKey}`;
        const res = yield Promise.all([
            get(`${start}.json`),
            get(`${start}-banner.json`),
            get(`${start}-maps.json`),
        ]);
        const data = {
            root: res[0],
            banner: res[1],
            maps: res[2],
        };
        if (isBrowser() && window.localStorage) {
            KlevuStorage.setItem(STORAGE_KEY, JSON.stringify(data));
            KlevuStorage.setItem(STORAGE_TS_KEY, new Date().getTime().toString());
        }
        return data;
    });
}

const klevuInitCss = ":host{}";

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 _KlevuInit_instances, _KlevuInit_settingsDefined, _KlevuInit_defineSettings, _KlevuInit_renderPriceKMCSettings;
const KlevuInit = /*@__PURE__*/ proxyCustomElement(class KlevuInit extends HTMLElement {
  constructor() {
    super();
    this.__registerHost();
    this.__attachShadow();
    this.klevuInitSettingsUpdated = createEvent(this, "klevuInitSettingsUpdated", 7);
    _KlevuInit_instances.add(this);
    _KlevuInit_settingsDefined.set(this, false);
    this.apiKey = undefined;
    this.url = undefined;
    this.eventsV1Url = undefined;
    this.eventsV2Url = undefined;
    this.recommendationsApiUrl = undefined;
    this.visitorServiceUrl = undefined;
    this.ipv6ServiceUrl = undefined;
    this.ipv4ServiceUrl = undefined;
    this.moiApiUrl = undefined;
    this.settings = {
      renderPrice,
    };
    this.language = "en";
    this.translation = undefined;
    this.enableKlaviyoConnector = undefined;
    this.useConsent = false;
    this.consentGiven = false;
    this.assetsPath = undefined;
    this.settingsUrl = undefined;
    this.translationUrlPrefix = undefined;
    this.kmcLoadDefaults = undefined;
    this.disableUserSession = false;
  }
  async settingsChanged(newValue, oldValue) {
    await __classPrivateFieldGet(this, _KlevuInit_instances, "m", _KlevuInit_defineSettings).call(this, newValue);
    this.klevuInitSettingsUpdated.emit(this.settings);
  }
  async connectedCallback() {
    KlevuConfig.init({
      apiKey: this.apiKey,
      url: this.url,
      eventsApiV1Url: this.eventsV1Url,
      eventsApiV2Url: this.eventsV2Url,
      recommendationsApiUrl: this.recommendationsApiUrl,
      visitorServiceUrl: this.visitorServiceUrl,
      ipv6ServiceUrl: this.ipv6ServiceUrl,
      ipv4ServiceUrl: this.ipv4ServiceUrl,
      enableKlaviyoConnector: this.enableKlaviyoConnector || false,
      useConsent: this.useConsent || false,
      consentGiven: this.consentGiven || false,
      moiApiUrl: this.moiApiUrl || "",
      disableUserSession: this.disableUserSession || false,
    });
    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);
    }
    await __classPrivateFieldGet(this, _KlevuInit_instances, "m", _KlevuInit_defineSettings).call(this, 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;
  }
  /**
   * Get settings defined in klevu-init
   *
   * @returns
   */
  async isSettingsDefined() {
    return __classPrivateFieldGet(this, _KlevuInit_settingsDefined, "f");
  }
  async getAssetsPath() {
    var _a;
    return (_a = this.assetsPath) !== null && _a !== void 0 ? _a : "";
  }
  async setConsentGiven(val) {
    this.consentGiven = val;
    KlevuConfig.getDefault().setConsentGiven(val);
  }
  async setUseConsent(val) {
    this.useConsent = val;
    KlevuConfig.getDefault().setUseConsent(val);
  }
  /**
   * 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 async ready() {
    var _a;
    const klevuInit = await ((_a = document.querySelector("klevu-init")) === null || _a === void 0 ? void 0 : _a.componentOnReady());
    await (klevuInit === null || klevuInit === void 0 ? void 0 : klevuInit.getConfig());
    return new Promise(async (resolve, reject) => {
      async function checkIsSettingsDefined() {
        const settingsDefined = await (klevuInit === null || klevuInit === void 0 ? void 0 : klevuInit.isSettingsDefined());
        if (settingsDefined)
          return resolve(true);
        setTimeout(checkIsSettingsDefined, 200);
      }
      return checkIsSettingsDefined();
    });
  }
  render() {
    return (h(Host, null, h("slot", null)));
  }
  static get watchers() { return {
    "settings": ["settingsChanged"]
  }; }
  static get style() { return klevuInitCss; }
}, [1, "klevu-init", {
    "apiKey": [1, "api-key"],
    "url": [1],
    "eventsV1Url": [1, "events-v-1-url"],
    "eventsV2Url": [1, "events-v-2-url"],
    "recommendationsApiUrl": [1, "recommendations-api-url"],
    "visitorServiceUrl": [1, "visitor-service-url"],
    "ipv6ServiceUrl": [1, "ipv-6-service-url"],
    "ipv4ServiceUrl": [1, "ipv-4-service-url"],
    "moiApiUrl": [1, "moi-api-url"],
    "settings": [16],
    "language": [1],
    "translation": [16],
    "enableKlaviyoConnector": [4, "enable-klaviyo-connector"],
    "useConsent": [4, "use-consent"],
    "consentGiven": [4, "consent-given"],
    "assetsPath": [1, "assets-path"],
    "settingsUrl": [1, "settings-url"],
    "translationUrlPrefix": [1, "translation-url-prefix"],
    "kmcLoadDefaults": [4, "kmc-load-defaults"],
    "disableUserSession": [4, "disable-user-session"],
    "getConfig": [64],
    "getSettings": [64],
    "isSettingsDefined": [64],
    "getAssetsPath": [64],
    "setConsentGiven": [64],
    "setUseConsent": [64]
  }, undefined, {
    "settings": ["settingsChanged"]
  }]);
_KlevuInit_settingsDefined = new WeakMap(), _KlevuInit_instances = new WeakSet(), _KlevuInit_defineSettings = async function _KlevuInit_defineSettings(settings) {
  var _a, _b, _c, _d;
  this.settings = settings;
  if (this.kmcLoadDefaults) {
    try {
      const data = await KlevuKMCSettings(false, undefined, this.settingsUrl);
      window["klevu_ui_kmc_settings"] = data.root;
      if (((_a = data.root) === null || _a === void 0 ? void 0 : _a.klevu_uc_userOptions.priceFormatter) && !this.settings.renderPrice) {
        this.settings.renderPrice = (...params) => __classPrivateFieldGet(this, _KlevuInit_instances, "m", _KlevuInit_renderPriceKMCSettings).call(this, ...params, data.root.klevu_uc_userOptions.priceFormatter);
      }
      if (this.enableKlaviyoConnector === undefined) {
        this.enableKlaviyoConnector = ((_d = (_c = (_b = data.root) === null || _b === void 0 ? void 0 : _b.klevu_connectors) === null || _c === void 0 ? void 0 : _c.klaviyo) === null || _d === void 0 ? void 0 : _d.segmentEnabled) || false;
      }
      KlevuConfig.getDefault().setEnableKlaviyoConnector(this.enableKlaviyoConnector);
    }
    catch (err) {
      console.error("Failed to load settings");
    }
  }
  __classPrivateFieldSet(this, _KlevuInit_settingsDefined, true, "f");
}, _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 || currency}`;
  }
  else {
    formattedAmount = `${priceSettings.currencySymbol || currency} ${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());
  });
}
function renderPrice(amount, currency) {
  const price = typeof amount === "string" ? parseFloat(amount) : amount;
  return new Intl.NumberFormat(undefined, { style: "currency", currency }).format(price);
}
function defineCustomElement() {
  if (typeof customElements === "undefined") {
    return;
  }
  const components = ["klevu-init"];
  components.forEach(tagName => { switch (tagName) {
    case "klevu-init":
      if (!customElements.get(tagName)) {
        customElements.define(tagName, KlevuInit);
      }
      break;
  } });
}
defineCustomElement();

export { KlevuInit as K, KlevuKMCSettings as a, defineCustomElement as d };

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