/* Cookie consent banner logic
 *
 * Behavior:
 *   1. Reads localStorage; if a valid choice is already stored, banner stays hidden.
 *      If choice is 'all', activates any tracking scripts that were rendered as
 *      <script type="text/plain" data-cookie="analytics">.
 *   2. If no stored choice, shows the banner. Banner cannot be dismissed without
 *      clicking one of the three buttons (no Esc handler, no overlay click).
 *   3. Storage is localStorage only — no cookies are set by the consent script itself.
 *
 * Stored values: 'all' | 'essential' | 'declined'
 *   'all'       → analytics scripts activated
 *   'essential' → analytics scripts NOT activated (only strictly necessary remain)
 *   'declined'  → analytics scripts NOT activated
 *
 * Today 'essential' and 'declined' produce identical technical behavior because
 * the engine currently has only one optional category (analytics). They remain
 * distinct values so additional categories can be introduced later without
 * changing the storage format.
 */
(function () {
    'use strict';

    var STORAGE_KEY = 'aliothpress_cookie_consent';
    var VALID = ['all', 'essential', 'declined'];

    function readChoice() {
        try {
            var v = window.localStorage.getItem(STORAGE_KEY);
            return VALID.indexOf(v) >= 0 ? v : null;
        } catch (e) {
            return null;
        }
    }

    function writeChoice(value) {
        try {
            window.localStorage.setItem(STORAGE_KEY, value);
        } catch (e) {
            /* private mode / disabled storage — choice not persisted, banner re-appears next visit */
        }
    }

    function activateBlockedScripts() {
        var blocked = document.querySelectorAll(
            'script[type="text/plain"][data-cookie="analytics"]'
        );
        for (var i = 0; i < blocked.length; i++) {
            var oldScript = blocked[i];
            var newScript = document.createElement('script');
            // Copy attributes, dropping the gating ones
            for (var j = 0; j < oldScript.attributes.length; j++) {
                var attr = oldScript.attributes[j];
                if (attr.name === 'type' || attr.name === 'data-cookie') continue;
                newScript.setAttribute(attr.name, attr.value);
            }
            // Inline body, if any
            if (!oldScript.src) {
                newScript.text = oldScript.textContent;
            }
            // Append a fresh script — browser will execute it
            oldScript.parentNode.insertBefore(newScript, oldScript.nextSibling);
        }
    }

    function showBanner(banner) {
        banner.hidden = false;
    }

    function hideBanner(banner) {
        banner.hidden = true;
    }

    function init() {
        var banner = document.getElementById('cookie-consent-banner');
        if (!banner) return;

        var stored = readChoice();

        if (stored === 'all') {
            activateBlockedScripts();
            return;
        }
        if (stored === 'essential' || stored === 'declined') {
            return;
        }

        // No valid stored choice — show banner and wait for user click
        showBanner(banner);

        var buttons = banner.querySelectorAll('[data-cookie-choice]');
        for (var i = 0; i < buttons.length; i++) {
            buttons[i].addEventListener('click', function (event) {
                var choice = event.currentTarget.getAttribute('data-cookie-choice');
                if (VALID.indexOf(choice) < 0) return;
                writeChoice(choice);
                hideBanner(banner);
                if (choice === 'all') {
                    activateBlockedScripts();
                }
            });
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
