/**
 * Cookie consent banner — stores choice in localStorage (ac_cookie_consent).
 * Values: all | necessary | reject
 */
(function (global) {
  'use strict';

  var STORAGE_KEY = 'ac_cookie_consent';
  var banner = null;

  function getChoice() {
    try {
      var v = localStorage.getItem(STORAGE_KEY);
      if (v === 'all' || v === 'necessary' || v === 'reject') {
        return v;
      }
    } catch (e) { /* ignore */ }
    return null;
  }

  function setChoice(value) {
    try {
      localStorage.setItem(STORAGE_KEY, value);
    } catch (e) { /* ignore */ }
    global.dispatchEvent(new CustomEvent('ac-cookie-consent', { detail: { choice: value } }));
    hideBanner();
  }

  function allowsAnalytics() {
    return getChoice() === 'all';
  }

  function allowsPreferenceCookies() {
    var c = getChoice();
    return c === 'all' || c === 'necessary';
  }

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

  function ensureBanner() {
    if (banner || getChoice()) {
      return;
    }
    banner = document.getElementById('cookie-consent-banner');
    if (!banner) {
      return;
    }
    banner.hidden = false;
    var allBtn = document.getElementById('cookie-consent-all');
    var necBtn = document.getElementById('cookie-consent-necessary');
    var rejBtn = document.getElementById('cookie-consent-reject');
    if (allBtn) {
      allBtn.addEventListener('click', function () { setChoice('all'); });
    }
    if (necBtn) {
      necBtn.addEventListener('click', function () { setChoice('necessary'); });
    }
    if (rejBtn) {
      rejBtn.addEventListener('click', function () { setChoice('reject'); });
    }
  }

  global.AndroidCastCookieConsent = {
    getChoice: getChoice,
    allowsAnalytics: allowsAnalytics,
    allowsPreferenceCookies: allowsPreferenceCookies,
    setChoice: setChoice
  };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', ensureBanner);
  } else {
    ensureBanner();
  }
})(typeof window !== 'undefined' ? window : this);
