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 __classPrivateFieldSet = (this && this.__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_setKMCPriceCalculationSetting, _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);
    _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());
    const klevuInitObj = 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 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
      },
      "visitorServiceUrl": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Override the default session API URL"
        },
        "attribute": "visitor-service-url",
        "reflect": false
      },
      "ipv6ServiceUrl": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Ipv6 ServiceUrl for ipv6 retrieval used in analytics"
        },
        "attribute": "ipv-6-service-url",
        "reflect": false
      },
      "ipv4ServiceUrl": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Ipv4 ServiceUrl for ipv4 retrieval used in analytics"
        },
        "attribute": "ipv-4-service-url",
        "reflect": false
      },
      "moiApiUrl": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Override the default moi API URL"
        },
        "attribute": "moi-api-url",
        "reflect": false
      },
      "settings": {
        "type": "unknown",
        "mutable": false,
        "complexType": {
          "original": "KlevuUIGlobalSettings",
          "resolved": "{ 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": false,
        "docs": {
          "tags": [],
          "text": "Global settings"
        },
        "defaultValue": "{\n    renderPrice,\n  }"
      },
      "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; tAnswerError: string; tPopuptitle: string; tButtonText: string; tFinePrint: string; disclaimer: string; tLoadingSorry: string; tRateExperienceTitle: string; tRateExperienceText: string; tDataProtectionNotice: string; }; quicksearch: { tSearchResults: string; tStartChat: string; tCategoriesCaption: string; tTrendingCaption: string; tPopularProductsTitle: string; tLastClickedProductsCaption: string; tNoResultsFound: 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"
        }
      },
      "enableKlaviyoConnector": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Enable Klaviyo integration"
        },
        "attribute": "enable-klaviyo-connector",
        "reflect": false
      },
      "useConsent": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Enable Data Protection"
        },
        "attribute": "use-consent",
        "reflect": false,
        "defaultValue": "false"
      },
      "consentGiven": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Data read consent given"
        },
        "attribute": "consent-given",
        "reflect": false,
        "defaultValue": "false"
      },
      "assetsPath": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "Override the default assets path. Will use format of `${assetsPath}/assets/${resource}`"
        },
        "attribute": "assets-path",
        "reflect": false
      },
      "settingsUrl": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "settings-url",
        "reflect": false
      },
      "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
      },
      "disableUserSession": {
        "type": "boolean",
        "mutable": false,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean | undefined",
          "references": {}
        },
        "required": false,
        "optional": true,
        "docs": {
          "tags": [],
          "text": "disableUserSession and stop making calls to visitor service when this is true, defaults to false."
        },
        "attribute": "disable-user-session",
        "reflect": false,
        "defaultValue": "false"
      }
    };
  }
  static get events() {
    return [{
        "method": "klevuInitSettingsUpdated",
        "name": "klevuInitSettingsUpdated",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "KlevuUIGlobalSettings",
          "resolved": "{ 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"
            }
          }
        }
      }];
  }
  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
            }]
        }
      },
      "isSettingsDefined": {
        "complexType": {
          "signature": "() => Promise<boolean>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global",
              "id": "global::Promise"
            }
          },
          "return": "Promise<boolean>"
        },
        "docs": {
          "text": "Get settings defined in klevu-init",
          "tags": [{
              "name": "returns",
              "text": undefined
            }]
        }
      },
      "getAssetsPath": {
        "complexType": {
          "signature": "() => Promise<string>",
          "parameters": [],
          "references": {
            "Promise": {
              "location": "global",
              "id": "global::Promise"
            }
          },
          "return": "Promise<string>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      },
      "setConsentGiven": {
        "complexType": {
          "signature": "(val: boolean) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global",
              "id": "global::Promise"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      },
      "setUseConsent": {
        "complexType": {
          "signature": "(val: boolean) => Promise<void>",
          "parameters": [{
              "tags": [],
              "text": ""
            }],
          "references": {
            "Promise": {
              "location": "global",
              "id": "global::Promise"
            }
          },
          "return": "Promise<void>"
        },
        "docs": {
          "text": "",
          "tags": []
        }
      }
    };
  }
  static get watchers() {
    return [{
        "propName": "settings",
        "methodName": "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_setKMCPriceCalculationSetting = function _KlevuInit_setKMCPriceCalculationSetting(settings, priceSettings) {
  if (!priceSettings || settings.renderPrice)
    return settings;
  if (priceSettings) {
    settings = Object.assign(Object.assign({}, (settings || {})), { renderPrice: (...params) => __classPrivateFieldGet(this, _KlevuInit_instances, "m", _KlevuInit_renderPriceKMCSettings).call(this, ...params, priceSettings) });
  }
}, _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);
}
//# sourceMappingURL=klevu-init.js.map
