'use strict';

const index = require('./index-97fdbb7d.js');
const isBrowser = require('./isBrowser-e8e10249.js');

var __awaiter$2 = (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());
    });
};
function get(url, ignoreResult = false) {
    return __awaiter$2(this, void 0, void 0, function* () {
        const axios = KlevuConfig.getDefault().axios;
        if (axios) {
            return (yield axios.get(url)).data;
        }
        const res = yield fetch(url, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
            },
        });
        if (ignoreResult) {
            return undefined;
        }
        return (yield res.json());
    });
}
function post(url, 
// eslint-disable-next-line @typescript-eslint/no-explicit-any
data, ignoreResult = false) {
    return __awaiter$2(this, void 0, void 0, function* () {
        const axios = KlevuConfig.getDefault().axios;
        if (axios) {
            try {
                const res = yield axios.post(url, data, {
                    headers: {
                        "Content-Type": "application/json",
                    },
                });
                return res.data;
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
            }
            catch (error) {
                return error.response.data;
            }
        }
        // Fetch will always return value. Even with 500 errors.
        const res = yield fetch(url, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(data),
        });
        if (ignoreResult) {
            return undefined;
        }
        return (yield res.json());
    });
}

/**
 * transform object to query parameters
 *
 * @param params
 */
function objectToQueryParameters(params) {
    let urlData = "?";
    for (const [key, value] of Object.entries(params)) {
        if (value === undefined) {
            continue;
        }
        urlData += `${key}=${encodeURIComponent(value)}&`;
    }
    return urlData;
}

var __awaiter$1 = (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());
    });
};
var __asyncValues = (undefined && undefined.__asyncValues) || function (o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
const KEY_PENDING_REQUESTS = "klevu-pending-analytics";
function KlevuEventV1Search(event) {
    return __awaiter$1(this, void 0, void 0, function* () {
        const url = `${KlevuConfig.getDefault().eventsApiV1Url}n-search/search${objectToQueryParameters(event)}`;
        const id = addPendingRequest(url);
        const res = yield get(url, true);
        if (id) {
            removePendingRequest(id);
        }
        return res;
    });
}
function KlevuEventV1ProductTracking(event) {
    return __awaiter$1(this, void 0, void 0, function* () {
        const url = `${KlevuConfig.getDefault().eventsApiV1Url}productTracking${objectToQueryParameters(event)}`;
        const id = addPendingRequest(url);
        const res = yield get(url, true);
        if (id) {
            removePendingRequest(id);
        }
        return res;
    });
}
function KlevuEventV1CheckedOutProducts(event) {
    return __awaiter$1(this, void 0, void 0, function* () {
        const url = `${KlevuConfig.getDefault().eventsApiV1Url}productTracking${objectToQueryParameters(event)}`;
        const id = addPendingRequest(url);
        const res = yield get(url, true);
        if (id) {
            removePendingRequest(id);
        }
        return res;
    });
}
function KlevuEventV1CategoryView(event) {
    return __awaiter$1(this, void 0, void 0, function* () {
        const url = `${KlevuConfig.getDefault().eventsApiV1Url}categoryProductViewTracking${objectToQueryParameters(event)}`;
        const id = addPendingRequest(url);
        const res = yield get(url, true);
        if (id) {
            removePendingRequest(id);
        }
        return res;
    });
}
function KlevuEventV1CategoryProductClick(event) {
    return __awaiter$1(this, void 0, void 0, function* () {
        const url = `${KlevuConfig.getDefault().eventsApiV1Url}categoryProductClickTracking${objectToQueryParameters(event)}`;
        const id = addPendingRequest(url);
        const res = yield get(url, true);
        if (id) {
            removePendingRequest(id);
        }
        return res;
    });
}
function KlevuEventV2(data) {
    return __awaiter$1(this, void 0, void 0, function* () {
        const url = KlevuConfig.getDefault().eventsApiV2Url;
        const id = addPendingRequest(url, data);
        const res = yield post(url, data, true);
        if (id) {
            removePendingRequest(id);
        }
        return res;
    });
}
function addPendingRequest(url, data) {
    if (!isBrowser.isBrowser()) {
        return;
    }
    let requests = [];
    const old = window.localStorage.getItem(KEY_PENDING_REQUESTS);
    if (old) {
        try {
            requests = JSON.parse(old);
        }
        catch (_a) {
            window.localStorage.removeItem(KEY_PENDING_REQUESTS);
        }
    }
    const id = generateUID();
    requests.push({ id, url, data });
    window.localStorage.setItem(KEY_PENDING_REQUESTS, JSON.stringify(requests));
    return id;
}
function removePendingRequest(id) {
    if (!isBrowser.isBrowser()) {
        return;
    }
    const data = window.localStorage.getItem(KEY_PENDING_REQUESTS);
    if (!data) {
        console.error("No pending requests!");
        return;
    }
    try {
        const requests = JSON.parse(data);
        requests.splice(requests.findIndex((r) => r.id === id), 1);
        window.localStorage.setItem(KEY_PENDING_REQUESTS, JSON.stringify(requests));
    }
    catch (e) {
        console.error("Failed to save pending request");
    }
}
function runPendingAnalyticalRequests() {
    var _a, e_1, _b, _c;
    return __awaiter$1(this, void 0, void 0, function* () {
        if (!isBrowser.isBrowser()) {
            return;
        }
        const data = window.localStorage.getItem(KEY_PENDING_REQUESTS);
        if (!data) {
            return;
        }
        const requests = JSON.parse(data);
        try {
            for (var _d = true, requests_1 = __asyncValues(requests), requests_1_1; requests_1_1 = yield requests_1.next(), _a = requests_1_1.done, !_a; _d = true) {
                _c = requests_1_1.value;
                _d = false;
                const request = _c;
                if (request.data) {
                    yield post(request.url, request.data, true);
                }
                else {
                    yield get(request.url, true);
                }
                removePendingRequest(request.id);
            }
        }
        catch (e_1_1) { e_1 = { error: e_1_1 }; }
        finally {
            try {
                if (!_d && !_a && (_b = requests_1.return)) yield _b.call(requests_1);
            }
            finally { if (e_1) throw e_1.error; }
        }
    });
}
function generateUID() {
    let firstPart = (Math.random() * 46656) | 0;
    let secondPart = (Math.random() * 46656) | 0;
    firstPart = ("000" + firstPart.toString(36)).slice(-3);
    secondPart = ("000" + secondPart.toString(36)).slice(-3);
    return firstPart + secondPart;
}

class KlevuConfig {
    constructor(config) {
        var _a;
        this.cacheMaxTTL = 600000;
        this.eventsApiV1Url = "https://stats.ksearchnet.com/analytics/";
        this.eventsApiV2Url = "https://stats.ksearchnet.com/analytics/collect";
        this.moiApiUrl = "https://moi-ai.ksearchnet.com/";
        this.disableClickTracking = false;
        this.apiKey = config.apiKey;
        this.url = config.url;
        if (config.moiApiUrl) {
            this.moiApiUrl = config.moiApiUrl;
        }
        if (config.cacheMaxTTL) {
            this.cacheMaxTTL = config.cacheMaxTTL;
        }
        if (config.axios) {
            this.axios = config.axios.create();
        }
        this.disableClickTracking = (_a = config.disableClickTrackStoring) !== null && _a !== void 0 ? _a : false;
    }
    static init(config) {
        KlevuConfig.default = new KlevuConfig(config);
        runPendingAnalyticalRequests();
    }
    static getDefault() {
        if (!KlevuConfig.default) {
            throw new Error("Configuration missing");
        }
        return KlevuConfig.default;
    }
}
KlevuConfig.default = loadFromGlobal();
function loadFromGlobal() {
    if (!isBrowser.isBrowser()) {
        return undefined;
    }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const cfg = window.KlevuConfig;
    if (!cfg) {
        return undefined;
    }
    return new KlevuConfig(cfg);
}

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) {
    return __awaiter(this, void 0, void 0, function* () {
        if (isBrowser.isBrowser() && window.localStorage && ignoreCache !== true) {
            const ts = window.localStorage.getItem(STORAGE_TS_KEY);
            const res = window.localStorage.getItem(STORAGE_KEY);
            if (res && ts && new Date().getTime() - parseInt(ts, 10) < cacheLength) {
                return JSON.parse(res);
            }
        }
        const start = `${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.isBrowser() && window.localStorage) {
            window.localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
            window.localStorage.setItem(STORAGE_TS_KEY, new Date().getTime().toString());
        }
        return data;
    });
}

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 _KlevuInit_instances, _KlevuInit_renderPriceKMCSettings;
const KlevuInit = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    _KlevuInit_instances.add(this);
    this.apiKey = undefined;
    this.url = 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,
    });
    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 (index.h(index.Host, null, index.h("slot", null)));
  }
};
_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 = (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('klevu-init-57de47f9.js', document.baseURI).href)).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());
  });
}

exports.KlevuConfig = KlevuConfig;
exports.KlevuEventV1CategoryProductClick = KlevuEventV1CategoryProductClick;
exports.KlevuEventV1CategoryView = KlevuEventV1CategoryView;
exports.KlevuEventV1CheckedOutProducts = KlevuEventV1CheckedOutProducts;
exports.KlevuEventV1ProductTracking = KlevuEventV1ProductTracking;
exports.KlevuEventV1Search = KlevuEventV1Search;
exports.KlevuEventV2 = KlevuEventV2;
exports.KlevuInit = KlevuInit;
exports.KlevuKMCSettings = KlevuKMCSettings;
exports.get = get;
exports.objectToQueryParameters = objectToQueryParameters;
exports.post = post;

//# sourceMappingURL=klevu-init-57de47f9.js.map