(function(){
  "use strict";
  var cfg = window.ITP_TRACK || {};
  if(!cfg.ajax || !cfg.id || !cfg.nonce) return;

  var start = Date.now();
  var maxScroll = 0;
  var clicked = false;
  var storage = window.localStorage || null;

  function uuid(prefix){
    return prefix + '_' + Math.random().toString(36).slice(2) + Date.now().toString(36);
  }
  function getStored(key, prefix){
    try{
      if(!storage) return uuid(prefix);
      var v = storage.getItem(key);
      if(!v){ v = uuid(prefix); storage.setItem(key, v); }
      return v;
    }catch(e){ return uuid(prefix); }
  }
  var visitorId = getStored('itp_visitor_id', 'v');
  var sessionId = getStored('itp_session_id', 's');
  try{
    var last = parseInt(sessionStorage.getItem('itp_session_time') || '0',10);
    if(!last || Date.now()-last > 30*60*1000){
      sessionId = uuid('s');
      if(storage) storage.setItem('itp_session_id', sessionId);
    }
    sessionStorage.setItem('itp_session_time', String(Date.now()));
  }catch(e){}

  function params(){ return new URLSearchParams(window.location.search || ''); }
  function parentLandingUrl(){
    var p = params();
    var parent = p.get('itp_parent') || '';
    return parent || document.referrer || location.href;
  }
  function sourceFromRef(){
    var p = params();
    if(p.get('utm_source')) return p.get('utm_source');
    if(p.get('gclid')) return 'google';
    if(p.get('fbclid')) return 'facebook';
    if(p.get('ttclid')) return 'tiktok';
    if(p.get('msclkid')) return 'microsoft';
    if(document.referrer){
      try{ return new URL(document.referrer).hostname.replace(/^www\./,''); }catch(e){}
    }
    return 'direct/internal';
  }
  function preservedParams(){
    var p = params();
    var keep = ['gclid','fbclid','msclkid','ttclid','tbclid','ob_click_id','outbrain_click_id','click_id','ad_id','adset_id','campaign_id','utm_source','utm_medium','utm_campaign','utm_content','utm_term'];
    var out = new URLSearchParams();
    keep.forEach(function(k){
      var v = p.get(k);
      if(v) out.set(k, v);
    });
    return out;
  }
  function appendTrackingParams(dest){
    var keep = preservedParams();
    if(!dest) return dest;
    try{
      var u = new URL(dest, window.location.href);
      keep.forEach(function(v,k){
        if(!u.searchParams.has(k)) u.searchParams.set(k, v);
      });
      if(cfg.id && !u.searchParams.has('itp_bridge')) u.searchParams.set('itp_bridge', String(cfg.id));
      if(sessionId && !u.searchParams.has('itp_session')) u.searchParams.set('itp_session', String(sessionId));
      if(visitorId && !u.searchParams.has('itp_visitor')) u.searchParams.set('itp_visitor', String(visitorId));
      return u.toString();
    }catch(e){
      return dest;
    }
  }
  function detectDevice(){
    var ua = navigator.userAgent || '';
    if(/Mobi|Android|iPhone|iPad/i.test(ua)) return 'mobile';
    if(/Tablet|iPad/i.test(ua)) return 'tablet';
    return 'desktop';
  }
  function browser(){
    var ua = navigator.userAgent || '';
    if(/Edg\//.test(ua)) return 'Edge';
    if(/Chrome\//.test(ua)) return 'Chrome';
    if(/Safari\//.test(ua) && !/Chrome\//.test(ua)) return 'Safari';
    if(/Firefox\//.test(ua)) return 'Firefox';
    return 'Other';
  }
  function os(){
    var ua = navigator.userAgent || '';
    if(/Windows/i.test(ua)) return 'Windows';
    if(/Android/i.test(ua)) return 'Android';
    if(/iPhone|iPad|iOS/i.test(ua)) return 'iOS';
    if(/Mac OS/i.test(ua)) return 'macOS';
    if(/Linux/i.test(ua)) return 'Linux';
    return 'Other';
  }
  function basePayload(eventType, destination){
    var p = params();
    return {
      action:'itp_track_event', nonce:cfg.nonce, presell_id:cfg.id,
      event_type:eventType, session_id:sessionId, visitor_id:visitorId,
      source:sourceFromRef(), medium:p.get('utm_medium') || '', campaign:p.get('utm_campaign') || '',
      content:p.get('utm_content') || '', term:p.get('utm_term') || '',
      referrer:document.referrer || '', landing_url:parentLandingUrl(),
      destination:destination || '', device:detectDevice(), browser:browser(), os:os(),
      screen:(screen.width || 0)+'x'+(screen.height || 0), language:navigator.language || '',
      timezone:(Intl.DateTimeFormat().resolvedOptions().timeZone || ''),
      scroll_depth:String(maxScroll), time_on_page:String(Math.round((Date.now()-start)/1000))
    };
  }

  function saveLastTouch(destination){
    try{
      if(!cfg || !cfg.id || !cfg.ajax || !cfg.nonce || !storage) return;
      var bp = basePayload('touch', destination || '');
      var touch = {
        bridgeId: cfg.id,
        nonce: cfg.nonce,
        ajax: cfg.ajax,
        sessionId: sessionId,
        visitorId: visitorId,
        source: bp.source || '',
        medium: bp.medium || '',
        campaign: bp.campaign || '',
        content: bp.content || '',
        term: bp.term || '',
        referrer: bp.referrer || '',
        landingUrl: bp.landing_url || location.href,
        destination: destination || '',
        url: location.href,
        expires: Date.now() + (30 * 24 * 60 * 60 * 1000)
      };
      storage.setItem('itp_last_touch', JSON.stringify(touch));
    }catch(e){}
  }

  function encode(obj){
    var fd = new FormData();
    Object.keys(obj).forEach(function(k){ fd.append(k, obj[k]); });
    return fd;
  }
  var itpPixelFiredRules = {};
  function itpPixelRules(){
    return Array.isArray(window.ITP_CONVERSION_RULES) ? window.ITP_CONVERSION_RULES : [];
  }
  function itpPublicContext(payload, destination){
    var base = window.ITP_PIXEL_CONTEXT || {};
    return {
      bridgeId: cfg.id || base.bridgeId || '',
      bridgeTitle: base.bridgeTitle || '',
      eventName: payload.event_type || '',
      destination: destination || payload.destination || '',
      source: payload.source || '',
      medium: payload.medium || '',
      campaign: payload.campaign || '',
      content: payload.content || '',
      term: payload.term_value || payload.term || '',
      sessionId: payload.session_id || '',
      visitorId: payload.visitor_id || '',
      landingUrl: payload.landing_url || location.href,
      url: location.href,
      timeOnPage: payload.time_on_page || '0',
      scrollDepth: payload.scroll_depth || '0'
    };
  }
  function dispatchPixelEvent(eventType, destination, payload){
    try{
      document.dispatchEvent(new CustomEvent('itp:event', {detail: itpPublicContext(payload, destination)}));
      document.dispatchEvent(new CustomEvent('itp:' + eventType, {detail: itpPublicContext(payload, destination)}));
    }catch(e){}
  }
  function ruleMatches(rule, eventType, destination){
    if(!rule || rule.enabled === false) return false;
    var trigger = String(rule.trigger || '').trim() || 'lead_submit';
    var hay = String(destination || location.href || '');
    var needle = String(rule.urlContains || rule.url_contains || '').trim();
    if(trigger === 'page_view'){
      return !needle || hay.indexOf(needle) !== -1 || String(location.pathname || '').indexOf(needle) !== -1;
    }
    if(trigger !== eventType) return false;
    if(needle && hay.indexOf(needle) === -1 && String(location.pathname || '').indexOf(needle) === -1) return false;
    return true;
  }
  function runConversionRules(eventType, destination, payload){
    var matched = false;
    var internal = false;
    itpPixelRules().forEach(function(rule, idx){
      if(!ruleMatches(rule, eventType, destination)) return;
      var key = String(rule.id || (rule.name || 'rule') + '_' + idx + '_' + eventType);
      if(itpPixelFiredRules[key]) return;
      itpPixelFiredRules[key] = true;
      matched = true;
      if(rule.internal && eventType !== 'conversion') internal = true;
      if(rule.code){
        try{
          var ctx = itpPublicContext(payload, destination);
          var cleanCode = String(rule.code).replace(/<\/?script[^>]*>/gi, '');
          var fn = new Function('eventName','destination','value','currency','ctx', cleanCode);
          fn.call(window, eventType, destination || '', rule.value || '', rule.currency || 'USD', ctx);
        }catch(err){
          try{ if(window.console && console.warn) console.warn('[Invalid Traffic] Conversion rule failed:', rule.name || key, err); }catch(e){}
        }
      }
    });
    return {matched: matched, internal: internal};
  }
  function send(eventType, destination, sync){
    var payload = basePayload(eventType, destination);
    var ruleResult = runConversionRules(eventType, destination, payload);
    dispatchPixelEvent(eventType, destination, payload);
    if(ruleResult && ruleResult.internal && eventType !== 'conversion'){
      setTimeout(function(){ send('conversion', destination || eventType, false); }, 30);
    }
    try{
      if(sync && navigator.sendBeacon){
        navigator.sendBeacon(cfg.ajax, encode(payload));
        return Promise.resolve();
      }
    }catch(e){}
    return fetch(cfg.ajax,{method:'POST',body:encode(payload),credentials:'same-origin'}).catch(function(){});
  }

  function cleanMoney(v){
    if(v === undefined || v === null) return '';
    return String(v).replace(/[^0-9.,-]/g, '').slice(0, 32);
  }
  function cleanCurrency(v){
    v = String(v || '').replace(/[^a-z]/ig, '').toUpperCase();
    return (v || 'USD').slice(0, 8);
  }
  function buildConversionPayload(input){
    var p = params();
    var opts = {};
    if(input && typeof input === 'object') opts = input;
    else opts = {name: input || 'conversion'};
    var eventName = opts.name || opts.eventName || p.get('event') || p.get('event_name') || 'conversion';
    var value = opts.value;
    if(value === undefined || value === null || value === '') value = p.get('value') || p.get('amount') || p.get('price') || p.get('total') || '';
    value = cleanMoney(value);
    var currency = cleanCurrency(opts.currency || p.get('currency') || p.get('currency_code') || 'USD');
    var externalId = opts.external_id || opts.externalId || opts.order_id || opts.orderId || opts.transaction || p.get('external_id') || p.get('order_id') || p.get('transaction') || p.get('transaction_id') || '';
    externalId = String(externalId || '').slice(0, 120);
    var destination = String(opts.destination || eventName || 'conversion');
    if(value) destination += '|value=' + value;
    if(currency) destination += '|currency=' + currency;
    if(externalId) destination += '|external_id=' + externalId;
    var payload = basePayload('conversion', destination);
    payload.event_name = String(eventName || 'conversion').slice(0, 120);
    payload.value = value;
    payload.currency = currency;
    payload.external_id = externalId;
    if(opts.source) payload.source = String(opts.source).slice(0, 120);
    if(opts.medium) payload.medium = String(opts.medium).slice(0, 120);
    if(opts.campaign) payload.campaign = String(opts.campaign).slice(0, 180);
    if(opts.content) payload.content = String(opts.content).slice(0, 180);
    if(opts.term) payload.term = String(opts.term).slice(0, 180);
    return payload;
  }
  function sendConversion(input, sync){
    var payload = buildConversionPayload(input);
    var destination = payload.destination || 'conversion';
    var ruleResult = runConversionRules('conversion', destination, payload);
    dispatchPixelEvent('conversion', destination, payload);
    try{
      if(sync && navigator.sendBeacon){
        navigator.sendBeacon(cfg.ajax, encode(payload));
        return Promise.resolve({ok:true, beacon:true, payload:payload});
      }
    }catch(e){}
    return fetch(cfg.ajax,{method:'POST',body:encode(payload),credentials:'same-origin'})
      .then(function(r){ return r.json().catch(function(){ return {}; }); })
      .then(function(res){ return {ok: !!(res && res.success), response: res, payload: payload, ruleMatched: !!(ruleResult && ruleResult.matched)}; })
      .catch(function(err){ return {ok:false, error:err, payload:payload}; });
  }
  function updateScroll(){
    var doc = document.documentElement, body = document.body;
    var scrollTop = window.scrollY || doc.scrollTop || body.scrollTop || 0;
    var height = Math.max(body.scrollHeight, doc.scrollHeight) - window.innerHeight;
    if(height <= 0) maxScroll = Math.max(maxScroll, 100);
    else maxScroll = Math.max(maxScroll, Math.min(100, Math.round(scrollTop/height*100)));
  }
  window.addEventListener('scroll', updateScroll, {passive:true});
  window.addEventListener('resize', updateScroll);
  updateScroll();

  function initDelay(){
    var delay = parseInt(cfg.delay || document.body.getAttribute('data-itp-delay') || '0', 10);
    if(!delay || delay < 1) return;
    var pill = document.querySelector('[data-itp-delay-pill]');
    var span = pill ? pill.querySelector('span') : null;
    document.body.classList.add('itp-is-locked');
    if(pill) pill.hidden = false;
    var left = delay;
    var timer = setInterval(function(){
      left--;
      if(span) span.textContent = String(left);
      if(left <= 0){
        clearInterval(timer);
        document.body.classList.remove('itp-is-locked');
        if(pill) pill.hidden = true;
      }
    },1000);
  }
  initDelay();

  document.addEventListener('click', function(e){
    if(e.target.closest('[data-itp-vsl-lead-open],[data-itp-vsl-lead-close],[data-itp-vsl-lead-form]')) return;
    var link = e.target.closest('[data-itp-destination]');
    if(!link) return;
    if(document.body.classList.contains('itp-is-locked')){
      e.preventDefault();
      return;
    }
    var dest = link.getAttribute('data-itp-destination') || link.getAttribute('href') || '';
    if(!dest || dest === '#') return;
    dest = appendTrackingParams(dest);
    clicked = true;
    e.preventDefault();
    saveLastTouch(dest);
    send('click', dest, true);
    var target = (link.getAttribute('data-itp-open-target') || link.getAttribute('target') || '').toLowerCase();
    var inVsl = !!link.closest('[data-itp-vsl]');
    var navigate = function(){
      if(target === '_blank'){
        var w = window.open(dest, '_blank', 'noopener');
        if(!w) window.location.href = dest;
        return;
      }
      if(target === '_top' || inVsl){
        try{
          if(window.top && window.top !== window){ window.top.location.href = dest; return; }
        }catch(err){
          var nw = window.open(dest, '_blank', 'noopener');
          if(nw) return;
        }
      }
      window.location.href = dest;
    };
    setTimeout(navigate, 90);
  });


  window.ITPTrackEvent = function(eventName, destination){ return send(eventName || 'conversion', destination || '', false); };
  window.ITPTrackConversion = function(input){ return sendConversion(input || {name:'conversion'}, false); };
  window.ITPTrackPurchase = window.ITPTrackConversion;

  function initVsl(){
    var wrap = document.querySelector('[data-itp-vsl]');
    if(!wrap) return;
    var video = wrap.querySelector('video.itp-vsl-video');
    var vcfg = window.ITP_VSL || {};
    function itpVslApplyLiveAspect(){
      if(!video) return;
      var w = parseInt(video.videoWidth || 0, 10);
      var h = parseInt(video.videoHeight || 0, 10);
      if(!w || !h) return;
      var ratio = w / Math.max(1, h);
      var aspect = w + ' / ' + h;
      wrap.style.setProperty('--itp-vsl-aspect', aspect);
      wrap.classList.toggle('itp-ratio-vertical', ratio < 0.82);
      wrap.classList.toggle('itp-ratio-square', ratio >= 0.82 && ratio <= 1.22);
      wrap.classList.toggle('itp-ratio-horizontal', ratio > 1.22);
      var f = wrap.querySelector('.itp-vsl-video-frame');
      if(f){ f.style.setProperty('--itp-vsl-aspect', aspect); }
    }
    if(video){
      ['loadedmetadata','loadeddata','canplay','durationchange'].forEach(function(evt){
        video.addEventListener(evt, itpVslApplyLiveAspect);
      });
      setTimeout(itpVslApplyLiveAspect, 120);
      setTimeout(itpVslApplyLiveAspect, 800);
    }
    var frame = wrap.querySelector('.itp-vsl-video-frame');
    var progress = wrap.querySelector('.itp-vsl-progress i');
    var overlay = wrap.querySelector('[data-itp-vsl-overlay]');
    if(overlay && overlay.classList.contains('pulse') && !overlay.querySelector(':scope > .itp-vsl-pulse-ring')){
      var ring = document.createElement('span');
      ring.className = 'itp-vsl-pulse-ring';
      ring.setAttribute('aria-hidden','true');
      overlay.insertBefore(ring, overlay.firstChild);
    }

    // 0.18.151: do not rewrite saved Smartplay x/y/width on the public renderer.
    // Preview, saved meta and final embed must use the same coordinate system.
    // Only force the full-screen templates to remain truly full-frame.

    function syncSmartplayOneCoordinateRenderer(){
      if(!overlay) return;
      var s=overlay.style;
      var x=s.getPropertyValue('--itp-vsl-x') || '50%';
      var y=s.getPropertyValue('--itp-vsl-y') || '50%';
      var w=s.getPropertyValue('--itp-vsl-w') || '42%';
      var r=s.getPropertyValue('--itp-vsl-r') || '0deg';
      s.setProperty('--itp-design-x', x);
      s.setProperty('--itp-design-y', y);
      s.setProperty('--itp-design-w', w);
      s.setProperty('--itp-design-r', r);
      if(overlay.classList && (overlay.classList.contains('template-full') || overlay.classList.contains('template-large'))){
        s.setProperty('--itp-vsl-x','50%'); s.setProperty('--itp-vsl-y','50%'); s.setProperty('--itp-vsl-w','100%');
        s.setProperty('--itp-design-x','50%'); s.setProperty('--itp-design-y','50%'); s.setProperty('--itp-design-w','100%');
      }
    }
    function applySmartplayInnerGeometry(){
      if(!overlay) return;
      var inner = (overlay.classList && overlay.classList.contains('itp-sp180') ? overlay.querySelector(':scope > .itp-smartplay-inner') : null) || overlay.querySelector('.itp-smartplay-public-canvas > .itp-smartplay-inner') || overlay.querySelector(':scope > .itp-smartplay-inner');
      if(!inner) return;
      var isFull = overlay.classList && (overlay.classList.contains('template-full') || overlay.classList.contains('template-large'));
      if(isFull){
        inner.style.setProperty('left','0','important');
        inner.style.setProperty('top','0','important');
        inner.style.setProperty('width','100%','important');
        inner.style.setProperty('height','100%','important');
        inner.style.setProperty('max-width','100%','important');
        inner.style.setProperty('max-height','100%','important');
        inner.style.setProperty('transform','none','important');
        inner.style.setProperty('aspect-ratio','auto','important');
        return;
      }
      var st = overlay.style;
      var x = inner.getAttribute('data-itp-sp-x');
      var y = inner.getAttribute('data-itp-sp-y');
      var w = inner.getAttribute('data-itp-sp-w');
      var r = inner.getAttribute('data-itp-sp-r');
      var isMobileCanvas = false;
      try{ isMobileCanvas = !!(window.matchMedia && window.matchMedia('(max-width: 640px)').matches); }catch(e){}
      // v0.18.158: the public renderer must not rewrite a mobile canvas back to desktop values.
      // The iframe/Elementor output now uses the same saved coordinate family as the Studio canvas.
      if(isMobileCanvas){
        x = (st.getPropertyValue('--itp-vsl-mobile-x') || st.getPropertyValue('--itp-design-x') || st.getPropertyValue('--itp-vsl-x') || (x ? x + '%' : '50%')).trim();
        y = (st.getPropertyValue('--itp-vsl-mobile-y') || st.getPropertyValue('--itp-design-y') || st.getPropertyValue('--itp-vsl-y') || (y ? y + '%' : '50%')).trim();
        w = (st.getPropertyValue('--itp-vsl-mobile-w') || st.getPropertyValue('--itp-design-w') || st.getPropertyValue('--itp-vsl-w') || (w ? w + '%' : '42%')).trim();
        r = (st.getPropertyValue('--itp-vsl-mobile-r') || st.getPropertyValue('--itp-design-r') || st.getPropertyValue('--itp-vsl-r') || (r ? r + 'deg' : '0deg')).trim();
      } else {
        x = (st.getPropertyValue('--itp-design-x') || st.getPropertyValue('--itp-vsl-x') || (x ? x + '%' : '50%')).trim();
        y = (st.getPropertyValue('--itp-design-y') || st.getPropertyValue('--itp-vsl-y') || (y ? y + '%' : '50%')).trim();
        w = (st.getPropertyValue('--itp-design-w') || st.getPropertyValue('--itp-vsl-w') || (w ? w + '%' : '42%')).trim();
        r = (st.getPropertyValue('--itp-design-r') || st.getPropertyValue('--itp-vsl-r') || (r ? r + 'deg' : '0deg')).trim();
      }
      inner.style.setProperty('left', x, 'important');
      inner.style.setProperty('top', y, 'important');
      inner.style.setProperty('width', w, 'important');
      inner.style.setProperty('height', 'auto', 'important');
      inner.style.setProperty('max-width', 'none', 'important');
      inner.style.setProperty('max-height', 'none', 'important');
      inner.style.setProperty('transform', 'translate(-50%,-50%) rotate(' + r + ')', 'important');
      inner.style.setProperty('transform-origin', 'center center', 'important');
    }
    function repairSmartplayOverlayBounds(){
      if(!overlay) return;
      syncSmartplayOneCoordinateRenderer();
      if(overlay.classList && (overlay.classList.contains('template-full') || overlay.classList.contains('template-large'))){
        overlay.style.setProperty('--itp-vsl-x','50%');
        overlay.style.setProperty('--itp-vsl-y','50%');
        overlay.style.setProperty('--itp-vsl-w','100%');
        overlay.style.setProperty('--itp-vsl-mobile-x','50%');
        overlay.style.setProperty('--itp-vsl-mobile-y','50%');
        overlay.style.setProperty('--itp-vsl-mobile-w','100%');
        overlay.style.setProperty('--itp-design-x','50%');
        overlay.style.setProperty('--itp-design-y','50%');
        overlay.style.setProperty('--itp-design-w','100%');
      }
      applySmartplayInnerGeometry();
    }
    function scheduleSmartplayOverlayRepair(){
      repairSmartplayOverlayBounds();
      requestAnimationFrame(repairSmartplayOverlayBounds);
      setTimeout(repairSmartplayOverlayBounds, 80);
      setTimeout(repairSmartplayOverlayBounds, 360);
    }
    scheduleSmartplayOverlayRepair();
    var cta = wrap.querySelector('[data-itp-vsl-cta]');
    var belowCtaArea = wrap.querySelector('[data-itp-vsl-below-cta-area]');
    var pauseCard = wrap.querySelector('[data-itp-vsl-pause-card]');
    var hook = wrap.querySelector('[data-itp-vsl-hook]');
    var resumeBadge = wrap.querySelector('[data-itp-vsl-resume-badge]');
    var resumePanel = wrap.querySelector('[data-itp-vsl-resume-panel]');
    var resumeContinueBtn = wrap.querySelector('[data-itp-vsl-resume-continue]');
    var resumeRestartBtn = wrap.querySelector('[data-itp-vsl-resume-restart]');
    var resumeTarget = 0;
    var bigPlayBtn = wrap.querySelector('[data-itp-vsl-big-play]');
    var smallPlayBtn = wrap.querySelector('[data-itp-vsl-small-play]');
    var customControls = wrap.querySelector('[data-itp-vsl-custom-controls]');
    var progressWrap = wrap.querySelector('.itp-vsl-progress');
    var back10Btn = wrap.querySelector('[data-itp-vsl-back10]');
    var forward10Btn = wrap.querySelector('[data-itp-vsl-forward10]');
    var volumeBtn = wrap.querySelector('[data-itp-vsl-volume]');
    var fullscreenBtn = wrap.querySelector('[data-itp-vsl-fullscreen]');
    var speedBtn = wrap.querySelector('[data-itp-vsl-speed]');
    var controlProgress = wrap.querySelector('[data-itp-vsl-control-progress] i');
    var controlProgressBtn = wrap.querySelector('[data-itp-vsl-control-progress]');
    var controlTime = wrap.querySelector('[data-itp-vsl-time]');
    var lastResizeSent = 0;
    function applyVideoAspect(){
      if(!video || !frame) return;
      var w = parseInt(video.videoWidth || 0, 10);
      var h = parseInt(video.videoHeight || 0, 10);
      if(!w || !h) return;
      var aspect = w + ' / ' + h;
      [wrap, frame, video].forEach(function(el){
        if(el && el.style) el.style.setProperty('--itp-vsl-aspect', aspect);
      });
      var ratio = w / Math.max(1, h);
      [wrap, frame].forEach(function(el){
        if(!el || !el.classList) return;
        el.classList.toggle('itp-ratio-vertical', ratio < 0.82);
        el.classList.toggle('itp-ratio-square', ratio >= 0.82 && ratio <= 1.22);
        el.classList.toggle('itp-ratio-horizontal', ratio > 1.22);
      });
      requestParentResize(true);
      if(typeof scheduleSmartplayOverlayRepair === "function") scheduleSmartplayOverlayRepair();
    }
    function isBelowCtaVisible(){
      return !!(cta && cta.classList && cta.classList.contains('below') && !cta.hidden && belowCtaArea && !belowCtaArea.hidden);
    }
    function currentEmbedHeight(){
      var h = 0;
      try{
        if(wrap){
          var r = wrap.getBoundingClientRect();
          h = Math.max(h, r.height || 0);
        }
        if(!h){
          var body = document.body, html = document.documentElement;
          if(body) h = Math.max(h, body.scrollHeight || 0, body.offsetHeight || 0);
          if(html) h = Math.max(h, html.scrollHeight || 0, html.offsetHeight || 0);
        }
      }catch(e){}
      // The CTA area already has bottom padding for shadow/pulse; add only a small safety buffer.
      return Math.max(120, Math.ceil((h || 0) + (isBelowCtaVisible() ? 14 : 6)));
    }
    function requestParentResize(force, reason){
      if(window.parent === window) return;
      var now = Date.now();
      if(!force && now - lastResizeSent < 450) return;
      lastResizeSent = now;
      var embedId='';try{embedId=(new URLSearchParams(window.location.search||'')).get('itp_embed_id')||'';}catch(e){}
      var payload = {type:'itp-vsl-resize', id:(embedId || vcfg.id || cfg.id || ''), height:currentEmbedHeight(), ctaVisible:isBelowCtaVisible(), force:!!force, reason:reason||''};
      try{ window.parent.postMessage(payload, '*'); }catch(e){}
    }
    function requestParentResizeSettled(reason){
      requestAnimationFrame(function(){
        requestAnimationFrame(function(){ requestParentResize(true, reason || 'settled'); });
      });
    }
    if(window.ResizeObserver && wrap && !wrap.__itpVslResizeObserver){
      try{
        wrap.__itpVslResizeObserver = new ResizeObserver(function(){ requestParentResize(false); if(typeof scheduleSmartplayOverlayRepair === 'function') scheduleSmartplayOverlayRepair(); });
        wrap.__itpVslResizeObserver.observe(wrap);
      }catch(e){}
    }
    window.addEventListener('resize', function(){ if(typeof scheduleSmartplayOverlayRepair === 'function') scheduleSmartplayOverlayRepair(); }, {passive:true});

    var sent = {};
    var userStarted = !vcfg.smartAutoplay;
    var ctaTimer = null, ctaEndTimer = null, hookTimer = null, hookEndTimer = null, teaserWindowTimer = null;
    var hasPlayedOnce = false;
    var lastUserStartAt = 0;
    function once(name, dest){ if(sent[name]) return; sent[name]=true; send(name, dest || '', false); }
    function formatTime(sec){
      sec = Math.max(0, Math.floor(sec || 0));
      var m = Math.floor(sec / 60), s = sec % 60;
      return m + ':' + (s < 10 ? '0' : '') + s;
    }
    function updateCustomControls(){
      if(!video) return;
      var teaser = isTeaser();
      var preStart = isPreStart();
      if(customControls) customControls.hidden = preStart || teaser;
      if(progressWrap) progressWrap.hidden = preStart || teaser;
      if(bigPlayBtn){
        var overlayVisible = !!(overlay && !overlay.hidden);
        bigPlayBtn.hidden = overlayVisible || !userStarted || !video.paused || teaser;
      }
      if(smallPlayBtn) smallPlayBtn.textContent = video.paused ? '▶' : 'Ⅱ';
      if(volumeBtn) volumeBtn.textContent = (video.muted || video.volume === 0) ? '🔇' : '🔊';
      if(speedBtn) speedBtn.textContent = formatSpeed(video.playbackRate || configuredSpeed);
      if(controlTime) controlTime.textContent = formatTime(video.currentTime || 0);
      if(controlProgress && video.duration && isFinite(video.duration)) controlProgress.style.width = Math.max(0, Math.min(100, video.currentTime / video.duration * 100)) + '%';
      wrap.classList.toggle('is-teaser', teaser);
    }
    once('vsl_view');
    var ctaMemoryKey = 'itp_vsl_cta_seen_' + (vcfg.id || cfg.id || 'player');
    function ctaSeenBefore(){
      try{ return !!(vcfg.ctaRemember && localStorage.getItem(ctaMemoryKey) === '1'); }catch(e){ return false; }
    }
    function ctaDestination(){ return cta ? (cta.getAttribute('data-itp-destination') || cta.getAttribute('href') || '') : ''; }
    function ctaRevealAt(){
      var start = parseFloat(vcfg.ctaDelay || 0);
      var pitch = parseFloat(vcfg.pitchTime || 0);
      if(!isFinite(start) || start < 0) start = 0;
      if(!isFinite(pitch) || pitch < 0) pitch = 0;
      // “Show at seconds” is the real CTA reveal time. Pitch is only a fallback marker.
      return start > 0 ? start : pitch;
    }
    function setBelowCtaVisible(visible){
      var isBelow = !!(cta && cta.classList && cta.classList.contains('below'));
      if(!isBelow) return;
      if(belowCtaArea){
        belowCtaArea.hidden = !visible;
        belowCtaArea.classList.toggle('is-visible', !!visible);
      }
      if(wrap) wrap.classList.toggle('has-visible-below-cta', !!visible);
    }
    function hideCta(){
      if(cta) cta.hidden = true;
      setBelowCtaVisible(false);
    }
    function showCta(){
      if(!cta) return;
      if(!cta.hidden){
        setBelowCtaVisible(true);
        requestParentResize(false, 'cta-visible');
        return;
      }
      if(video && (!userStarted || isTeaser())) return;
      cta.hidden = false;
      setBelowCtaVisible(true);
      try{ if(vcfg.ctaRemember) localStorage.setItem(ctaMemoryKey, '1'); }catch(e){}
      once('vsl_cta_view', ctaDestination());
      requestParentResizeSettled('cta');
      setTimeout(function(){ requestParentResize(true, 'cta'); }, 240);
      if(vcfg.ctaAutoScroll && cta.classList.contains('below')){
        setTimeout(function(){ try{ cta.scrollIntoView({behavior:'smooth', block:'center'}); }catch(e){} }, 80);
      }
    }
    function scheduleCta(){
      if(!cta || ctaTimer || vcfg.ctaOn === false) return;
      if(video) return;
      if(ctaSeenBefore()){ showCta(); return; }
      var delay = ctaRevealAt();
      if(delay > 0) ctaTimer = setTimeout(showCta, delay * 1000);
      else showCta();
    }
    function showHook(){
      if(!hook || !hook.hidden || vcfg.hookOn === false) return;
      if(video && (!userStarted || isTeaser())) return;
      hook.hidden = false;
      once('vsl_hook_view');
      requestParentResize(true);
      if(!video){
        var hookEnd = parseFloat(vcfg.hookEnd || 0);
        var hookStart = parseFloat(vcfg.hookStart || 0);
        if(hookEnd > hookStart){ hookEndTimer = setTimeout(function(){ hook.hidden = true; }, (hookEnd - hookStart) * 1000); }
      }
    }
    function scheduleHook(){
      if(!hook || hookTimer || vcfg.hookOn === false) return;
      if(video) return;
      var hookStart = parseFloat(vcfg.hookStart || 0);
      hookTimer = setTimeout(showHook, Math.max(0, hookStart) * 1000);
    }
    var leadModal = wrap.querySelector('[data-itp-vsl-lead-modal]');
    var leadForm = wrap.querySelector('[data-itp-vsl-lead-form]');
    var leadMessage = wrap.querySelector('[data-itp-vsl-lead-message]');
    function openLeadModal(){
      if(!leadModal) return;
      leadModal.hidden = false;
      wrap.classList.add('itp-vsl-lead-open');
      send('lead_view', 'lead_popup', false);
      requestParentResize(true, 'lead-open');
      setTimeout(function(){
        var input = leadModal.querySelector('input[name="email"],input[name="name"]');
        if(input){ try{ input.focus(); }catch(e){} }
      },80);
    }
    function closeLeadModal(){
      if(!leadModal) return;
      leadModal.hidden = true;
      wrap.classList.remove('itp-vsl-lead-open');
      requestParentResize(true, 'lead-close');
    }
    if(leadModal){
      leadModal.addEventListener('click', function(e){
        if(e.target && e.target.closest('[data-itp-vsl-lead-close]')){ e.preventDefault(); closeLeadModal(); }
      });
    }
    if(leadForm){
      leadForm.addEventListener('submit', function(e){
        e.preventDefault();
        var email = leadForm.querySelector('input[name="email"]');
        if(!email || !email.value || !/.+@.+\..+/.test(email.value)){
          if(email) email.focus();
          return;
        }
        var payload = basePayload('lead_submit', leadForm.getAttribute('data-itp-redirect') || 'lead_popup');
        payload.action = 'itp_submit_lead';
        payload.email = email.value;
        var nameInput = leadForm.querySelector('input[name="name"]');
        var phoneInput = leadForm.querySelector('input[name="phone"]');
        payload.name = nameInput ? nameInput.value : '';
        payload.phone = phoneInput ? phoneInput.value : '';
        var submit = leadForm.querySelector('button[type="submit"]');
        if(submit) submit.disabled = true;
        fetch(cfg.ajax,{method:'POST',body:encode(payload),credentials:'same-origin'}).then(function(r){return r.json();}).then(function(res){
          if(!res || !res.success){ throw new Error((res&&res.data&&res.data.message)||'Could not save lead.'); }
          send('lead_submit', payload.destination || 'lead_popup', true);
          if(leadMessage) leadMessage.hidden = false;
          var redirect = leadForm.getAttribute('data-itp-redirect') || '';
          if(redirect){
            saveLastTouch(redirect);
            send('lead_redirect', redirect, true);
            setTimeout(function(){ try{ if(window.top && window.top !== window){ window.top.location.href = appendTrackingParams(redirect); return; } }catch(err){} window.location.href = appendTrackingParams(redirect); }, 650);
          }
        }).catch(function(err){
          if(leadMessage){ leadMessage.hidden=false; leadMessage.textContent = (err && err.message) ? err.message : 'Could not save lead.'; }
        }).finally(function(){ if(submit) submit.disabled = false; });
      });
    }
    if(cta){
      cta.addEventListener('click', function(e){
        if(cta.hasAttribute('data-itp-vsl-lead-open')){
          e.preventDefault();
          e.stopPropagation();
          once('vsl_cta_click', 'lead_popup');
          openLeadModal();
          return;
        }
        once('vsl_cta_click', ctaDestination());
      });
    }
    /* 0.18.87: Public/embed player starts clean.
       CTA, Mini Hook and Thumb Recovery must not appear before the main video timeline.
       The admin preview may show them for editing, but the final player must not. */
    if(cta && vcfg.ctaOn !== false){ hideCta(); }
    if(hook && vcfg.hookOn !== false) hook.hidden = true;
    if(pauseCard) pauseCard.hidden = true;
    if(!video){ scheduleCta(); scheduleHook(); return; }
    function normalizeSpeed(value){
      var n = parseFloat(value || '1');
      if(!isFinite(n) || n <= 0) n = 1;
      return Math.max(0.25, Math.min(4, Math.round(n * 100) / 100));
    }
    function formatSpeed(value){
      return String(normalizeSpeed(value)).replace(/\.0+$/, '') + '×';
    }
    var configuredSpeed = normalizeSpeed(vcfg.speed || '1');
    var manualSpeedOverride = false;
    function applyConfiguredSpeed(force){
      if(!video) return;
      if(manualSpeedOverride && !force) return;
      try{ video.defaultPlaybackRate = configuredSpeed; }catch(e){}
      try{ video.playbackRate = configuredSpeed; }catch(e){}
      if(speedBtn) speedBtn.textContent = formatSpeed(video.playbackRate || configuredSpeed);
    }
    applyConfiguredSpeed(true);
    var mainVideo = video.getAttribute('data-itp-main-video') || '';
    var teaserVideo = video.getAttribute('data-itp-teaser-video') || '';
    var resumeKey = 'itp_vsl_position_' + (vcfg.id || cfg.id || 'player');
    var resumeKeyLegacy = 'itp_vsl_position_' + (cfg.id || vcfg.id || 'player');
    var resumeKeys = [];
    [resumeKey, resumeKeyLegacy].forEach(function(k){ if(k && resumeKeys.indexOf(k) === -1) resumeKeys.push(k); });
    function writeResumePosition(pos){
      if(!vcfg.resumeOn || !pos || pos <= 5) return;
      try{
        resumeKeys.forEach(function(k){ localStorage.setItem(k, String(Math.floor(pos))); });
        localStorage.setItem('itp_vsl_position_last', String(Math.floor(pos)));
      }catch(e){}
    }
    function clearResumePosition(){
      try{ resumeKeys.forEach(function(k){ localStorage.removeItem(k); }); }catch(e){}
    }
    function currentSrc(){ return (video.currentSrc || (video.querySelector('source') ? video.querySelector('source').src : video.src) || ''); }
    function hasTeaserVideo(){
      return !!(mainVideo && teaserVideo);
    }
    function isSeparateTeaser(){
      return !!(hasTeaserVideo() && !userStarted && currentSrc().indexOf(teaserVideo) !== -1);
    }
    function isTeaser(){
      /* 0.18.87: the pre-click state is always a teaser state.
         With no separate teaser video, the main video loops muted as the teaser. */
      return !!(!userStarted && vcfg.smartAutoplay);
    }
    function isPreStart(){
      return !!(!userStarted && vcfg.smartAutoplay);
    }
    function hideOverlay(){
      if(!overlay) return;
      overlay.hidden = true;
      overlay.classList.add('is-consumed');
      overlay.setAttribute('aria-hidden','true');
      overlay.style.setProperty('display','none','important');
      overlay.style.pointerEvents = 'none';
    }
    function showOverlay(){
      if(!overlay) return;
      overlay.classList.remove('is-consumed');
      overlay.removeAttribute('aria-hidden');
      overlay.style.pointerEvents = '';
      overlay.style.removeProperty('display');
      overlay.hidden = false;
    }
    var teaserStartApplied = false;
    function bgWindow(){
      var start = parseFloat(vcfg.bgStart || 0);
      var end = parseFloat(vcfg.bgEnd || 0);
      if(!isFinite(start) || start < 0) start = 0;
      if(!isFinite(end) || end < 0) end = 0;
      if(video && video.duration && isFinite(video.duration)){
        start = Math.min(start, Math.max(0, video.duration - 0.2));
        if(end > 0) end = Math.min(end, video.duration);
      }
      if(end > 0 && end <= start + 0.25) end = 0;
      return { start: start, end: end };
    }
    function applyBgStart(force){
      if(!video || !isSeparateTeaser()) return;
      var w = bgWindow();
      var seek = function(){
        if(!video || !isSeparateTeaser() || video.readyState < 1) return;
        if(!force && teaserStartApplied && !(w.start > 0 && video.currentTime < w.start - 0.35)) return;
        try{
          if(force || Math.abs((video.currentTime || 0) - w.start) > 0.35) video.currentTime = w.start;
          teaserStartApplied = true;
        }catch(e){}
      };
      if(video.readyState >= 1) seek();
      else {
        try{ video.addEventListener('loadedmetadata', seek, {once:true}); }catch(e){}
      }
    }
    function maintainTeaserWindow(){
      if(!video || !isSeparateTeaser()) return;
      var w = bgWindow();
      if(video.readyState < 1) return;
      var now = video.currentTime || 0;
      if(now < w.start - 0.18){ applyBgStart(true); return; }
      if(w.end > w.start && now >= Math.max(w.start + 0.25, w.end - 0.05)){
        try{ video.currentTime = w.start; video.play().catch(function(){}); }catch(e){}
      }
    }
    function setVideoSource(url){
      var source = video.querySelector('source');
      if(source) source.src = url; else video.src = url;
      teaserStartApplied = false;
      try{ video.defaultPlaybackRate = configuredSpeed; }catch(e){}
      video.load();
      applyConfiguredSpeed(false);
    }
    function switchToMainVideo(){
      if(!mainVideo) return false;
      var src = currentSrc();
      /* 0.18.87: after the visitor clicks, always force the player back
         to the main video source. The old check depended on isSeparateTeaser(),
         but userStarted is set before this call, so teaser detection could fail. */
      if(!src || src.indexOf(mainVideo) === -1){
        setVideoSource(mainVideo);
        video.loop = false;
        return true;
      }
      return false;
    }
    function savePosition(){
      if(!vcfg.resumeOn || !userStarted || isTeaser() || !video) return;
      var dur = video.duration || 0;
      var pos = Math.floor(video.currentTime || 0);
      if(!pos || pos <= 5) return;
      if(dur && isFinite(dur) && pos >= dur - 5) return;
      writeResumePosition(pos);
    }
    function storedResumePosition(){
      if(!vcfg.resumeOn || !video) return 0;
      try{
        var pos = 0;
        resumeKeys.forEach(function(k){
          if(pos) return;
          var v = parseInt(localStorage.getItem(k) || '0', 10);
          if(v && v > 5) pos = v;
        });
        if(!pos || pos <= 5) return 0;
        /* 0.18.188: when a separate background/teaser video is configured,
           the first loaded duration belongs to the teaser, not to the main VSL.
           Do not reject a saved main-video position while still in the pre-click
           smart autoplay state. This keeps Continue Watching working with:
           background teaser video -> click Smart Autoplay -> main video -> F5/return. */
        var preClickTeaserState = !!(!userStarted && vcfg.smartAutoplay);
        if(video.duration && isFinite(video.duration) && !preClickTeaserState && !isSeparateTeaser()){
          if(pos >= video.duration - 5) return 0;
        }
        return pos;
      }catch(e){}
      return 0;
    }
    function showResumePanelIfNeeded(){
      if(!vcfg.resumeOn || !resumePanel || userStarted) return false;
      var pos = storedResumePosition();
      if(!pos) return false;
      resumeTarget = pos;
      try{
        resumePanel.style.setProperty('--itp-resume-bg', vcfg.resumeBg || '#581c87');
        resumePanel.style.setProperty('--itp-resume-text', vcfg.resumeTextColor || '#ffffff');
        var msg = resumePanel.querySelector('strong');
        if(msg) msg.textContent = vcfg.resumeMessage || 'You already started watching this video';
        if(resumeContinueBtn) resumeContinueBtn.lastChild.nodeValue = vcfg.resumeContinueText || 'Continue watching?';
        if(resumeRestartBtn) resumeRestartBtn.lastChild.nodeValue = vcfg.resumeRestartText || 'Start from the beginning?';
      }catch(e){}
      resumePanel.hidden = false;
      resumePanel.removeAttribute('hidden');
      resumePanel.style.setProperty('display','flex','important');
      resumePanel.style.setProperty('z-index','90','important');
      resumePanel.style.setProperty('pointer-events','auto','important');
      if(overlay){
        overlay.hidden = true;
        overlay.setAttribute('aria-hidden','true');
        overlay.style.setProperty('display','none','important');
        overlay.style.pointerEvents = 'none';
      }
      try{ video.pause(); }catch(e){}
      requestParentResize(true, 'resume-panel');
      return true;
    }
    function hideResumePanel(){
      if(!resumePanel) return;
      resumePanel.hidden = true;
      resumePanel.setAttribute('hidden','hidden');
      resumePanel.style.removeProperty('display');
      resumePanel.style.removeProperty('z-index');
      resumePanel.style.removeProperty('pointer-events');
    }
    function restorePosition(){
      if(!vcfg.resumeOn || isTeaser() || !video.duration || !isFinite(video.duration)) return;
      if(resumeTarget > 5 && resumeTarget < video.duration - 5){
        try{ video.currentTime = resumeTarget; }catch(e){}
        if(resumeBadge){ resumeBadge.hidden = false; setTimeout(function(){ resumeBadge.hidden = true; }, 2200); }
      }
    }
    function startTeaser(){
      if(showResumePanelIfNeeded()) return;
      video.muted = true;
      video.setAttribute('muted','muted');
      video.playsInline = true;
      showOverlay();
      if(!hasTeaserVideo()){
        video.loop = true;
        applyConfiguredSpeed(false);
        var reset = function(){ try{ if(video.readyState >= 1 && (video.currentTime || 0) < 0.05) video.currentTime = 0; }catch(e){} };
        reset();
        try{ video.addEventListener('loadedmetadata', reset, {once:true}); }catch(e){}
        var playMainTeaser = video.play();
        if(playMainTeaser && playMainTeaser.catch) playMainTeaser.catch(function(){});
        updateCustomControls();
        return;
      }
      video.loop = true;
      applyConfiguredSpeed(false);
      applyBgStart(true);
      setTimeout(function(){ applyBgStart(true); }, 120);
      setTimeout(function(){ applyBgStart(false); }, 420);
      setTimeout(function(){ applyBgStart(false); }, 900);
      var playAttempt = video.play();
      if(playAttempt && playAttempt.catch) playAttempt.catch(function(){});
      if(teaserWindowTimer) clearInterval(teaserWindowTimer);
      teaserWindowTimer = setInterval(maintainTeaserWindow, 180);
      updateCustomControls();
    }
    function userStart(){
      if(userStarted) return;
      lastUserStartAt = Date.now();
      hideOverlay();
      hideResumePanel();
      if(teaserWindowTimer){ clearInterval(teaserWindowTimer); teaserWindowTimer = null; }
      if(ctaTimer){ clearTimeout(ctaTimer); ctaTimer = null; }
      if(ctaEndTimer){ clearTimeout(ctaEndTimer); ctaEndTimer = null; }
      if(hookTimer){ clearTimeout(hookTimer); hookTimer = null; }
      if(hookEndTimer){ clearTimeout(hookEndTimer); hookEndTimer = null; }
      if(cta){ hideCta(); }
      if(hook) hook.hidden = true;
      if(pauseCard) pauseCard.hidden = true;
      userStarted = true;
      var changedToMain = switchToMainVideo();
      video.loop = false;
      video.controls = !!vcfg.controlsOn;
      video.muted = false;
      video.removeAttribute('muted');
      function playMainFromZero(){
        try{ video.currentTime = resumeTarget > 5 ? resumeTarget : 0; }catch(e){}
        applyConfiguredSpeed(false);
        var p = video.play();
        if(p && p.catch) p.catch(function(){});
        hideOverlay();
        once('vsl_unmute');
        once('vsl_play');
        if(ctaSeenBefore()) setTimeout(showCta, 160);
        updateCustomControls();
      }
      if(changedToMain && video.readyState < 1){
        var booted = false;
        var boot = function(){ if(booted) return; booted = true; playMainFromZero(); };
        try{ video.addEventListener('loadedmetadata', boot, {once:true}); }catch(e){}
        try{ video.addEventListener('canplay', boot, {once:true}); }catch(e){}
        setTimeout(boot, 500);
      } else {
        setTimeout(playMainFromZero, changedToMain ? 30 : 0);
      }
    }
    if(resumeContinueBtn) resumeContinueBtn.addEventListener('click', function(e){
      e.preventDefault(); e.stopPropagation();
      if(!resumeTarget) resumeTarget = storedResumePosition();
      userStart();
    });
    if(resumeRestartBtn) resumeRestartBtn.addEventListener('click', function(e){
      e.preventDefault(); e.stopPropagation();
      resumeTarget = 0;
      clearResumePosition();
      userStart();
    });
    if(vcfg.smartAutoplay){ startTeaser(); }
    setTimeout(function(){ if(!userStarted) showResumePanelIfNeeded(); }, 150);
    setTimeout(function(){ if(!userStarted) showResumePanelIfNeeded(); }, 650);
    setTimeout(function(){ if(!userStarted) showResumePanelIfNeeded(); }, 1600);
    if(wrap && !wrap.__itpSmartOverlayForceStartBound){
      wrap.__itpSmartOverlayForceStartBound = '1';
      wrap.addEventListener('click', function(e){
        if(!vcfg.smartAutoplay || userStarted) return;
        if(!overlay || overlay.hidden) return;
        e.preventDefault();
        e.stopPropagation();
        userStart();
      }, true);
    }
    if(overlay){
      var overlayStart = function(e){ e.preventDefault(); e.stopPropagation(); userStart(); };
      overlay.addEventListener('pointerdown', overlayStart, true);
      overlay.addEventListener('touchstart', overlayStart, {capture:true, passive:false});
      overlay.addEventListener('click', overlayStart, true);
      var smartInner = (overlay.classList && overlay.classList.contains('itp-sp180') ? overlay.querySelector(':scope > .itp-smartplay-inner') : null) || overlay.querySelector('.itp-smartplay-public-canvas > .itp-smartplay-inner') || overlay.querySelector(':scope > .itp-smartplay-inner');
      if(smartInner && smartInner !== overlay){
        smartInner.addEventListener('pointerdown', overlayStart, true);
        smartInner.addEventListener('touchstart', overlayStart, {capture:true, passive:false});
        smartInner.addEventListener('click', overlayStart, true);
      }
    }
    if(video){
      video.addEventListener('pointerdown', function(e){
        if(overlay && !overlay.hidden && !userStarted){
          e.preventDefault();
          e.stopPropagation();
          userStart();
        }
      }, true);
    }
    function toggleCustomPlay(){
      if(!video) return;
      if(!userStarted || isTeaser()){ userStart(); return; }
      if(video.paused){ video.play().catch(function(){}); }
      else if(vcfg.customControls && vcfg.customControls.allowPause){ video.pause(); }
    }
    if(bigPlayBtn) bigPlayBtn.addEventListener('click', function(e){ e.preventDefault(); e.stopPropagation(); toggleCustomPlay(); });
    if(smallPlayBtn) smallPlayBtn.addEventListener('click', function(e){ e.preventDefault(); e.stopPropagation(); toggleCustomPlay(); });
    if(back10Btn) back10Btn.addEventListener('click', function(e){ e.preventDefault(); e.stopPropagation(); if(video && userStarted && !isTeaser()) video.currentTime = Math.max(0, (video.currentTime || 0) - 10); updateCustomControls(); });
    if(forward10Btn) forward10Btn.addEventListener('click', function(e){ e.preventDefault(); e.stopPropagation(); if(video && userStarted && !isTeaser() && video.duration) video.currentTime = Math.min(video.duration, (video.currentTime || 0) + 10); updateCustomControls(); });
    if(volumeBtn) volumeBtn.addEventListener('click', function(e){ e.preventDefault(); e.stopPropagation(); if(!video) return; video.muted = !video.muted; updateCustomControls(); });
    if(speedBtn) speedBtn.addEventListener('click', function(e){
      e.preventDefault(); e.stopPropagation(); if(!video) return;
      manualSpeedOverride = true;
      var baseRates=[0.9,1,1.1,1.2,1.3,1.4,1.5,1.75,2];
      if(baseRates.every(function(x){ return Math.abs(x - configuredSpeed) > 0.01; })) baseRates.unshift(configuredSpeed);
      var cur=normalizeSpeed(video.playbackRate || configuredSpeed);
      var idx=baseRates.findIndex(function(x){ return Math.abs(x - cur) < 0.01; });
      var next=baseRates[(idx + 1) % baseRates.length];
      try{ video.defaultPlaybackRate = next; video.playbackRate = next; }catch(err){}
      speedBtn.textContent = formatSpeed(next);
    });
    if(fullscreenBtn) fullscreenBtn.addEventListener('click', function(e){
      e.preventDefault();
      e.stopPropagation();
      var target = frame || video;
      if(!target) return;
      if(document.fullscreenElement){
        if(document.exitFullscreen) document.exitFullscreen().catch(function(){});
        return;
      }
      if(target.requestFullscreen) target.requestFullscreen().catch(function(){});
    });
    document.addEventListener('fullscreenchange', function(){
      if(frame) frame.classList.toggle('is-fullscreen', document.fullscreenElement === frame);
    });
    if(controlProgressBtn) controlProgressBtn.addEventListener('click', function(e){ e.preventDefault(); e.stopPropagation(); if(!video || !video.duration || !userStarted || isTeaser()) return; var rect = controlProgressBtn.getBoundingClientRect(); var pct = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width)); video.currentTime = pct * video.duration; updateCustomControls(); });
    updateCustomControls();
    setTimeout(function(){ applyVideoAspect(); requestParentResize(true, 'boot'); }, 80);
    setTimeout(function(){ applyVideoAspect(); requestParentResize(false, 'boot'); }, 650);
    if(vcfg.interactionSound){
      var unlock = function(ev){
        if(userStarted || !vcfg.smartAutoplay) return;
        try{
          if(frame) frame.setAttribute('data-itp-interaction-sound', 'triggered');
          if(wrap) wrap.setAttribute('data-itp-interaction-sound', 'triggered');
          if(window && window.console && window.console.info) window.console.info('[Invalid Traffic] Detect page interaction triggered Smart Autoplay', ev && ev.type ? ev.type : 'interaction');
        }catch(debugErr){}
        try{ userStart(); }catch(e){}
        document.removeEventListener('click', unlock, true);
        document.removeEventListener('pointerdown', unlock, true);
        document.removeEventListener('touchstart', unlock, true);
        document.removeEventListener('keydown', unlock, true);
        document.removeEventListener('wheel', unlock, true);
        document.removeEventListener('scroll', unlock, true);
        try{ window.removeEventListener('message', unlockFromParent, false); }catch(msgErr){}
      };
      var unlockFromParent = function(ev){
        var d = ev && ev.data ? ev.data : {};
        if(!d || d.type !== 'itp-vsl-interaction-start') return;
        if(d.bridgeId && String(d.bridgeId) !== String(vcfg.id || cfg.id || '')) return;
        unlock({type:'parent:' + (d.event || 'interaction')});
      };
      document.addEventListener('click', unlock, true);
      document.addEventListener('pointerdown', unlock, true);
      document.addEventListener('touchstart', unlock, true);
      document.addEventListener('keydown', unlock, true);
      document.addEventListener('wheel', unlock, true);
      document.addEventListener('scroll', unlock, true);
      window.addEventListener('message', unlockFromParent, false);
    }
    video.addEventListener('loadedmetadata', function(){
      applyVideoAspect();
      applyConfiguredSpeed(false);
      if(!userStarted && showResumePanelIfNeeded()) { requestParentResize(true, 'resume'); return; }
      if(isSeparateTeaser()) applyBgStart(true);
      else if(!isTeaser()){
        if(!showResumePanelIfNeeded()) restorePosition();
      }
      requestParentResize(false, 'metadata');
    });
    video.addEventListener('canplay', function(){ applyVideoAspect(); applyConfiguredSpeed(false); if(isSeparateTeaser()){ applyBgStart(false); maintainTeaserWindow(); } requestParentResize(false, 'canplay'); });
    video.addEventListener('playing', function(){ if(isSeparateTeaser() && !teaserStartApplied) applyBgStart(true); });
    video.addEventListener('loadeddata', function(){ applyVideoAspect(); if(isSeparateTeaser()) applyBgStart(false); requestParentResize(false, 'loadeddata'); });
    video.addEventListener('play', function(){
      applyConfiguredSpeed(false);
      if(userStarted) hideOverlay();
      if(!userStarted && vcfg.smartAutoplay) return;
      if(hasPlayedOnce) send('vsl_resume','',false);
      hasPlayedOnce = true;
      once('vsl_play');
      scheduleCta(); scheduleHook();
      if(pauseCard) pauseCard.hidden = true;
      updateCustomControls();
      requestParentResize(false, 'play');
    });
    video.addEventListener('pause', function(){
      lastPauseAt = Date.now();
      if(!userStarted || isTeaser() || video.ended) return;
      send('vsl_pause','',false);
      savePosition();
      var pauseStart = parseInt(vcfg.pauseStart || '0',10);
      var pauseEnd = parseInt(vcfg.pauseEnd || '0',10);
      var inWindow = video.currentTime >= pauseStart && (!pauseEnd || video.currentTime <= pauseEnd);
      var pauseTrigger = vcfg.pauseTrigger || 'pause';
      if(pauseCard && vcfg.pauseOn !== false && inWindow && (pauseTrigger === 'pause' || pauseTrigger === 'both')){
        pauseCard.classList.remove('is-final');
        pauseCard.hidden = false;
        once('vsl_pause_image_view');
      }
      updateCustomControls();
    });
    video.addEventListener('seeking', function(){ if(userStarted && !isTeaser()) send('vsl_resume','',false); });
    var lastPauseAt = 0;
    if(frame){
      frame.addEventListener('click', function(e){
        if(!vcfg.clickPause) return;
        if(Date.now() - lastUserStartAt < 850) return;
        if(e.target.closest('[data-itp-vsl-overlay], [data-itp-vsl-cta], [data-itp-vsl-pause-card], [data-itp-vsl-big-play], [data-itp-vsl-back10], [data-itp-vsl-forward10], a, button')) return;
        if(!userStarted || isTeaser()) return;
        var rect = frame.getBoundingClientRect();
        if(e.clientY && e.clientY > rect.bottom - 54) return;
        if(video.paused && Date.now() - lastPauseAt < 650) return;
        if(video.paused) video.play().catch(function(){}); else video.pause();
      });
    }
    if(pauseCard){
      pauseCard.addEventListener('click', function(e){
        if(e.target.closest('a')) return;
        pauseCard.hidden = true;
        userStarted = true;
        video.play().catch(function(){});
      });
    }
    var milestones = [25,50,75,100];
    var granularInterval = 0;
    var nextGranularAt = 0;
    function granularStep(duration){
      duration = Math.max(1, Math.round(duration || 0));
      if(duration <= 5) return 1;
      if(duration <= 30) return 2;
      if(duration <= 120) return 5;
      if(duration <= 600) return 10;
      if(duration <= 1200) return 15;
      return 30;
    }
    function trackGranularProgress(){
      if(!video || !video.duration || !isFinite(video.duration)) return;
      if(video.paused || video.seeking || !userStarted || isTeaser()) return;
      var duration = Math.max(1, Math.floor(video.duration));
      if(!granularInterval){
        granularInterval = granularStep(duration);
        nextGranularAt = granularInterval;
      }
      var t = Math.max(0, video.currentTime || 0);
      if(t + 0.35 < nextGranularAt) return;
      var guard = 0;
      while(nextGranularAt < duration && nextGranularAt <= t + 0.35 && guard < 3){
        once('vsl_progress_' + Math.round(nextGranularAt) + 's');
        nextGranularAt += granularInterval;
        guard++;
      }
      if(t - nextGranularAt > granularInterval * 2){
        nextGranularAt = (Math.floor(t / granularInterval) + 1) * granularInterval;
      }
    }
    video.addEventListener('timeupdate', function(){
      if(isTeaser()){
        if(isSeparateTeaser()){
          if(!teaserStartApplied) applyBgStart(false);
          maintainTeaserWindow();
        }
        return;
      }
      if(!userStarted || !video.duration || !isFinite(video.duration)) return;
      var pct = Math.max(0, Math.min(100, video.currentTime / video.duration * 100));
      milestones.forEach(function(m){ if(pct >= m) once('vsl_'+m); });
      trackGranularProgress();
      updateCustomControls();
      if(progress){
        var visual = pct;
        if((vcfg.progressType || 'smart') === 'smart') visual = Math.min(100, (1 - Math.exp(-pct/28)) * 100);
        progress.style.width = visual + '%';
      }
      var revealAt = ctaRevealAt();
      var ctaEnd = parseFloat(vcfg.ctaEnd || 0);
      if(cta && vcfg.ctaOn !== false){
        if(ctaSeenBefore()){
          showCta();
        } else if(video.currentTime >= revealAt && (!ctaEnd || video.currentTime <= ctaEnd)) showCta();
        else if(ctaEnd > 0 && video.currentTime > ctaEnd){ hideCta(); requestParentResize(true); }
        else if(video.currentTime < revealAt){ hideCta(); }
      }
      var hookStart = parseFloat(vcfg.hookStart || 0);
      var hookEnd = parseFloat(vcfg.hookEnd || 0);
      if(hook && vcfg.hookOn !== false){
        if(video.currentTime >= hookStart && (!hookEnd || video.currentTime <= hookEnd)) showHook();
        else hook.hidden = true;
      }
      if(Math.floor(video.currentTime) % 5 === 0){ savePosition(); }
    });
    video.addEventListener('volumechange', function(){ if(!video.muted && video.volume > 0) once('vsl_unmute'); });
    window.addEventListener('pagehide', function(){ savePosition(); });
    window.addEventListener('beforeunload', function(){ savePosition(); });
    document.addEventListener('visibilitychange', function(){ if(document.visibilityState === 'hidden') savePosition(); });
    setInterval(function(){ if(userStarted && !isTeaser()) savePosition(); }, 2000);
    video.addEventListener('ended', function(){
      once('vsl_100');
      if(progress) progress.style.width = '100%';
      updateCustomControls();
      clearResumePosition();
      var pauseTrigger = vcfg.pauseTrigger || 'pause';
      requestParentResize(false, 'ended');
      if(pauseCard && vcfg.pauseOn !== false && (pauseTrigger === 'end' || pauseTrigger === 'both')){
        pauseCard.classList.add('is-final');
        pauseCard.hidden = false;
        once('vsl_pause_image_view');
      }
    });
  }
  initVsl();

  saveLastTouch('');
  send('visit','',false);
  setTimeout(function(){
    var payload = basePayload('page_view', location.href);
    var res = runConversionRules('page_view', location.href, payload);
    dispatchPixelEvent('page_view', location.href, payload);
    if(res && res.internal) send('conversion', location.href, false);
  }, 80);
  setTimeout(function(){ if(!clicked) send('heartbeat','',false); }, 10000);
  window.addEventListener('pagehide', function(){ if(!clicked) send('heartbeat','',true); });

    /* v0.18.180 Smartplay public sticky diagnostics
       Enable with ?itp_diag=1. Fixed on viewport so it cannot be clipped by the player. */
    function itp180DiagEnabled(){
      try{ var h=String(window.location.search||'')+String(window.location.hash||''); if(/itp[_-]?diag=1|itpdiag|itp_diag/i.test(h)) return true; }catch(e){}
      try{ if(window.localStorage && localStorage.getItem('itp_vsl_diag')==='1') return true; }catch(e){}
      return false;
    }
    function itp180Rect(el){ if(!el) return 'missing'; var r=el.getBoundingClientRect(); return Math.round(r.width)+'x'+Math.round(r.height)+' @ '+Math.round(r.left)+','+Math.round(r.top); }
    function itp180Css(el,n){ try{return (getComputedStyle(el).getPropertyValue(n)||'').trim()||'-';}catch(e){return '-';} }
    function itp180SmartplayDiag(){
      if(!itp180DiagEnabled()) return;
      var box=document.getElementById('itp-vsl-diag-fixed-180');
      if(!box){ box=document.createElement('pre'); box.id='itp-vsl-diag-fixed-180'; box.style.cssText='position:fixed;left:8px;right:8px;bottom:8px;z-index:2147483647;max-height:44vh;overflow:auto;padding:8px 9px;border-radius:8px;background:rgba(2,6,23,.92);color:#67e8f9;font:11px/1.35 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap;text-align:left;pointer-events:none;box-shadow:0 8px 24px rgba(0,0,0,.35);'; document.documentElement.appendChild(box); }
      var ov=overlay;
      var inner=ov?((ov.classList&&ov.classList.contains('itp-sp180')?ov.querySelector(':scope > .itp-smartplay-inner'):null)||ov.querySelector('.itp-smartplay-public-canvas > .itp-smartplay-inner')||ov.querySelector(':scope > .itp-smartplay-inner')):null;
      var visual=inner?inner.querySelector('svg,.itp-smartplay-final-svg,img.itp-vsl-custom-overlay-image'):null;
      var css=getComputedStyle(inner||ov||document.body);
      var lines=[];
      lines.push('ITP PUBLIC SMARTPLAY DIAG 0.18.224');
      lines.push('viewport: '+window.innerWidth+'x'+window.innerHeight+' max640='+(window.matchMedia?window.matchMedia('(max-width:640px)').matches:'-'));
      lines.push('wrap:   '+itp180Rect(wrap));
      lines.push('frame:  '+itp180Rect(frame));
      lines.push('video:  '+itp180Rect(video));
      lines.push('overlay:'+itp180Rect(ov)+' hidden='+(ov?ov.hidden:'-'));
      lines.push('inner:  '+itp180Rect(inner));
      lines.push('visual: '+itp180Rect(visual));
      if(ov){ lines.push('ov class: '+ov.className); lines.push('ov vars x/y/w/r: '+itp180Css(ov,'--itp-vsl-x')+' / '+itp180Css(ov,'--itp-vsl-y')+' / '+itp180Css(ov,'--itp-vsl-w')+' / '+itp180Css(ov,'--itp-vsl-r')); }
      if(inner){ lines.push('inner data x/y/w/r: '+(inner.getAttribute('data-itp-sp-x')||'-')+' / '+(inner.getAttribute('data-itp-sp-y')||'-')+' / '+(inner.getAttribute('data-itp-sp-w')||'-')+' / '+(inner.getAttribute('data-itp-sp-r')||'-')); lines.push('inner css left/top/width/transform: '+css.left+' / '+css.top+' / '+css.width+' / '+css.transform); lines.push('inner inline: '+inner.getAttribute('style')); }
      box.textContent=lines.join('\n');
    }
    if(itp180DiagEnabled()){ setTimeout(itp180SmartplayDiag,120); setTimeout(itp180SmartplayDiag,700); setTimeout(itp180SmartplayDiag,1600); try{setInterval(itp180SmartplayDiag,1200);}catch(e){} }

})();


/* Invalid Traffic 0.18.188 - Resume/Thumb diagnostics for public/embed player */
(function(){
  'use strict';
  function enabled(){try{var s=String(location.search||'')+String(location.hash||'');return /itp[_-]?diag=1|itpdiag|itp_diag/i.test(s);}catch(e){}try{return localStorage.getItem('itp_vsl_diag')==='1';}catch(e){}return false;}
  if(!enabled()) return;
  function qs(s,c){return (c||document).querySelector(s);}
  function rect(el){if(!el)return 'missing';var r=el.getBoundingClientRect();return Math.round(r.width)+'x'+Math.round(r.height)+' @ '+Math.round(r.left)+','+Math.round(r.top);}
  function css(el,n){try{return (getComputedStyle(el).getPropertyValue(n)||'').trim()||'-';}catch(e){return '-';}}
  function box(){var p=document.getElementById('itp-vsl-public-stage-diag-182'); if(!p){p=document.createElement('pre');p.id='itp-vsl-public-stage-diag-182';p.style.cssText='position:fixed;right:8px;bottom:8px;z-index:2147483647;max-width:min(540px,92vw);max-height:48vh;overflow:auto;padding:9px 10px;border-radius:9px;background:rgba(2,6,23,.94);color:#fde68a;font:11px/1.35 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap;text-align:left;pointer-events:none;box-shadow:0 12px 34px rgba(0,0,0,.38);';document.documentElement.appendChild(p);}return p;}
  function update(){
    var wrap=qs('[data-itp-vsl-player]')||qs('.itp-vsl-player');
    var frame=wrap?qs('.itp-vsl-video-frame',wrap):qs('.itp-vsl-video-frame');
    var video=frame?qs('video',frame):null;
    var resume=frame?qs('[data-itp-vsl-resume-panel]',frame):null;
    var recovery=frame?qs('[data-itp-vsl-pause-card]',frame):null;
    var recImg=recovery?qs('img',recovery):null;
    var overlay=frame?qs('[data-itp-vsl-overlay]',frame):null;
    var lines=[];
    lines.push('ITP PUBLIC STAGE DIAG 0.18.224');
    lines.push('viewport: '+innerWidth+'x'+innerHeight);
    lines.push('wrap:    '+rect(wrap));
    lines.push('frame:   '+rect(frame));
    lines.push('video:   '+rect(video)+' intrinsic='+(video?(video.videoWidth+'x'+video.videoHeight):'-'));
    lines.push('frame class: '+(frame?frame.className:'-'));
    lines.push('wrap class: '+(wrap?wrap.className:'-'));
    lines.push('resume: '+rect(resume)+' hidden='+(resume?resume.hidden:'-')+' display='+(resume?css(resume,'display'):'-'));
    lines.push('recovery: '+rect(recovery)+' hidden='+(recovery?recovery.hidden:'-')+' display='+(recovery?css(recovery,'display'):'-'));
    lines.push('recovery img: '+rect(recImg)+' fit='+(recImg?css(recImg,'object-fit'):'-'));
    lines.push('smartplay: '+rect(overlay)+' hidden='+(overlay?overlay.hidden:'-'));
    box().textContent=lines.join('\n');
  }
  [120,600,1400,2400].forEach(function(ms){setTimeout(update,ms);});
  try{setInterval(update,1000);}catch(e){}
})();
