const ageVerification_script = (function () {
    return {
        initialize: function () {
            var ageVerificationShopIdentifier = 'woo';
            var ageVerificationShopGuid = '3e1f34af-053b-41ae-a195-2916b32cf85c';
            var ageVerificationUrl = 'https://mitid.bewise.dk';
            var ageVerificationSite = ageVerificationData.site_id;

            var ageVerificationSiteData = '[{"Site":"1","CountryValue":null,"CountrySelector":"","ReturnURL":"checkout","OrderField":""}]';
            var ageVerificationCountryValue = JSON.parse(ageVerificationSiteData).find(x => x.Site == ageVerificationData.site_id).CountryValue || "";
            var countrySelector = JSON.parse(ageVerificationSiteData).find(x => x.Site == ageVerificationData.site_id).CountrySelector || "";

            var ageVerificationUnder18Error = getWindowVariable('ageVerificationUnder18Error', 'Vi kunne desværre ikke bekræfte at du er over 18år og kan derfor ikke gennemføre denne ordre.');
            var ageVerificationText = getWindowVariable('ageVerificationText', 'Ny dansk lovgivning kræver aldersverificering ved køb af tobak og alkohol på internettet.');
            var ageVerificationBtnText = getWindowVariable('ageVerificationBtnText', 'Bekræft alder med MitID');
            var ageVerificationStepOneText = getWindowVariable('ageVerificationStepOneText', 'Klik og åben MitID og verificer din alder.');
            var ageVerificationStepTwoText = getWindowVariable('ageVerificationStepTwoText', 'Tak, du er nu klar til at gennemføre din ordre.');
            var ageVerificationHeaderText = getWindowVariable('ageVerificationHeaderText', 'MitID Aldersverificering');
            var ageVerificationCheckboxText = getWindowVariable('ageVerificationCheckboxText', 'My delivery country is outside Denmark');
            var ageVerificationCountryText = getWindowVariable('ageVerificationHeaderText', 'Hvis dit leveringsland er udenfor Danmark, kræves der ikke MitID aldersverficering.');
            var ageVerificationLogoUrl = getWindowVariable('ageVerificationLogo', '');

            function getWindowVariable(variableName, defaultValue) {
                return ageVerificationData[variableName] !== undefined ? ageVerificationData[variableName] : defaultValue;
            }

            var ageVerificationToken = getAgeCookieValue('verificationGuid');
            if (!ageVerificationToken) {
                ageVerificationToken = getUrlParameter('ageVerificationToken');
            }

            if (ageVerificationToken) {
                var products = JSON.parse(ageVerificationData.products);
                var productNumbers = products.map(item => item.product_id.toString());

                fetch(ageVerificationUrl + '/VerifyToken', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'VerificationGuid': ageVerificationToken,
                        'AgeVerificationShopIdentifier': ageVerificationShopIdentifier,
                        'AgeVerificationShopGuid': ageVerificationShopGuid,
                    },
                    body: JSON.stringify(productNumbers)
                })
                    .then(response => {
                        if (response.ok) {
                            return response.json();
                        } else {
                            throw new Error('Bad response from server');
                        }
                    })
                    .then(result => {
                        if (result["isOver16"]) {
                            createAgeCookieValue("ageVerified16", result["isOver16"].toString());
                        }
                        if (result["isOver18"]) {
                            createAgeCookieValue("ageVerified18", result["isOver18"].toString());
                        }
                        if (result["timestamp"]) {
                            createAgeCookieValue("ageVerifiedTimestamp", result["timestamp"].toString());
                        }
                        if (result["idToken"]) {
                            createAgeCookieValue("ageVerifiedIdToken", result["idToken"].toString());
                        }

                        deleteAgeCookieValue('verificationGuid');

                        if (ageVerificationData.isCheckout === 'true') {
                            addVerificationStep();
                        }
                    })
                    .catch(error => {
                        console.error(error);
                        deleteAgeCookie();
                        if (ageVerificationData.isCheckout === 'true') {
                            addVerificationStep();
                        }
                    });
            } else if (ageVerificationData.isCheckout === 'true') {
                addVerificationStep();
            }

            var countryChecker;
            function countryCheckInterval() {
                if (countrySelector != '') {
                    let countryValue = document.querySelector(countrySelector);
                    let cookieVerified = getAgeCookie();

                    if (!(cookieVerified.hasOwnProperty('ageVerified18') && cookieVerified.ageVerified18 === "true"
                        || cookieVerified.hasOwnProperty('ageVerified16') && cookieVerified.ageVerified16 === "true")
                        && countryChecker === undefined) {
                        countryChecker = setInterval(function () {
                            if (countryValue !== document.querySelector(countrySelector).value) {
                                countryValue = document.querySelector(countrySelector).value;

                                if (countryValue == ageVerificationCountryValue) {
                                    addVerificationStep();
                                }
                            }
                        }, 1000);
                    }
                }
            }

            function addVerificationStep() {
                let cookieVerified = getAgeCookie();
                if (!(cookieVerified.hasOwnProperty('ageVerified18') && cookieVerified.ageVerified18 === "true"
                    || cookieVerified.hasOwnProperty('ageVerified16') && cookieVerified.ageVerified16 === "true")) {
                    if (ageVerificationData.isCheckout === 'true') {
                        countryCheckInterval();
                    }
                }

                var products = JSON.parse(ageVerificationData.products);
                var productNumbers = products.map(item => item.product_id.toString());

                let headers = {
                    'Content-Type': 'application/json',
                    'AgeVerificationShopIdentifier': ageVerificationShopIdentifier,
                    'AgeVerificationShopGuid': ageVerificationShopGuid
                };

                if (cookieVerified.hasOwnProperty('ageVerified18') && cookieVerified.ageVerified18 === "true") {
                    headers['Validated18'] = true;
                }
                if (cookieVerified.hasOwnProperty('ageVerified16') && cookieVerified.ageVerified16 === "true") {
                    headers['Validated16'] = true;
                }

                if (ageVerificationData.isLoggedIn === 'true') {
                    headers['CustomerId'] = ageVerificationData.customerId;
                }

                fetch(ageVerificationUrl + '/VerifyBasket', {
                    method: 'POST',
                    headers: headers,
                    body: JSON.stringify(productNumbers)
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.needVerfication) {
                            addVerificationHTML();
                        }
                    })
                    .catch(error => {
                        console.error('An error occurred: ' + error.message);
                    });

                document.body.classList.add('ageVerificationLoaded');
            }

            function addStylesheetIfNotExists() {
                const stylesheetHref = ageVerificationUrl + '/style.css';
                const existingLink = document.querySelector(`link[href="${stylesheetHref}"]`);

                if (!existingLink) {
                    const link = createElementWithAttributes('link', {
                        rel: 'stylesheet',
                        href: stylesheetHref
                    });
                    document.head.appendChild(link);
                }
            }

            function addVerificationHTML(closeFunction, selectDeliveryOutSideDKFunction, returnUrl) {
                let isCreated = document.getElementById('ageVerification');
                if (isCreated) {
                    return;
                }

                addStylesheetIfNotExists(ageVerificationUrl);

                const ageVerificationContainer = createElementWithAttributes('div', { id: 'ageVerification' });
                const ageVerificationContent = createElementWithAttributes('div', { id: 'ageVerificationContent' });
                ageVerificationContainer.appendChild(ageVerificationContent);

                if (ageVerificationLogoUrl) {
                    const logo = createElementWithAttributes('img', { id: 'ageVerificationLogo', src: ageVerificationLogoUrl });
                    ageVerificationContent.appendChild(logo);
                }

                const ageHeader = createElementWithAttributes('span', { class: 'ageVerificationHeader' }, ageVerificationHeaderText);
                ageVerificationContent.appendChild(ageHeader);
                const ageVerificationTextDiv = createElementWithAttributes('div', { class: 'ageVerification-text' }, ageVerificationText);
                ageVerificationContent.appendChild(ageVerificationTextDiv);

                const ageVerificationRedirectDiv = createElementWithAttributes('div', { id: 'ageVerificationRedirectDiv' });
                // country
                if (countrySelector != '') {
                    const checkboxWrapper = createElementWithAttributes('div', { id: 'ageVerificationCheckboxWrapper' });
                    const checkbox = createElementWithAttributes('input', { type: 'checkbox', id: 'ageVerificationCheckbox' });
                    const checkboxLabel = createElementWithAttributes('label', { for: 'ageVerificationCheckbox' }, ageVerificationCheckboxText);

                    checkboxWrapper.appendChild(checkbox);
                    checkboxWrapper.appendChild(checkboxLabel);
                    ageVerificationContent.appendChild(checkboxWrapper);

                    const ageVerificationCountryTextDiv = createElementWithAttributes('div', { id: 'ageVerificationCountrytext' });
                    ageVerificationContent.appendChild(ageVerificationCountryTextDiv);

                    if (typeof selectDeliveryOutSideDKFunction == 'function') {
                        selectDeliveryOutSideDKFunction(checkbox);
                    }
                    else {
                        const ageVerificationCountrySelector = createElementWithAttributes('select', { id: 'ageVerificationCountryselect' });
                        ageVerificationCountrySelector.style.display = 'none';

                        const sourceSelect = document.querySelector(countrySelector);

                        const newDefaultOption = document.createElement('option');
                        newDefaultOption.text = 'Select country';
                        newDefaultOption.disabled = true;
                        newDefaultOption.selected = true;
                        ageVerificationCountrySelector.add(newDefaultOption);
                        for (let i = 0; i < sourceSelect.options.length; i++) {
                            if (sourceSelect.options[i].value == ageVerificationCountryValue) {
                                continue;
                            }
                            const newOption = document.createElement('option');
                            newOption.value = sourceSelect.options[i].value;
                            newOption.text = sourceSelect.options[i].text;
                            ageVerificationCountrySelector.add(newOption);
                        }

                        ageVerificationCountrySelector.addEventListener('change', function () {
                            sourceSelect.value = ageVerificationCountrySelector.value;
                            sourceSelect.dispatchEvent(new Event("change"));
                            if (typeof jQuery != "undefined") { 
                                jQuery('#billing_country, #shipping_country, #calc_shipping_country').val(sourceSelect.value).trigger('change');
                            }

                            if (ageVerificationCountryValue != ageVerificationCountrySelector.value) {
                                ageVerificationContainer.remove();
                            }
                        });

                        checkbox.addEventListener('change', function () {
                            if (checkbox.checked) {
                                ageVerificationCountrySelector.style.display = 'block'; // Show the div
                                ageVerificationRedirectDiv.classList.add("ageVerificationRedirectDivOverlay");
                            } else {
                                ageVerificationCountrySelector.style.display = 'none'; // Hide the div
                                ageVerificationRedirectDiv.classList.remove("ageVerificationRedirectDivOverlay");
                            }
                        });
                        ageVerificationContent.appendChild(ageVerificationCountrySelector);
                    }
                }
                // country end


                const stepsList = createElementWithAttributes('ul');
                const steps = [
                    { text: ageVerificationStepOneText, number: '1' },
                    { text: ageVerificationStepTwoText, number: '2' }
                ];

                steps.forEach(step => {
                    const stepItem = createElementWithAttributes('li');
                    const stepNumber = createElementWithAttributes('span', {}, step.number);
                    stepItem.appendChild(stepNumber);
                    stepItem.append(step.text);
                    stepsList.appendChild(stepItem);
                });
                ageVerificationRedirectDiv.appendChild(stepsList);

                const verifyAgeButton = createElementWithAttributes('div', {
                    id: 'verify-age-button',
                    class: 'ageVerification-button ageVerification-button-disabled'
                }, `<span>${ageVerificationBtnText}</span>`);


                verifyAgeButton.addEventListener('click', () => {
                    const verificationGuid = generateGUID();

                    createAgeCookieValue('verificationGuid', verificationGuid);

                    const baseUrl = new URL('/start-verification', ageVerificationUrl);
                    let params = new URLSearchParams({
                        ageVerificationShopGuid,
                        ageVerificationShopIdentifier,
                        site: ageVerificationSite,
                        verificationGuid: verificationGuid
                    });

                    if (returnUrl !== undefined && returnUrl != "") {
                        params.append('returnUrl', returnUrl);
                    }

                    if (window.ageVerificationData !== undefined && window.ageVerificationData.customerId) {
                        params.append('CustomerId', window.ageVerificationData.customerId);
                    }

                    baseUrl.search = params.toString();

                    window.location.href = baseUrl.toString();
                });
                ageVerificationRedirectDiv.appendChild(verifyAgeButton);
                ageVerificationContent.appendChild(ageVerificationRedirectDiv);

                const ageVerificationClose = createElementWithAttributes('div', { id: 'ageVerificationClose' }, '×');
                ageVerificationClose.addEventListener('click', () => {
                    if (typeof closeFunction == 'function') {
                        closeFunction();
                    } else {
                        window.location.href = "/"
                    }
                });
                ageVerificationContent.appendChild(ageVerificationClose);

                document.body.appendChild(ageVerificationContainer);
            }

            function createElementWithAttributes(tag, attributes = {}, innerHTML = '') {
                const element = document.createElement(tag);
                Object.keys(attributes).forEach(attr => element.setAttribute(attr, attributes[attr]));
                element.innerHTML = innerHTML;
                return element;
            }

            var cookieName = "ageVerificationCookie";
            function deleteAgeCookie() {
                document.cookie = cookieName + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
            }

            function deleteAgeCookieValue(name) {
                let cookieObj = getAgeCookie();
                delete cookieObj[name];
                let encryptedValue = btoa(simpleEncryptDecrypt(JSON.stringify(cookieObj)));

                let expirationTime = new Date();
                expirationTime.setTime(expirationTime.getTime() + (1 * 60 * 60 * 1000)); // 1 hour = 60 minutes * 60 seconds * 1000 milliseconds
                let expires = "expires=" + expirationTime.toUTCString();
                document.cookie = cookieName + "=" + encodeURIComponent(encryptedValue) + "; " + expires + "; path=/";
            }

            function createAgeCookieValue(name, value) {
                let cookieObj = getAgeCookie();
                cookieObj[name] = value;
                let encryptedValue = btoa(simpleEncryptDecrypt(JSON.stringify(cookieObj)));
                setCookie(encryptedValue);
            }

            function setCookie(encryptedValue) {
                let expirationTime = new Date();
                expirationTime.setTime(expirationTime.getTime() + (1 * 60 * 60 * 1000)); // 1 hour = 60 minutes * 60 seconds * 1000 milliseconds
                let expires = "expires=" + expirationTime.toUTCString();
                document.cookie = cookieName + "=" + encodeURIComponent(encryptedValue) + "; " + expires + "; path=/";
            }

            function getAgeCookieValue(name) {
                let cookieObj = getAgeCookie();
                return cookieObj[name];
            }

            function getAgeCookie() {
                let cookieName = "ageVerificationCookie";
                if (document.cookie.length > 0) {
                    let start = document.cookie.indexOf(cookieName + "=");
                    if (start != -1) {
                        start = start + cookieName.length + 1;
                        let end = document.cookie.indexOf(";", start);
                        if (end == -1) end = document.cookie.length;
                        let encryptedValue = decodeURIComponent(document.cookie.substring(start, end));

                        let decryptedValue = simpleEncryptDecrypt(atob(encryptedValue));
                        return JSON.parse(decryptedValue);
                    }
                }
                return {};
            }

            function simpleEncryptDecrypt(input) {
                let key = "ageVerification";
                let output = '';
                for (let i = 0; i < input.length; i++) {
                    output += String.fromCharCode(input.charCodeAt(i) ^ key.charCodeAt(i % key.length));
                }
                return output;
            }

            function getUrlParameter(name) {
                name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
                var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
                var results = regex.exec(window.location.search);
                return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
            }

            function generateGUID() {
                return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                    var r = Math.random() * 16 | 0,
                        v = c == 'x' ? r : (r & 0x3 | 0x8);
                    return v.toString(16);
                });
            }

            if (window.ageVerificationData.hasOwnProperty('isLoggedIn')) {
                var isLoggedIn = getAgeCookieValue("isLoggedIn");
                if (ageVerificationData.isLoggedIn === 'true' && (isLoggedIn === "false" || isLoggedIn == false || isLoggedIn == undefined)) {
                    createAgeCookieValue("isLoggedIn", true);

                    let cookieVerified = getAgeCookie();

                    if (cookieVerified.hasOwnProperty('ageVerified18')) {
                        return;
                    }
                    if (cookieVerified.hasOwnProperty('ageVerified16')) {
                        return;
                    }

                    let headers = {
                        'Content-Type': 'application/json',
                        'AgeVerificationShopIdentifier': ageVerificationShopIdentifier,
                        'AgeVerificationShopGuid': ageVerificationShopGuid,
                        'CustomerId': ageVerificationData.customerId
                    };

                    fetch(ageVerificationUrl + '/VerifyCustomer', {
                        method: 'POST',
                        headers: headers,
                    })
                        .then(response => response.json())
                        .then(result => {
                            createAgeCookieValue("ageVerified16", result["isOver16"].toString());
                            createAgeCookieValue("ageVerified18", result["isOver18"].toString());
                            createAgeCookieValue("ageVerifiedTimestamp", result["timestamp"].toString());
                            createAgeCookieValue("ageVerifiedIdToken", result["idToken"].toString());

                             
                        })
                        .catch(error => {
                            console.error('Error fetching VerifyCustomer:', error);
                        });
                } else if (ageVerificationData.isLoggedIn === 'false' && (isLoggedIn === "true" || isLoggedIn == true)) {
                    deleteAgeCookie();
                }
            }
        }
    };
})();


function ageVerification_ready(callback) {
    if (document.readyState != 'loading') callback();
    else if (document.addEventListener) document.addEventListener('DOMContentLoaded', callback);
    else document.attachEvent('onreadystatechange', function () {
        if (document.readyState == 'complete') callback();
    });
}

ageVerification_ready(function () {
    if (window.ageVerificationData !== undefined) {
        ageVerification_script.initialize();
    }
});