/*!
 * pp-analytics.js — PPPHP unified-analytics browser beacon for a SEPARATE property
 * (marketing site, community portal, …). Reports pageviews + device/engagement to
 * a central collector so all your properties share one Visitor dashboard.
 *
 * Embed on the property:
 *   <script>window.__PP_ANALYTICS={url:"https://ppphp.ppradhan.com/api/analytics/collect",site:"st_xxxxxxxx"};</script>
 *   <script src="https://ppphp.ppradhan.com/assets/js/pp-analytics.js" defer></script>
 *
 * Cookieless (uses localStorage/sessionStorage), dependency-free, and defensive —
 * any failure is swallowed. Posts as text/plain so there is no CORS preflight.
 */
(function () {
  'use strict';
  if (window.__ppAnalyticsLoaded) return;
  window.__ppAnalyticsLoaded = true;

  var cfg = window.__PP_ANALYTICS || {};
  var endpoint = cfg.url || '';
  var site = cfg.site || '';
  if (!endpoint || !site) return;

  var n = navigator || {};
  var conn = n.connection || n.mozConnection || n.webkitConnection || {};

  function rid() {
    try { var a = new Uint8Array(16); (crypto || window.msCrypto).getRandomValues(a);
      return Array.prototype.map.call(a, function (b) { return ('0' + b.toString(16)).slice(-2); }).join(''); }
    catch (e) { return (Date.now().toString(16) + Math.floor(1e9 * (0.5)).toString(16)); }
  }
  function persistent(store, key) {
    try { var v = store.getItem(key); if (v) return v; v = rid(); store.setItem(key, v); return v; } catch (e) { return rid(); }
  }
  var vid = persistent(localStorage, 'ppaVid');       // returning-visitor id
  var sid = persistent(sessionStorage, 'ppaSid');     // per-session id

  function tz() { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || ''; } catch (e) { return ''; } }
  function num(v) { v = parseInt(v, 10); return isFinite(v) && v > 0 ? v : 0; }
  function loadMs() {
    try { var nav = performance.getEntriesByType && performance.getEntriesByType('navigation')[0];
      if (nav) return Math.max(0, Math.round(nav.duration || (nav.loadEventEnd - nav.startTime)));
      var t = performance.timing; if (t && t.loadEventEnd) return Math.max(0, t.loadEventEnd - t.navigationStart);
    } catch (e) {} return 0;
  }

  function base(type) {
    return {
      site: site, type: type || 'pageview', sid: sid, vid: vid,
      url: location.href, ref: document.referrer || '',
      tz: tz(), langs: (n.languages || []).slice(0, 6).join(',') || n.language || '',
      sw: num(screen.width), sh: num(screen.height), vw: num(window.innerWidth), vh: num(window.innerHeight),
      dpr: window.devicePixelRatio || 1, cd: num(screen.colorDepth),
      touch: ('ontouchstart' in window) || (n.maxTouchPoints > 0) ? 1 : 0,
      cores: num(n.hardwareConcurrency), mem: n.deviceMemory || 0,
      conn: (conn.effectiveType || '').substring(0, 12),
      dark: (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) ? 1 : 0
    };
  }

  function send(data, beacon) {
    try {
      var body = JSON.stringify(data);
      // text/plain avoids a CORS preflight; the collector reads the raw body.
      if (beacon && n.sendBeacon) { n.sendBeacon(endpoint, new Blob([body], { type: 'text/plain' })); }
      else { fetch(endpoint, { method: 'POST', mode: 'no-cors', keepalive: true,
        headers: { 'Content-Type': 'text/plain' }, body: body }).catch(function () {}); }
    } catch (e) {}
  }

  // Engagement (visible + active seconds), banked in sessionStorage across pages.
  var active = 0, engaged = true, idle = null, pageStart = Date.now();
  setInterval(function () { if (document.visibilityState === 'visible' && engaged) active++; }, 1000);
  function act() { engaged = true; if (idle) clearTimeout(idle); idle = setTimeout(function () { engaged = false; }, 30000); }
  ['mousemove', 'keydown', 'scroll', 'click', 'touchstart'].forEach(function (e) { window.addEventListener(e, act, { passive: true }); });
  act();
  function total() { var p = 0; try { p = parseInt(sessionStorage.getItem('ppaActive') || '0', 10) || 0; } catch (e) {} return p + active; }
  function flush() { var t = total(); try { sessionStorage.setItem('ppaActive', String(t)); } catch (e) {}
    send({ site: site, type: 'event', sid: sid, vid: vid, active: t, url: location.href }, true); active = 0; }
  document.addEventListener('visibilitychange', function () { if (document.visibilityState === 'hidden') flush(); });
  window.addEventListener('pagehide', flush);

  function init() { var d = base('pageview'); d.load = loadMs(); d.active = total(); send(d, false); }
  if (document.readyState === 'complete') setTimeout(init, 300);
  else window.addEventListener('load', function () { setTimeout(init, 300); });
})();
