

(function () {
  'use strict';
  if (window.__flux) { return; }
  window.__flux = 1;

  var PREVIEW = !!window.__fluxPreview;
  var COOLDOWN_MS = 30000;       
  var SESSION_CEILING = 10;      

  var cfgEl = document.getElementById('flux-cfg');
  if (!cfgEl) { return; }
  var SPOTS;
  try { SPOTS = JSON.parse(cfgEl.textContent || '[]'); } catch (e) { return; }
  if (!SPOTS || !SPOTS.length) { return; }

  var SID;
  try {
    SID = sessionStorage.getItem('flux_sid');
    if (!SID) { SID = String(Date.now()) + Math.random().toString(36).slice(2); sessionStorage.setItem('flux_sid', SID); }
  } catch (e) { SID = 'ns'; }
  function sf() { try { return parseInt(sessionStorage.getItem('flux_sf'), 10) || 0; } catch (e) { return 0; } }
  function sfBump() { try { sessionStorage.setItem('flux_sf', String(sf() + 1)); } catch (e) {} }

  function b64utf8(b) {
    var s = window.atob(b), a = new Uint8Array(s.length), i = 0;
    for (; i < s.length; i++) { a[i] = s.charCodeAt(i); }
    try { return new TextDecoder('utf-8').decode(a); } catch (e) { return s; }
  }
  function injectCode(sp) {
    try {
      var box = document.createElement('div'); box.style.display = 'none';
      box.innerHTML = b64utf8(sp.code); document.body.appendChild(box);
      var sc = box.getElementsByTagName('script'), i = 0;
      for (; i < sc.length; i++) {
        var o = sc[i], n = document.createElement('script'), a = 0;
        for (; a < o.attributes.length; a++) { n.setAttribute(o.attributes[a].name, o.attributes[a].value); }
        n.text = o.text || o.textContent || '';
        o.parentNode.replaceChild(n, o);
      }
    } catch (e) {}
  }

  
  var armed = {}, lastFire = 0;
  var bucket = { click: [], player_click: [], player_pause: [], player_play: [] };
  for (var i = 0; i < SPOTS.length; i++) {
    (function (sp) {
      if (sp.mode === 'code') {
        
        setTimeout(function () {
          if (PREVIEW) { try { console.info('[popunder] code spot ready (would inject)', sp.id); } catch (e) {} return; }
          injectCode(sp);
        }, Math.max(0, (sp.delay | 0) * 1000));
        return;
      }
      setTimeout(function () { armed[sp.id] = 1; }, Math.max(0, (sp.delay | 0) * 1000));
      String(sp.trig || 'click').split(',').forEach(function (tk) {
        (bucket[tk.trim()] || bucket.click).push(sp);
      });
    })(SPOTS[i]);
  }

  function key(sp) { return (PREVIEW ? 'fluxp_' : 'flux_') + sp.id + '_' + sp.win + '_' + sp.cap; }
  function reads(sp) {
    var raw; try { raw = localStorage.getItem(key(sp)); } catch (e) { return []; }
    if (!raw) { return []; }
    var o; try { o = JSON.parse(raw); } catch (e) { return []; }
    if (!o || typeof o !== 'object') { return []; }
    var L = Array.isArray(o.list) ? o.list : [];
    if (sp.win === 0) { return o.sid === SID ? L : []; }
    var h = Date.now() - sp.win * 3600000, out = [], j = 0;
    for (; j < L.length; j++) { if (L[j] > h) { out.push(L[j]); } }
    return out;
  }
  function remaining(sp) { var cap = sp.cap || SESSION_CEILING; return cap - reads(sp).length; }
  function record(sp) {
    var L = reads(sp); L.push(Date.now());
    var keep = Math.max(sp.cap || SESSION_CEILING, 1); if (keep > 200) { keep = 200; }
    L = L.slice(-keep);
    try { localStorage.setItem(key(sp), JSON.stringify({ sid: SID, list: L })); } catch (e) {}
  }
  function openUnder(sp) {
    var w; try { w = window.open(sp.url, '_blank'); } catch (e) { return false; }
    if (!w) { return false; }
    try { w.opener = null; } catch (e) {}
    try { w.blur(); window.focus(); window.self.focus(); } catch (e) {}
    return true;
  }

  
  
  function fire(list) {
    if (!list || !list.length) { return; }
    if (!PREVIEW && Date.now() - lastFire < COOLDOWN_MS) { return; }
    if (!PREVIEW && sf() >= SESSION_CEILING) { return; }
    var pick = null, i = 0;
    for (; i < list.length; i++) { if (armed[list[i].id] && remaining(list[i]) > 0) { pick = list[i]; break; } }
    if (!pick) { return; }
    if (PREVIEW) {
      try { console.info('[popunder] would fire spot', pick.id, '(' + (pick.trig || 'click') + ', remaining ' + remaining(pick) + ')'); } catch (e) {}
      record(pick); return;
    }
    if (openUnder(pick)) { record(pick); lastFire = Date.now(); sfBump(); try { navigator.sendBeacon('/ev/' + pick.id); } catch (e) {} }
  }

  var EXCL = 'input,textarea,select,option,button,[contenteditable="true"],a.flux__link,.flux a,.video-card--flux a,.flux-x';

  
  document.addEventListener('click', function (e) {
    if (!e || e.isTrusted === false) { return; }
    var t = e.target;
    if (t && t.closest && t.closest(EXCL)) { return; }
    fire(bucket.click);
  }, true);

  
  var player = document.querySelector('.video-player');
  var vid = document.getElementById('mainVideo');
  if (player && bucket.player_click.length) {
    player.addEventListener('click', function (e) {
      if (!e || e.isTrusted === false) { return; }
      var t = e.target;
      if (t && t.closest && t.closest('.flux-x,.flux__link,.flux a')) { return; } 
      fire(bucket.player_click);
    }, true);
  }
  if (vid) {
    
    
    
    if (bucket.player_pause.length) { vid.addEventListener('pause', function () { fire(bucket.player_pause); }); }
    if (bucket.player_play.length) { vid.addEventListener('play', function () { fire(bucket.player_play); }); }
  }
})();
