// Test, ob kicktipp schon definiert ist. Das kann passieren, wenn der Kunde das Script zweimal einbindet. Wir wollen aber
// den Status des "initialized" behalten und sicherstellen, dass kicktipp nur einmal ausgefÃ¼hrt wird.
// Es kann auch sein, dass es ein DOM Element mit id="kicktipp" gibt. Im Safari
// wÃ¼rde dann "var kicktipp = kicktipp || {...}" nicht funktionieren, da kicktipp
// als definiert gilt.
if (typeof kicktipp == 'undefined' || typeof kicktipp.show !== 'function') {
    window.kicktipp = {
        baseUrl: "",
        kurzname: "",
        iframe: null,
        uniq: new Date().getTime(),
        darkmodeStatus: 'auto', // auto, on, off
        show: function () {
            let srcUrl = new URL(document.currentScript.src)
            this.baseUrl = srcUrl.origin
            this.kurzname = srcUrl.pathname.split("/")[1]
            this.checkMultipleScripts()
            window.addEventListener('message', this.inbox, false)
            window.addEventListener('popstate', this.historyNavigation, false)
            this.addIframe()
            this.iframe = document.getElementById("kti" + kicktipp.uniq);
            this.iframe.onload = kicktipp.sendDarkmodeStatus
        },
        historyNavigation: function (event) {
            if (event.state && event.state.url) {
                let path = "/" + kicktipp.kurzname + "/";
                let url = new URL(event.state.url)
                if (url.searchParams.has("br_p")) {
                    path = url.searchParams.get("br_p")
                }
                kicktipp.iframe.contentWindow.postMessage({
                    event: 'fetch',
                    url: path,
                }, "*");
            }
        },
        insertTag: function (tag) {
            let script = document.currentScript;
            script.parentNode.insertBefore(tag, script.nextSibling);
        },
        checkMultipleScripts: function () {
            let srcPattern = '/' + this.kurzname + '/javascript';
            let scriptCount = document.querySelectorAll("script[src*='" + srcPattern + "']").length
            if (scriptCount > 1) {
                const errorMessage = "Kicktipp was integrated more than once on one page. Please use our integration script only once."
                let tag = document.createElement("div");
                let text = document.createTextNode(errorMessage);
                tag.appendChild(text);
                this.insertTag(tag)
                throw new Error(errorMessage)
            }
        },
        addIframe: function () {
            // style
            const cssIframe = '#kti' + kicktipp.uniq + ' { margin: 0; padding: 0; width: 1px; min-width: 100%; max-height: none; border: none; display: block; }';
            const cssDiv = '#ktd' + kicktipp.uniq + ' { min-width: 320px; width: 100%; max-height: none}';
            const style = document.createElement('style');
            style.appendChild(document.createTextNode(cssIframe + cssDiv));
            document.head.appendChild(style);
            // iframe
            let queryParams = new URLSearchParams();
            queryParams.set("url", window.location);
            let iframeUrl = this.baseUrl + "/" + this.kurzname + "/integration" + "?" + queryParams.toString();
            let div = document.createElement("div");
            div.setAttribute("id", "ktd" + kicktipp.uniq)
            div.setAttribute("style", "min-width: 320px; width: 100%; max-width: 1024px")
            let iframe = document.createElement("iframe");
            iframe.setAttribute("id", "kti" + kicktipp.uniq)
            iframe.setAttribute("src", iframeUrl)
            iframe.setAttribute("data-cy", "oframe")
            iframe.setAttribute("frameBorder", "0")
            iframe.setAttribute("scrolling", "no")
            iframe.setAttribute("style", "margin: 0; padding: 0; width: 1px; min-width: 100%; border: none; display: block;")
            div.appendChild(iframe)
            this.insertTag(div)
        },
        storage: {
            // localStorage ist im Incognito-Mode nicht erreichbar
            map: {},
            get(key) {
                try {
                    return window.localStorage.getItem(key);
                } catch (e) {
                    return this.map[key];
                }
            },
            set(key, value) {
                try {
                    window.localStorage.setItem(key, value);
                } catch (e) {
                    this.map[key] = value;
                }
            },
        },
        inbox: function (event) {
            if (event.origin !== kicktipp.baseUrl) {
                return
            }
            try {
                let message = event.data;
                if (message.event === "height") {
                    let height = parseInt(message.height);
                    kicktipp.iframe.height = height + "px";
                }
                if (message.event === "getStorage") {
                    const val = kicktipp.storage.get(message.key)
                    event.source.postMessage({ "event": "sendStorage", "key": message.key, "value": val}, event.origin);
                }
                if (message.event === "setStorage") {
                    kicktipp.storage.set(message.key, message.value)
                }
                if (message.event === "scroll") {
                    let iframe = document.getElementById("kti" + kicktipp.uniq);
                    if (iframe.getBoundingClientRect().top < 0) {
                        iframe.scrollIntoView(true);
                    }
                }
                if (message.event === "click") {
                    kicktipp.click();
                }
                if (message.event === "history") {
                    kicktipp.fixAddressBar(message.path);
                }
            } catch (e) {
                console.error(e);
            }
        },

        fixAddressBar: function (path) {
            if (path) {
                let url = new URL(window.location);
                let currentParams = url.searchParams;
                if (currentParams.has("br_p")) {
                    if (currentParams.get("br_p") !== path) {
                        currentParams.set("br_p", path);
                        history.pushState({url: url.toString()}, "", url.toString());
                        kicktipp.onPageChanged(path);
                    }
                } else {
                    currentParams.set("br_p", path);
                    history.replaceState({url: url.toString()}, "", url.toString());
                    kicktipp.onPageChanged(path);
                }
            }
        },

        click: function () {
            // no operation. A hook can be installed here to trigger clicks inside iframe
        },

        onPageChanged: function (path) {
            // no operation. A hook can be installed here to trigger clicks inside iframe
        },

        darkmode: function (status) {
            if (!["on", "off", "auto"].includes(status)) {
                status = status ? "on" : "off";
            }
            if (status !== this.darkmodeStatus) {
                this.darkmodeStatus = status;
                this.sendDarkmodeStatus()
            }
        },
        sendDarkmodeStatus() {
            kicktipp.iframe.contentWindow.postMessage({
                event: "darkmode",
                status: kicktipp.darkmodeStatus
            }, "*");
        }
    }
}
kicktipp.show();