import { r as registerInstance, h, H as Host } from './index-89bb9d20.js';
import { i as isBrowser } from './isBrowser-0ab0def8.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()) {
        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()) {
        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 e_1, _a;
    return __awaiter(this, void 0, void 0, function* () {
        if (!isBrowser()) {
            return;
        }
        const data = window.localStorage.getItem(KEY_PENDING_REQUESTS);
        if (!data) {
            return;
        }
        const requests = JSON.parse(data);
        try {
            for (var requests_1 = __asyncValues(requests), requests_1_1; requests_1_1 = yield requests_1.next(), !requests_1_1.done;) {
                const request = requests_1_1.value;
                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 (requests_1_1 && !requests_1_1.done && (_a = requests_1.return)) yield _a.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()) {
        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) {
    registerInstance(this, hostRef);
    this.apiKey = undefined;
    this.url = undefined;
    this.settings = undefined;
  }
  async connectedCallback() {
    KlevuConfig.init({
      apiKey: this.apiKey,
      url: this.url,
    });
    // @ts-expect-error
    window["klevu_ui_settings"] = Object.assign(Object.assign({}, this.settings), { apiKey: this.apiKey, url: this.url });
    // Inject material fonts to project
    const fontCssUrl = "https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@20,600,0,0";
    let element = document.querySelector(`link[href="${fontCssUrl}"]`);
    // Only inject the element if it's not yet present
    if (!element) {
      element = document.createElement("link");
      element.setAttribute("rel", "stylesheet");
      element.setAttribute("href", fontCssUrl);
      document.head.appendChild(element);
    }
    if (!Boolean(document.querySelector("#klevu-icons"))) {
      const style = document.createElement("style");
      style.id = "klevu-icons";
      style.appendChild(document.createTextNode(`
          ::part(material-icon) { font-family: "Material Symbols Rounded"; font-variation-settings: "FILL" 0, "wght" 600, "GRAD" 0, "opsz" 20; }
          `));
      document.head.appendChild(style);
    }
  }
  /**
   *
   * @returns KlevuConfig, but due to typescript problems it is any
   */
  async getConfig() {
    return KlevuConfig.getDefault();
  }
  /**
   * 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)));
  }
};

export { KlevuInit as K, KlevuConfig as a, KlevuEventV1CheckedOutProducts as b, KlevuEventV2 as c, KlevuEventV1ProductTracking as d, KlevuEventV1Search as e, KlevuEventV1CategoryView as f, get as g, KlevuEventV1CategoryProductClick as h, objectToQueryParameters as o, post as p };

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