(function () {
  'use strict';

  var NOTICE_KEY = 'aiml_analytics_notice';
  var LEGACY_CONSENT_KEY = 'aiml_analytics_consent';
  var LEGACY_DISABLED_KEY = 'tianji.disabled';
  var configEl = document.getElementById('tianji-config');
  if (!configEl) {
    return;
  }

  var trackerUrl = configEl.dataset.trackerUrl;
  var websiteId = configEl.dataset.websiteId;
  var userId = configEl.dataset.userId || '';

  function getStorageItem(key) {
    try {
      return localStorage.getItem(key);
    } catch (e) {
      return null;
    }
  }

  function setStorageItem(key, value) {
    try {
      localStorage.setItem(key, value);
    } catch (e) {
      /* ignore storage errors */
    }
  }

  function removeStorageItem(key) {
    try {
      localStorage.removeItem(key);
    } catch (e) {
      /* ignore storage errors */
    }
  }

  function showBanner() {
    var banner = document.getElementById('cookie-consent-banner');
    if (banner) {
      banner.removeAttribute('hidden');
    }
  }

  function hideBanner() {
    var banner = document.getElementById('cookie-consent-banner');
    if (banner) {
      banner.setAttribute('hidden', '');
    }
  }

  function trackEvent(name, data) {
    if (window.tianji && typeof window.tianji.track === 'function') {
      window.tianji.track(name, data || {});
    }
  }

  function identifyUser() {
    if (!userId || !window.tianji || typeof window.tianji.identify !== 'function') {
      return;
    }
    window.tianji.identify({ userId: userId });
  }

  function loadTracker() {
    if (document.querySelector('script[data-tianji-loaded="true"]')) {
      identifyUser();
      return;
    }

    var script = document.createElement('script');
    script.async = true;
    script.defer = true;
    script.src = trackerUrl;
    script.setAttribute('data-website-id', websiteId);
    script.setAttribute('data-do-not-track', 'true');
    script.setAttribute('data-tianji-loaded', 'true');

    script.onload = function () {
      identifyUser();
      document.dispatchEvent(new CustomEvent('tianji:ready'));
    };

    document.head.appendChild(script);
  }

  function migrateLegacyConsent() {
    var legacyConsent = getStorageItem(LEGACY_CONSENT_KEY);
    var legacyDisabled = getStorageItem(LEGACY_DISABLED_KEY);

    if (legacyConsent === 'accepted') {
      setStorageItem(NOTICE_KEY, 'acknowledged');
      removeStorageItem(LEGACY_CONSENT_KEY);
      removeStorageItem(LEGACY_DISABLED_KEY);
      return 'migrated_acknowledged';
    }

    if (legacyConsent === 'declined' || legacyDisabled === '1') {
      removeStorageItem(LEGACY_CONSENT_KEY);
      removeStorageItem(LEGACY_DISABLED_KEY);
      return 'migrated_declined';
    }

    return null;
  }

  function acknowledgeNotice() {
    setStorageItem(NOTICE_KEY, 'acknowledged');
    hideBanner();
    window.aimlTrackWhenReady('notice_acknowledged');
  }

  function bindBannerControls() {
    var acknowledgeBtn = document.getElementById('cookie-consent-acknowledge');
    var manageLinks = document.querySelectorAll('[data-open-cookie-preferences]');

    if (acknowledgeBtn) {
      acknowledgeBtn.addEventListener('click', acknowledgeNotice);
    }
    manageLinks.forEach(function (link) {
      link.addEventListener('click', function (event) {
        event.preventDefault();
        showBanner();
      });
    });
  }

  window.aimlTrack = function (name, data) {
    trackEvent(name, data);
  };

  window.aimlTrackWhenReady = function (name, data) {
    if (window.tianji && typeof window.tianji.track === 'function') {
      trackEvent(name, data);
      return;
    }
    document.addEventListener('tianji:ready', function handler() {
      document.removeEventListener('tianji:ready', handler);
      trackEvent(name, data);
    });
  };

  function initNotice() {
    bindBannerControls();
    loadTracker();

    var migration = migrateLegacyConsent();
    var notice = getStorageItem(NOTICE_KEY);

    if (notice === 'acknowledged' || migration === 'migrated_acknowledged') {
      hideBanner();
      return;
    }

    showBanner();
  }

  initNotice();
})();
