/**
 * Google Analytics 4 for Android Cast web platform (hub + crash console).
 * Set window.ANDROIDCAST_ANALYTICS before this script loads:
 *   { measurementId: 'G-XXXXXXXX', platform: 'hub'|'crashes', debug: false }
 */
(function (global) {
  'use strict';

  var cfg = global.ANDROIDCAST_ANALYTICS || {};
  var measurementId = (cfg.measurementId || '').trim();
  var platform = cfg.platform || 'web';
  var debug = !!cfg.debug;

  function log() {
    if (debug && global.console) {
      global.console.log.apply(global.console, ['[analytics]'].concat([].slice.call(arguments)));
    }
  }

  function enabled() {
    if (global.AndroidCastCookieConsent && !global.AndroidCastCookieConsent.allowsAnalytics()) {
      var choice = global.AndroidCastCookieConsent.getChoice && global.AndroidCastCookieConsent.getChoice();
      if (choice && choice !== 'all') {
        return false;
      }
    }
    return measurementId.length > 0 && /^G-[A-Z0-9]+$/i.test(measurementId);
  }

  function ensureGtag(cb) {
    if (!enabled()) {
      return;
    }
    global.dataLayer = global.dataLayer || [];
    if (!global.gtag) {
      global.gtag = function () {
        global.dataLayer.push(arguments);
      };
    }
    if (global.__acAnalyticsLoaded) {
      if (cb) cb();
      return;
    }
    var s = document.createElement('script');
    s.async = true;
    s.src = 'https://www.googletagmanager.com/gtag/js?id=' + encodeURIComponent(measurementId);
    s.onload = function () {
      global.__acAnalyticsLoaded = true;
      global.gtag('js', new Date());
      global.gtag('config', measurementId, {
        send_page_view: false,
        anonymize_ip: true
      });
      log('loaded', measurementId);
      if (cb) cb();
    };
    document.head.appendChild(s);
  }

  function pagePath() {
    var base = (cfg.basePath || '').replace(/\/$/, '');
    var path = global.location.pathname || '/';
    if (base && path.indexOf(base) === 0) {
      path = path.slice(base.length) || '/';
    }
    return path;
  }

  function pageView(extra) {
    if (!enabled()) return;
    ensureGtag(function () {
      var params = {
        page_title: document.title || '',
        page_location: global.location.href,
        page_path: pagePath(),
        platform: platform
      };
      if (extra) {
        for (var k in extra) {
          if (Object.prototype.hasOwnProperty.call(extra, k)) params[k] = extra[k];
        }
      }
      global.gtag('event', 'page_view', params);
      log('page_view', params);
    });
  }

  function trackEvent(name, params) {
    if (!enabled() || !name) return;
    ensureGtag(function () {
      var payload = params || {};
      payload.platform = platform;
      global.gtag('event', name, payload);
      log('event', name, payload);
    });
  }

  function bindConsoleView() {
    var body = document.body;
    if (!body) return;
    var view = body.getAttribute('data-view');
    if (view) {
      trackEvent('console_view', { view_name: view });
    }
  }

  function bindHubInteractions() {
    document.addEventListener('click', function (ev) {
      var t = ev.target;
      if (!(t instanceof Element)) return;
      var card = t.closest('.hub-card, .hub-card-link');
      if (card) {
        var label = card.getAttribute('data-analytics-label')
          || (card.textContent || '').trim().slice(0, 64);
        trackEvent('hub_nav_click', { link_text: label });
        return;
      }
      if (t.closest('[data-open-docs], #hub-compass-layer, .hub-logo-layer--compass')) {
        trackEvent('hub_open_docs', { source: 'compass' });
      }
      if (t.closest('[data-close-docs]')) {
        trackEvent('hub_close_docs', {});
      }
    });
  }

  function init() {
    if (!enabled()) {
      log('disabled (no measurement id or cookie consent)');
      return;
    }
    pageView();
    if (platform === 'crashes' || String(platform).indexOf('live_') === 0) {
      bindConsoleView();
    } else if (platform === 'hub') {
      bindHubInteractions();
    }
  }

  global.addEventListener('ac-cookie-consent', function () {
    if (enabled()) {
      init();
    }
  });

  global.AndroidCastAnalytics = {
    enabled: enabled,
    pageView: pageView,
    trackEvent: trackEvent
  };

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