'use strict';

const index = require('./index-4ab26f11.js');
const isBrowser = require('./isBrowser-e8e10249.js');

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());
    });
};
function get(url, ignoreResult = false) {
    return __awaiter$1(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$1(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 = (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(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(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(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(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(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(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(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) {
        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.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();
        }
    }
    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);
}

const KlevuInit = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.apiKey = undefined;
    this.url = undefined;
    this.settings = undefined;
  }
  async connectedCallback() {
    KlevuConfig.init({
      apiKey: this.apiKey,
      url: this.url,
    });
    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)));
  }
};

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.get = get;
exports.objectToQueryParameters = objectToQueryParameters;
exports.post = post;

//# sourceMappingURL=klevu-init-e6adb771.js.map