function getCookie(name) {
    var value = "; " + document.cookie;
    var parts = value.split("; " + name + "=");
    if (parts.length >= 2) return parts.pop().split(";").shift();
}

function submitEvent(hostname, type) {
    var clickId = getCookie('rtkclickid-store');
    if (!clickId || clickId === 'undefined') {
        clickId = sessionStorage.getItem("rtkclickid");
    }
    if (!clickId || clickId === 'undefined') {
        setTimeout(function () {
            submitEvent(hostname, type);
        }, 1000);
        return;
    }
    console.log(type);
    var xhr = new XMLHttpRequest;
    xhr.open("GET", `${hostname}/postback?clickid=${clickId}&type=${type}&eventid=${clickId}`);
    xhr.send();
    if (type === 'viewcontent' || type === 'addtocart') {
        var xhr2 = new XMLHttpRequest;
        xhr2.open("POST", '/cart/update.js');
        xhr2.setRequestHeader("Content-Type", "application/json");
        xhr2.send(
            JSON.stringify({
                attributes: {
                    '__clickid': clickId,
                }
            })
        );
    }
}

function detectProductByMeta() {
    try {
        return meta && meta.product;
    } catch (e) {
        return false;
    }
}

function detectProductByCartForm() {
    return document.querySelector("form[action='/cart/add']");
}

var pathArray = document.currentScript.src.split('/');
var protocol = pathArray[0];
var host = pathArray[2];
var hostname = protocol + '//' + host;
var cartFormDetected = false;
var isProduct = false;
document.addEventListener("DOMContentLoaded", function () {
    if (detectProductByMeta() || detectProductByCartForm()) {
        isProduct = true;
    } else {
        var path = window.location.pathname;
        var potentialHandle = path.substring(path.lastIndexOf("/") + 1);
        var xhr = new XMLHttpRequest;
        xhr.onreadystatechange = function () {
            if (xhr.status == 200) {
                submitEvent(hostname, 'viewcontent');
            }
        };
        xhr.open("GET", `/products/${potentialHandle}.json`);
        xhr.send();
    }
    if (isProduct) {
        submitEvent(hostname, 'viewcontent');

        document.body.addEventListener('click', function (event) {
            if (event.target.className && event.target.className.toString().indexOf('shopify-payment-button__button') !== -1) {
                submitEvent(hostname, 'buynow');
            }
            ;
        });
    }

    var cartForms = document.querySelectorAll("form[action='/cart/add']");
    if (cartForms) {
        cartForms.forEach(function (cartForm) {
            cartForm.addEventListener("submit", function (e) {
                submitEvent(hostname, 'addtocart');
                cartFormDetected = true;
            });
        });
    }
});

(function () {
    var open = window.XMLHttpRequest.prototype.open;

    function openReplacement() {
        this.addEventListener("load", function () {
            if (this._url && this._url.indexOf('/products/') !== -1 && this._url.indexOf('view=ajax') !== -1) {
                submitEvent(hostname, 'viewcontent');

                setTimeout(function () {
                    var cartForms = document.querySelectorAll("form[action='/cart/add']");
                    if (cartForms) {
                        cartForms.forEach(function (cartForm) {
                            cartForm.addEventListener("submit", function (e) {
                                submitEvent(hostname, 'addtocart');
                                cartFormDetected = true;
                            });
                        });
                    }
                }, 2000);
            }
            if (
                [
                    `${window.location.origin}/cart/add.js`,
                    //`${window.location.origin}/cart/update.js`,
                    //`${window.location.origin}/cart/change.js`,
                    //`${window.location.origin}/cart/clear.js`,
                ].includes((this._url ? this._url.split('?')[0] : this._url))
            ) {
                if (!cartFormDetected) {
                    submitEvent(hostname, 'addtocart');
                }
            }
        });
        return open.apply(this, arguments);
    }

    window.XMLHttpRequest.prototype.open = openReplacement;
})();

(function (ns, fetch) {
    if (typeof fetch !== 'function') return;

    ns.fetch = function () {
        var response = fetch.apply(this, arguments);

        response.then(res => {
            if ([
                `${window.location.origin}/cart/add.js`,
                //`${window.location.origin}/cart/update.js`,
                //`${window.location.origin}/cart/change.js`,
                //`${window.location.origin}/cart/clear.js`,
            ].includes((res.url ? res.url.split('?')[0] : res.url))) {
                res.clone().json().then(data => {
                    if (!cartFormDetected) {
                        submitEvent(hostname, 'addtocart');
                    }
                });
            }
        });

        return response;
    }

}(window, window.fetch))