(function () {
  var STORAGE_KEY = 'ms_consent';
  var MAX_AGE_MS  = 365 * 24 * 60 * 60 * 1000;

  function getStored() {
    try {
      var raw = localStorage.getItem(STORAGE_KEY);
      if (!raw) return null;
      var data = JSON.parse(raw);
      if (!data || !data.choice || !data.ts) return null;
      if (Date.now() - data.ts > MAX_AGE_MS) { localStorage.removeItem(STORAGE_KEY); return null; }
      return data;
    } catch (e) { return null; }
  }

  function store(choice) {
    try { localStorage.setItem(STORAGE_KEY, JSON.stringify({ choice: choice, ts: Date.now() })); } catch (e) {}
  }

  function grantAnalytics() {
    if (typeof gtag === 'function') gtag('consent', 'update', { analytics_storage: 'granted' });
  }

  var _trigger = null;

  function showBanner() {
    var banner = document.getElementById('cookie-banner');
    if (!banner) return;
    banner.hidden = false;
    document.body.classList.add('cookie-banner-open');
    var first = banner.querySelector('button');
    if (first) { setTimeout(function () { first.focus({ preventScroll: true }); }, 50); }
  }

  function hideBanner(returnFocusTo) {
    var banner = document.getElementById('cookie-banner');
    if (!banner) return;
    banner.hidden = true;
    document.body.classList.remove('cookie-banner-open');
    if (returnFocusTo && returnFocusTo.focus) { returnFocusTo.focus(); }
  }

  function buildBanner() {
    var banner = document.createElement('div');
    banner.id = 'cookie-banner';
    banner.setAttribute('role', 'region');
    banner.setAttribute('aria-label', 'Cookie consent');
    banner.hidden = true;
    banner.innerHTML =
      '<div class="cookie-banner-inner">' +
        '<p class="cookie-banner-text">This site uses cookies to understand how visitors use it. ' +
          '<a href="/privacy-policy" class="cookie-banner-link">Privacy Policy</a>.' +
        '</p>' +
        '<div class="cookie-banner-actions">' +
          '<button class="btn-pill cookie-banner-btn" id="cookie-accept" type="button">Accept</button>' +
          '<button class="btn-pill cookie-banner-btn" id="cookie-reject" type="button">Reject</button>' +
        '</div>' +
      '</div>';
    var ref = document.getElementById('nav-placeholder') || document.body.firstChild;
    document.body.insertBefore(banner, ref);

    document.getElementById('cookie-accept').addEventListener('click', function () {
      store('accepted');
      grantAnalytics();
      hideBanner(_trigger);
      _trigger = null;
    });

    document.getElementById('cookie-reject').addEventListener('click', function () {
      store('rejected');
      hideBanner(_trigger);
      _trigger = null;
    });
  }

  window.openCookieSettings = function (triggerEl) {
    _trigger = triggerEl || null;
    showBanner();
  };

  document.addEventListener('DOMContentLoaded', function () {
    buildBanner();
    if (!getStored()) showBanner();
  });
})();
