(function(window){
    var replaceUrl = false;
    var url = new URL(window.location.href);
    var searchParams = new URLSearchParams(url.search);
    var profileCookieName = 'kprofile';

    if ('undefined' === typeof window.kuuid) {
        setUuidParam();
    }

    if ('undefined' === typeof window.kll) {
        setKllParam();
    }

    if ('undefined' === typeof window.kref) {
        setKrefParam();
    }

    setKaffParam();

    if (replaceUrl) {
        window.history.replaceState(
            null,
            null,
            url.toString()
        );
    }

    function getCookie(name) {
        var cookieRegex = '(?:(?:^|.*; *)' + name + ' *= *([^;]*).*$)|^.*$';
        var cookie = document.cookie.match(cookieRegex)[1];

        if (cookie) {
            return decodeURIComponent(cookie);
        }
    }

    function setCookie(name, value, options) {
        options = options || {};

        // If 'days' is provided, calculate max-age in seconds
        if (options.days) {
            options['max-age'] = options.days * 60 * 60 * 24;

            delete options.days;
        }

        // Build the options string from the options object
        var optionsStr = Object.keys(options).reduce(
            function(acc, key) {
                return acc + '; ' + key + '=' + options[key];
            },
            ''
        );

        // Get the current document domain and split it by '.'
        var domain = document.domain;
        var parts = domain.split('.');

        // Build an array of all possible domain variants
        // For example, for "subdomain.abc.co.uk" this will yield:
        // ["subdomain.abc.co.uk", "abc.co.uk", "co.uk"]
        var domains = [];

        if (parts.length > 1) {
            for (var i = 0; i < parts.length - 1; i++) {
                domains.push(parts.slice(i).join('.'));
            }
        } else {
            domains = [domain];
        }

        // Set the cookie for each domain variant
        for (var j = 0; j < domains.length; j++) {
            document.cookie = name + '=' + encodeURIComponent(value) + optionsStr + '; path=/; domain=' + domains[j];
        }
    }

    function generateUUID() {
        var d = new Date().getTime();
        var d2 = (
                'undefined' !== typeof performance
                && performance.now
                && (performance.now() * 1000)
            )
            || 0;

        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16;

            if (d > 0) {
                r = (d + r) % 16 | 0;
                d = Math.floor(d / 16);
            } else {
                r = (d2 + r) % 16 | 0;
                d2 = Math.floor(d2 / 16);
            }

            return (
                c === 'x'
                    ? r
                    : (r & 0x3 | 0x8)
            ).toString(16);
        });
    }

    function generateKuuid() {
        var uuid = generateUUID();
        var currentUnixTimestamp = Math.floor(Date.now() / 1000);

        return uuid + '-' + currentUnixTimestamp;
    }

    function isInIframe() {
        try {
            return window.self !== window.top;
        } catch (e) {
            return true;
        }
    }

    function validateKuuid(uuid) {
        // Explode the string by the dash
        var segments = uuid.split('-');

        // Check if the 6th segment exists & is a valid UNIX timestamp
        if (
            segments.length >= 6
            && segments[5]
        ) {
            return isValidUnixTimestamp(segments[5]);
        }

        // If no 6th segment, check the current time against the threshold
        var currentTimestamp = Math.floor(Date.now() / 1000); // Current UNIX timestamp in seconds
        var thresholdTimestamp = 1728950400; // 15 Oct 2024 00:00:00 UNIX timestamp

        // Validate if the current timestamp is before the threshold
        return currentTimestamp < thresholdTimestamp;
    }

    function setUuidParam() {
        var inIframe = isInIframe();
        var uuid;

        if (inIframe) {
            if (searchParams.has('kuid')) {
                uuid = searchParams.get('kuid');
            } else {
                uuid = getCookie('kuuid');
            }
        } else {
            uuid = getCookie('kuuid');

            if (!uuid) {
                var kartraReferrer = searchParams.get('kref');
                var kartraLid = searchParams.get('lid');

                if (
                    searchParams.has('kuid')
                    && kartraReferrer
                    && (
                        document.referrer
                        || kartraLid
                    )
                ) {
                    uuid = searchParams.get('kuid');
                }
            }
        }

        if (
            !uuid
            || !validateKuuid(uuid)
        ) {
            uuid = generateKuuid();
        }

        window.kuuid = uuid;

        if (searchParams.has('kuid')) {
            url.searchParams.delete('kuid');

            replaceUrl = true;
        }
    }

    function setKllParam() {
        var kll = getCookie('kll');

        if (!kll) {
            if (searchParams.has('kll')) {
                kll = searchParams.get('kll');
            }
        }

        window.kll = kll;

        if (searchParams.has('kll')) {
            url.searchParams.delete('kll');

            replaceUrl = true;
        }
    }

    function setKrefParam() {
        var referrer;
        var inIframe = isInIframe();

        if (inIframe) {
            if (searchParams.has('referrer')) {
                referrer = searchParams.get('referrer');
                replaceUrl = true;
                url.searchParams.delete('referrer');
            }
        } else {
            referrer = (document.referrer && document.referrer.split('?')[0]) || '';
        }

        if (searchParams.has('kref')) {
            referrer = searchParams.get('kref');
            replaceUrl = true;
            url.searchParams.delete('kref');
        }

        window.kref = referrer;
    }

    function setKaffParam() {
        if (
            searchParams.has('kaff')
            && searchParams.has('kmid')
        ) {
            var affiliateHash = searchParams.get('kaff');
            var memberHash = searchParams.get('kmid');
            var cookieName = 'kaff_' + memberHash;

            url.searchParams.delete('kaff');
            url.searchParams.delete('kmid');

            setCookie(
                cookieName,
                affiliateHash,
                {
                    path: '/',
                    days: 30,
                    secure: true,
                    samesite: 'none',
                }
            );

            replaceUrl = true;
        }
    }

    function isValidUnixTimestamp(timestamp) {
        var timestampInteger = parseInt(timestamp, 10);

        return !isNaN(timestampInteger)
            && timestampInteger > 0
            && timestamp.length === 10;
    }

    function getProfileCookie() {
        return getCookie(profileCookieName);
    }

    function setProfileCookie(cookieValue) {
        setCookie(
            profileCookieName,
            cookieValue,
            {
                path: '/',
                days: 30,
                secure: true,
                samesite: 'none',
            }
        );
    }

    window.getProfileCookie = getProfileCookie;
    window.setProfileCookie = setProfileCookie;
}(window));

var formScript = document.createElement('script');
formScript.type = 'text/javascript';
formScript.src = 'https://app.kartra.com/form/VGkfQNP8SiYf?kuid=' + window.kuuid;
formScript.className = 'js_dynamic-script-from-optin-form-generator';
document.body.appendChild(formScript);