(function () {
    var STORAGE_KEY = 'zalorox_cookie_consent';
    var banner = document.querySelector('[data-cookie-consent]');

    function payloadFor(mode) {
        var necessaryOnly = {
            necessary: true,
            analytics: false,
            personalization: false,
            marketing: false
        };

        if (mode === 'all') {
            return {
                necessary: true,
                analytics: true,
                personalization: true,
                marketing: true
            };
        }

        return necessaryOnly;
    }

    function setCookie(value) {
        var secure = window.location.protocol === 'https:' ? '; secure' : '';
        document.cookie = STORAGE_KEY + '=' + encodeURIComponent(JSON.stringify(value)) + '; path=/; max-age=31536000; samesite=lax' + secure;
    }

    function persist(endpoint, value) {
        if (!endpoint || typeof fetch !== 'function') return Promise.resolve(false);

        return fetch(endpoint, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify(value)
        }).then(function (response) {
            return response.ok;
        }).catch(function () {
            return false;
        });
    }

    function save(mode) {
        var value = payloadFor(mode);
        var endpoint = banner ? banner.dataset.cookieEndpoint : '';

        setCookie(value);
        try {
            window.localStorage.setItem(STORAGE_KEY, JSON.stringify(value));
        } catch (error) {
            /* localStorage may be disabled; cookie persistence is enough. */
        }

        if (banner) banner.remove();

        persist(endpoint, value).then(function (stored) {
            if (window.ZaloroxToast) {
                var saved = banner ? banner.dataset.cookieSaved : 'Cerez tercihin kaydedildi.';
                var savedLocal = banner ? banner.dataset.cookieSavedLocal : 'Cerez tercihin bu tarayicida kaydedildi.';
                window.ZaloroxToast.show(stored ? saved : savedLocal, 'success');
            }
        });
    }

    try {
        if (banner && window.localStorage.getItem(STORAGE_KEY)) {
            banner.remove();
            return;
        }
    } catch (error) {
        /* Ignore storage access errors. */
    }

    if (!banner) return;

    banner.querySelectorAll('[data-cookie-save]').forEach(function (button) {
        button.addEventListener('click', function () {
            save(button.dataset.cookieSave || 'necessary');
        });
    });
})();
