import { r as registerInstance, c as createEvent, h, H as Host } from './index-e582ed08.js';
import { K as KlevuDomEvents } from './KlevuDomEvents-062429b2.js';

var __awaiter$4 = (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$4(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, data, ignoreResult = false) {
    return __awaiter$4(this, void 0, void 0, function* () {
        const sendAsFormData = data instanceof FormData;
        const axios = KlevuConfig.getDefault().axios;
        if (axios) {
            try {
                const res = yield axios.post(url, data, {
                    headers: sendAsFormData
                        ? undefined
                        : {
                            "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: sendAsFormData
                ? undefined
                : {
                    "Content-Type": "application/json",
                },
            body: sendAsFormData ? data : JSON.stringify(data),
        });
        if (ignoreResult) {
            return undefined;
        }
        return (yield res.json());
    });
}

const isBrowser = () => ![typeof window, typeof document].includes("undefined");

var _a;
var StorageType;
(function (StorageType) {
    StorageType["SESSION"] = "session";
    StorageType["LOCAL"] = "local";
})(StorageType || (StorageType = {}));
const isSessionStorage = (storageType) => {
    return (storageType === StorageType.SESSION &&
        typeof window !== "undefined" &&
        window.sessionStorage);
};
const isLocalStorage = (storageType) => {
    return (storageType === StorageType.LOCAL &&
        typeof window !== "undefined" &&
        window.localStorage);
};
class KlevuStorage {
    static listKeys() {
        return this.dataProtectedKeys;
    }
}
_a = KlevuStorage;
KlevuStorage.dataProtectedKeys = [];
KlevuStorage.addKey = (key) => {
    if (!_a.dataProtectedKeys.find((k) => k === key))
        _a.dataProtectedKeys.push(key);
};
KlevuStorage.removeKey = (key) => {
    const keyIndex = _a.dataProtectedKeys.indexOf(key);
    if (keyIndex !== -1) {
        _a.dataProtectedKeys.splice(keyIndex, 1);
    }
};
KlevuStorage.getItem = (key, storageType = StorageType.LOCAL) => {
    if (_a.dataProtectedKeys.find((k) => k.includes(key)) !== undefined &&
        KlevuConfig.getDefault().isConsentDisallowed()) {
        return null;
    }
    if (isLocalStorage(storageType)) {
        return window.localStorage.getItem(key);
    }
    if (isSessionStorage(storageType)) {
        return window.sessionStorage.getItem(key);
    }
    return null;
};
KlevuStorage.setItem = (key, value, storageType = StorageType.LOCAL) => {
    if (_a.dataProtectedKeys.find((k) => k.includes(key)) !== undefined &&
        KlevuConfig.getDefault().isConsentDisallowed()) {
        return;
    }
    if (isLocalStorage(storageType)) {
        return window.localStorage.setItem(key, value);
    }
    if (isSessionStorage(storageType)) {
        return window.sessionStorage.setItem(key, value);
    }
};
KlevuStorage.removeItem = (key, storageType = StorageType.LOCAL) => {
    if (_a.dataProtectedKeys.find((k) => k.includes(key)) !== undefined &&
        KlevuConfig.getDefault().isConsentDisallowed()) {
        return;
    }
    if (isLocalStorage(storageType)) {
        return window.localStorage.removeItem(key);
    }
    if (isSessionStorage(storageType)) {
        return window.sessionStorage.removeItem(key);
    }
};

var __awaiter$3 = (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$3(this, void 0, void 0, function* () {
        const url = `${KlevuConfig.getDefault().eventsApiV1Url}n-search/search`;
        const id = addPendingRequest(url, event);
        const res = yield sendGenericPostEvent(url, event);
        if (id) {
            removePendingRequest(id);
        }
        return res;
    });
}
function KlevuEventV1ProductTracking(event) {
    return __awaiter$3(this, void 0, void 0, function* () {
        const url = `${KlevuConfig.getDefault().eventsApiV1Url}productTracking`;
        const id = addPendingRequest(url, event);
        const res = yield sendGenericPostEvent(url, event);
        if (id) {
            removePendingRequest(id);
        }
        return res;
    });
}
function KlevuEventV2CheckedOutProducts(event) {
    return __awaiter$3(this, void 0, void 0, function* () {
        const url = `${KlevuConfig.getDefault().eventsApiV2Url}`;
        const id = addPendingRequest(url, event);
        const res = yield post(url, [event], true);
        if (id) {
            removePendingRequest(id);
        }
        return res;
    });
}
function KlevuEventV1CategoryView(event) {
    return __awaiter$3(this, void 0, void 0, function* () {
        const url = `${KlevuConfig.getDefault().eventsApiV1Url}categoryProductViewTracking`;
        const id = addPendingRequest(url, event);
        const res = yield sendGenericPostEvent(url, event);
        if (id) {
            removePendingRequest(id);
        }
        return res;
    });
}
function KlevuEventV1CategoryProductClick(event) {
    return __awaiter$3(this, void 0, void 0, function* () {
        const url = `${KlevuConfig.getDefault().eventsApiV1Url}categoryProductClickTracking`;
        const id = addPendingRequest(url, event);
        const res = yield sendGenericPostEvent(url, event);
        if (id) {
            removePendingRequest(id);
        }
        return res;
    });
}
function KlevuEventV1BannerClick(event) {
    return __awaiter$3(this, void 0, void 0, function* () {
        const url = `${KlevuConfig.getDefault().eventsApiV1Url}dataTracking`;
        const id = addPendingRequest(url, event);
        const res = yield sendGenericPostEvent(url, event);
        if (id) {
            removePendingRequest(id);
        }
        return res;
    });
}
function KlevuEventV2(data) {
    return __awaiter$3(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;
    });
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function sendGenericPostEvent(url, data) {
    return __awaiter$3(this, void 0, void 0, function* () {
        const formData = new FormData();
        for (const key in data) {
            if (data[key] !== undefined) {
                if (Array.isArray(data[key])) {
                    data[key].forEach((d) => {
                        formData.append(key, d);
                    });
                }
                else {
                    formData.append(key, data[key]);
                }
            }
        }
        if (isBrowser() && navigator.sendBeacon) {
            if (navigator.sendBeacon(url, formData)) {
                return;
            }
        }
        return yield post(url, formData, true);
    });
}
function addPendingRequest(url, data) {
    if (!isBrowser()) {
        return;
    }
    let requests = [];
    const old = KlevuStorage.getItem(KEY_PENDING_REQUESTS, StorageType.SESSION);
    if (old) {
        try {
            requests = JSON.parse(old);
        }
        catch (_a) {
            KlevuStorage.removeItem(KEY_PENDING_REQUESTS, StorageType.SESSION);
        }
    }
    const id = generateUID();
    requests.push({ id, url, data });
    KlevuStorage.setItem(KEY_PENDING_REQUESTS, JSON.stringify(requests), StorageType.SESSION);
    return id;
}
function removePendingRequest(id) {
    if (!isBrowser()) {
        return;
    }
    const data = KlevuStorage.getItem(KEY_PENDING_REQUESTS, StorageType.SESSION);
    if (!data) {
        console.error("No pending requests!");
        return;
    }
    try {
        const requests = JSON.parse(data);
        requests.splice(requests.findIndex((r) => r.id === id), 1);
        KlevuStorage.setItem(KEY_PENDING_REQUESTS, JSON.stringify(requests), StorageType.SESSION);
    }
    catch (e) {
        console.error("Failed to save pending request");
    }
}
function runPendingAnalyticalRequests() {
    var _a, e_1, _b, _c;
    return __awaiter$3(this, void 0, void 0, function* () {
        if (!isBrowser()) {
            return;
        }
        const data = KlevuStorage.getItem(KEY_PENDING_REQUESTS, StorageType.SESSION);
        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;
                try {
                    if (request.data) {
                        yield sendGenericPostEvent(request.url, request.data);
                    }
                    else {
                        yield get(request.url, true);
                    }
                    removePendingRequest(request.id);
                }
                catch (e) {
                    // we ignore errors here
                }
            }
        }
        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 Klaviyo {
    constructor() {
        this.timer = null;
    }
    setExchangeId() {
        var _a;
        if (!globalThis._learnq) {
            if (!this.timer) {
                this.timer = setInterval(() => {
                    this.setExchangeId();
                }, 300);
            }
            return;
        }
        const _getIdentifiersResponse = (_a = globalThis._learnq) === null || _a === void 0 ? void 0 : _a.push([
            "_getIdentifiers",
            "",
            {},
        ]);
        this.exchangeId = _getIdentifiersResponse.$exchange_id;
        if (!this.exchangeId) {
            if (!this.timer) {
                this.timer = setInterval(() => {
                    this.setExchangeId();
                }, 300);
            }
            return;
        }
        if (this.timer) {
            clearInterval(this.timer);
        }
        KlevuUserSession.getDefault().generateSession();
    }
    static init() {
        Klaviyo.default = new Klaviyo();
        this.getDefault().setExchangeId();
    }
    static getDefault() {
        if (!Klaviyo.default) {
            throw new Error("Klaviyo not initialized.");
        }
        return Klaviyo.default;
    }
    getExchangeId() {
        return this.exchangeId;
    }
    static generatePayload() {
        if (!KlevuConfig.getDefault().enableKlaviyoConnector ||
            !this.default ||
            !this.getDefault().exchangeId) {
            return undefined;
        }
        return {
            connectorType: "klaviyo",
            exchangeId: this.getDefault().exchangeId || "",
        };
    }
}

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());
    });
};
const USER_SESSION_ID_STORAGE_KEY = "klevu-user-sessionId";
const USER_SESSION_EXPIRY_STORAGE_KEY = "klevu-user-session_expiry";
const USER_SEGMENT_INFO_STORAGE_KEY = "klevu-user-segmentInfo";
const connectors = [
    { name: "klaviyo", connector: Klaviyo },
];
class KlevuUserSession {
    constructor() {
        this.timer = null;
        this.getSessionId = () => __awaiter$2(this, void 0, void 0, function* () {
            const apiKey = KlevuConfig.getDefault().apiKey;
            const sessionInfo = {
                connectorInfo: connectors
                    .map(({ connector }) => {
                    try {
                        return connector.generatePayload();
                    }
                    catch (_a) {
                        return undefined;
                    }
                })
                    .filter((connector) => connector),
            };
            const payload = {
                apiKey,
                sessionId: this.sessionId || undefined,
                sessionInfo,
            };
            return post(`${KlevuConfig.getDefault().visitorServiceUrl}/${apiKey}/session`, payload);
        });
        KlevuStorage.addKey(USER_SESSION_ID_STORAGE_KEY);
        KlevuStorage.addKey(USER_SESSION_EXPIRY_STORAGE_KEY);
        KlevuStorage.addKey(USER_SEGMENT_INFO_STORAGE_KEY);
        this.expiry = KlevuStorage.getItem(USER_SESSION_EXPIRY_STORAGE_KEY);
        const segmentInfo = KlevuStorage.getItem(USER_SEGMENT_INFO_STORAGE_KEY);
        this.segmentInfo = segmentInfo ? JSON.parse(segmentInfo) : null;
        this.sessionId = KlevuStorage.getItem(USER_SESSION_ID_STORAGE_KEY);
    }
    static init() {
        if (!KlevuUserSession.default)
            KlevuUserSession.default = new KlevuUserSession();
    }
    static getDefault() {
        if (!KlevuUserSession.default) {
            throw new Error("KlevuUserSession not initialized.");
        }
        return KlevuUserSession.default;
    }
    hasSessionExpired() {
        if (!this.sessionId || !this.expiry)
            return true;
        return Date.now() > +this.expiry;
    }
    generateSession() {
        return __awaiter$2(this, void 0, void 0, function* () {
            const sessionInfo = yield this.getSessionId();
            if (sessionInfo) {
                KlevuStorage.setItem(USER_SESSION_ID_STORAGE_KEY, sessionInfo.sessionId);
                this.sessionId = sessionInfo.sessionId;
                if (sessionInfo.segmentInfo) {
                    KlevuStorage.setItem(USER_SEGMENT_INFO_STORAGE_KEY, JSON.stringify(sessionInfo.segmentInfo));
                    this.segmentInfo = sessionInfo.segmentInfo;
                    const expiry = Date.now() +
                        (sessionInfo.segmentInfo.ttl ? sessionInfo.segmentInfo.ttl * 1000 : 0);
                    KlevuStorage.setItem(USER_SESSION_EXPIRY_STORAGE_KEY, expiry.toString());
                    this.expiry = expiry.toString();
                    /**
                     * Regenerate session on expiry
                     */
                    if (this.timer) {
                        // To ensure only one timer is active
                        clearTimeout(this.timer);
                    }
                    this.timer = setTimeout(() => {
                        this.generateSession();
                    }, sessionInfo.segmentInfo.ttl * 1000);
                }
            }
            else {
                console.warn("Failed to generate user session");
            }
        });
    }
    setExpiryTimer() {
        const currentTime = Date.now();
        const expiry = +(this.expiry || currentTime) - currentTime;
        if (this.timer) {
            // To ensure only one timer is active
            clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
            this.generateSession();
        }, expiry);
    }
    getSegments() {
        var _a;
        return ((_a = this.segmentInfo) === null || _a === void 0 ? void 0 : _a.segments) || [];
    }
}

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());
    });
};
const USER_IPV4_STORAGE_KEY = "klevu-user-v4-id";
const USER_IPV6_STORAGE_KEY = "klevu-user-v6-id";
const USER_IP_EXPIRY_STORAGE_KEY = "klevu-user-v4-v6-expiry";
const USER_UUID_STORAGE_KEY = "klevu-user-uuid";
const ONE_HOUR = 60 * 60 * 1000;
class KlevuIpResolver {
    constructor() {
        this.timer = null;
        this.getIPData = () => __awaiter$1(this, void 0, void 0, function* () {
            let ipV4Response = undefined;
            let ipV6Response = undefined;
            try {
                const ipV4Payload = {
                    klevu_uuid: this.uuid || "",
                };
                ipV4Response = yield post(KlevuConfig.getDefault().ipv4ServiceUrl, ipV4Payload);
            }
            catch (err) {
                console.info(err);
            }
            try {
                const ipV6Payload = {
                    klevu_uuid: (ipV4Response === null || ipV4Response === void 0 ? void 0 : ipV4Response.klevu_uuid) || "",
                };
                ipV6Response = yield post(KlevuConfig.getDefault().ipv6ServiceUrl, ipV6Payload);
            }
            catch (err) {
                console.info(err);
            }
            return {
                uuid: (ipV4Response === null || ipV4Response === void 0 ? void 0 : ipV4Response.klevu_uuid) || (ipV6Response === null || ipV6Response === void 0 ? void 0 : ipV6Response.klevu_uuid) || "",
                ipv4: (ipV4Response === null || ipV4Response === void 0 ? void 0 : ipV4Response.ip_address) || "",
                ipv6: (ipV6Response === null || ipV6Response === void 0 ? void 0 : ipV6Response.ip_address) || "",
            };
        });
        KlevuStorage.addKey(USER_IPV4_STORAGE_KEY);
        KlevuStorage.addKey(USER_IPV6_STORAGE_KEY);
        KlevuStorage.addKey(USER_IP_EXPIRY_STORAGE_KEY);
        KlevuStorage.addKey(USER_UUID_STORAGE_KEY);
        this.expiry = KlevuStorage.getItem(USER_IP_EXPIRY_STORAGE_KEY);
        this.uuid = KlevuStorage.getItem(USER_UUID_STORAGE_KEY);
        this.ipv4 = KlevuStorage.getItem(USER_IPV4_STORAGE_KEY);
        this.ipv6 = KlevuStorage.getItem(USER_IPV6_STORAGE_KEY);
    }
    static init() {
        if (!KlevuIpResolver.default)
            KlevuIpResolver.default = new KlevuIpResolver();
    }
    static getDefault() {
        if (!KlevuIpResolver.default) {
            throw new Error("KlevuIpResolver not initialized.");
        }
        return KlevuIpResolver.default;
    }
    hasIPInfoExpired() {
        if (!this.uuid || !this.ipv4 || !this.ipv6 || !this.expiry)
            return true;
        return Date.now() > +this.expiry;
    }
    generateIPData() {
        return __awaiter$1(this, void 0, void 0, function* () {
            try {
                const ipData = yield this.getIPData();
                KlevuStorage.setItem(USER_IPV4_STORAGE_KEY, ipData.ipv4);
                KlevuStorage.setItem(USER_IPV6_STORAGE_KEY, ipData.ipv6);
                KlevuStorage.setItem(USER_UUID_STORAGE_KEY, ipData.uuid);
                this.uuid = ipData.uuid;
                this.ipv4 = ipData.ipv4;
                this.ipv6 = ipData.ipv6;
                const expiry = Date.now() + ONE_HOUR;
                KlevuStorage.setItem(USER_IP_EXPIRY_STORAGE_KEY, expiry.toString());
                this.expiry = expiry.toString();
                /**
                 * Regenerate ip on expiry
                 */
                if (this.timer) {
                    // To ensure only one timer is active
                    clearTimeout(this.timer);
                }
                this.timer = setTimeout(() => {
                    this.generateIPData();
                }, ONE_HOUR);
            }
            catch (err) {
                console.error("Failed to generate ip data", err);
                this.timer = setTimeout(() => {
                    this.generateIPData();
                }, ONE_HOUR);
            }
        });
    }
    setExpiryTimer() {
        const currentTime = Date.now();
        const expiry = +(this.expiry || currentTime) - currentTime;
        if (this.timer) {
            // To ensure only one timer is active
            clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
            this.generateIPData();
        }, expiry);
    }
    getUserData() {
        if (KlevuConfig.getDefault().isConsentDisallowed()) {
            return {};
        }
        return {
            ipv4: KlevuStorage.getItem(USER_IPV4_STORAGE_KEY) || "",
            ipv6: KlevuStorage.getItem(USER_IPV6_STORAGE_KEY) || "",
            uuid: KlevuStorage.getItem(USER_UUID_STORAGE_KEY) || "",
        };
    }
}

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.recommendationsApiUrl = "https://config-cdn.ksearchnet.com/recommendations/";
        this.visitorServiceUrl = "https://visitor.service.ksearchnet.com/public/1.0";
        this.ipv6ServiceUrl = "https://ipv6check.ksearchnet.com";
        this.ipv4ServiceUrl = "https://ipv4check.ksearchnet.com";
        this.moiApiUrl = "https://moi-ai.ksearchnet.com/";
        this.disableClickTracking = false;
        this.enableKlaviyoConnector = false;
        this.useConsent = false;
        this.consentGiven = false;
        this.disableUserSession = 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();
        }
        if (config.eventsApiV1Url) {
            this.eventsApiV1Url = config.eventsApiV1Url;
        }
        if (config.eventsApiV2Url) {
            this.eventsApiV2Url = config.eventsApiV2Url;
        }
        if (config.visitorServiceUrl) {
            this.visitorServiceUrl = config.visitorServiceUrl;
        }
        if (config.ipv4ServiceUrl) {
            this.ipv4ServiceUrl = config.ipv4ServiceUrl;
        }
        if (config.ipv6ServiceUrl) {
            this.ipv6ServiceUrl = config.ipv6ServiceUrl;
        }
        if (config.recommendationsApiUrl) {
            this.recommendationsApiUrl = config.recommendationsApiUrl;
        }
        this.disableClickTracking = (_a = config.disableClickTrackStoring) !== null && _a !== void 0 ? _a : false;
        this.useConsent = config.useConsent || false;
        this.consentGiven = config.consentGiven || false;
        this.enableKlaviyoConnector = config.enableKlaviyoConnector || false;
        this.disableUserSession = config.disableUserSession || false;
    }
    static init(config) {
        KlevuConfig.default = new KlevuConfig(config);
        runPendingAnalyticalRequests();
        if (!config.disableUserSession) {
            this.initializeUserSession();
        }
        this.initializeIPResolver();
    }
    static initializeIPResolver() {
        KlevuIpResolver.init();
        if (KlevuIpResolver.getDefault().hasIPInfoExpired()) {
            KlevuIpResolver.getDefault().generateIPData();
        }
        else {
            KlevuIpResolver.getDefault().setExpiryTimer();
        }
    }
    static initializeUserSession() {
        KlevuUserSession.init();
        if (KlevuUserSession.getDefault().hasSessionExpired()) {
            KlevuUserSession.getDefault()
                .generateSession()
                .then(() => {
                if (this.getDefault().enableKlaviyoConnector) {
                    Klaviyo.init();
                }
            });
        }
        else {
            KlevuUserSession.getDefault().setExpiryTimer();
            if (this.getDefault().enableKlaviyoConnector) {
                Klaviyo.init();
            }
        }
    }
    static getDefault() {
        if (!KlevuConfig.default) {
            throw new Error("Configuration missing");
        }
        return KlevuConfig.default;
    }
    isConsentDisallowed() {
        return this.useConsent && !this.consentGiven;
    }
    setUseConsent(useConsent) {
        this.useConsent = useConsent;
        if (typeof document !== "undefined") {
            document.dispatchEvent(new CustomEvent(KlevuDomEvents.UseConsentChanged, {
                detail: {
                    useConsent,
                },
            }));
        }
    }
    setEnableKlaviyoConnector(val) {
        this.enableKlaviyoConnector = val;
        if (val) {
            Klaviyo.init();
        }
    }
    setConsentGiven(userConsent) {
        this.consentGiven = userConsent;
        if (userConsent) {
            KlevuUserSession.getDefault().generateSession();
            KlevuIpResolver.getDefault().generateIPData();
        }
        if (typeof document !== "undefined") {
            document.dispatchEvent(new CustomEvent(KlevuDomEvents.UserConsentGivenChanged, {
                detail: {
                    userConsent,
                },
            }));
        }
    }
}
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);
}

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 = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    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"]
  }; }
};
_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);
}
KlevuInit.style = klevuInitCss;

export { KlevuInit as K, StorageType as S, USER_SESSION_ID_STORAGE_KEY as U, KlevuStorage as a, KlevuConfig as b, KlevuIpResolver as c, KlevuEventV2CheckedOutProducts as d, KlevuEventV2 as e, KlevuEventV1ProductTracking as f, KlevuEventV1Search as g, KlevuEventV1CategoryView as h, isBrowser as i, KlevuEventV1CategoryProductClick as j, KlevuEventV1BannerClick as k, get as l, KlevuKMCSettings as m, KlevuUserSession as n, post as p };

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