(function(){
  "use strict";
  function qs(s,c){return (c||document).querySelector(s)}
  function qsa(s,c){return Array.prototype.slice.call((c||document).querySelectorAll(s))}


  function itpNormalizeSpeed(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 itpFormatSpeed(value){
    var n = itpNormalizeSpeed(value);
    return (String(n).replace(/\.0+$/, '')) + '×';
  }
  function itpGetSelectedTurboSpeed(){
    var field = qs('select[name="vsl_speed"]');
    return itpNormalizeSpeed(field ? field.value : '1');
  }
  function itpApplyTurboSpeed(video, control){
    if(!video) return;
    var rate = itpGetSelectedTurboSpeed();
    try{ video.defaultPlaybackRate = rate; }catch(e){}
    try{ video.playbackRate = rate; }catch(e){}
    if(control) control.textContent = itpFormatSpeed(rate);
  }
  function itpFormatDuration(seconds){
    seconds = parseFloat(seconds || 0);
    if(!isFinite(seconds) || seconds <= 0) return 'detecting…';
    seconds = Math.floor(seconds);
    var h = Math.floor(seconds / 3600);
    var m = Math.floor((seconds % 3600) / 60);
    var s = seconds % 60;
    if(h > 0) return h + ':' + (m < 10 ? '0' : '') + m + ':' + (s < 10 ? '0' : '') + s;
    return m + ':' + (s < 10 ? '0' : '') + s;
  }
  var itpDurationProbeCache = {};
  var itpDetectedDurations = { main: 0, background: 0 };
  function itpProbeVideoDuration(url, cb){
    if(!url){ cb('optional', 0); return; }
    if(itpDurationProbeCache[url]){ cb(itpDurationProbeCache[url].text, itpDurationProbeCache[url].seconds); return; }
    var v = document.createElement('video');
    v.preload = 'metadata';
    v.muted = true;
    v.playsInline = true;
    v.style.position = 'absolute';
    v.style.left = '-9999px';
    v.style.width = '1px';
    v.style.height = '1px';
    v.style.opacity = '0';
    var done = false;
    function finish(text, seconds){
      if(done) return;
      done = true;
      seconds = parseFloat(seconds || 0);
      if(!isFinite(seconds) || seconds <= 0) seconds = 0;
      if(seconds > 0) text = itpFormatDuration(seconds);
      itpDurationProbeCache[url] = { text: text, seconds: seconds };
      cb(text, seconds);
      try{ v.removeAttribute('src'); v.load(); }catch(e){}
      try{ if(v.parentNode) v.parentNode.removeChild(v); }catch(e){}
    }
    function maybeFinish(){
      if(v.duration && isFinite(v.duration) && v.duration > 0) finish(itpFormatDuration(v.duration), v.duration);
    }
    ['loadedmetadata','durationchange','loadeddata','canplay'].forEach(function(evt){
      v.addEventListener(evt, maybeFinish, {once:false});
    });
    v.addEventListener('error', function(){ finish('unavailable', 0); }, {once:true});
    setTimeout(function(){ maybeFinish(); }, 900);
    setTimeout(function(){ maybeFinish(); }, 2400);
    setTimeout(function(){ finish('unavailable', 0); }, 8000);
    try{ document.body.appendChild(v); }catch(e){}
    v.src = url;
    try{ v.load(); }catch(e){}
  }
  function itpApplyTimeDurationLimits(source, seconds){
    seconds = parseFloat(seconds || 0);
    if(!isFinite(seconds) || seconds <= 0) return;
    var label = itpFormatDuration(seconds);
    qsa('[data-itp-time-source="'+source+'"]').forEach(function(input){
      var current = parseFloat(input.value || '0');
      var safeMax = Math.max(Math.ceil(seconds), isFinite(current) ? current : 0);
      input.setAttribute('max', String(safeMax));
      input.setAttribute('data-itp-detected-duration', String(Math.floor(seconds)));
      input.title = 'Detected '+source+' video duration: ' + label;
    });
    qsa('[data-itp-time-helper="'+source+'"]').forEach(function(el){
      if(source === 'main') el.textContent = 'Main video duration detected: ' + label + '. Use seconds on this timeline.';
      else el.textContent = 'Background duration detected: ' + label + '. The muted teaser will start/end inside this window.';
    });
  }
  function itpUpdateVslDurationBadges(mainUrl, previewUrl){
    var mainBadge = qs('[data-itp-duration-for="vsl_video_url"]');
    var previewBadge = qs('[data-itp-duration-for="vsl_preview_video_url"]');
    if(mainBadge){
      if(!mainUrl){
        mainBadge.textContent = 'Duration: no video selected';
        mainBadge.dataset.itpDurationUrl = '';
        itpDetectedDurations.main = 0;
      } else {
        if(mainBadge.dataset.itpDurationUrl !== mainUrl){
          mainBadge.dataset.itpDurationUrl = mainUrl;
          mainBadge.textContent = 'Duration: detecting…';
        }
        itpProbeVideoDuration(mainUrl, function(text, seconds){
          if(mainBadge.dataset.itpDurationUrl !== mainUrl) return;
          mainBadge.textContent = 'Duration: ' + text;
          itpDetectedDurations.main = seconds || 0;
          itpApplyTimeDurationLimits('main', seconds);
        });
      }
    }
    if(previewBadge){
      if(!previewUrl){
        previewBadge.textContent = 'Duration: optional';
        previewBadge.dataset.itpDurationUrl = '';
        itpDetectedDurations.background = 0;
      } else {
        if(previewBadge.dataset.itpDurationUrl !== previewUrl){
          previewBadge.dataset.itpDurationUrl = previewUrl;
          previewBadge.textContent = 'Duration: detecting…';
        }
        itpProbeVideoDuration(previewUrl, function(text, seconds){
          if(previewBadge.dataset.itpDurationUrl !== previewUrl) return;
          previewBadge.textContent = 'Duration: ' + text;
          itpDetectedDurations.background = seconds || 0;
          itpApplyTimeDurationLimits('background', seconds);
        });
      }
    }
  }
  function itpSecondsField(name){
    var field = qs('[name="'+name+'"]');
    var n = field ? parseFloat(field.value || '0') : 0;
    return isFinite(n) && n > 0 ? n : 0;
  }
  function itpPreviewBackgroundActive(video){
    if(!video) return false;
    var bgInput = qs('input[name="vsl_preview_video_url"]');
    var bg = bgInput ? (bgInput.value || '') : '';
    if(!bg) return false;
    var src = video.currentSrc || (video.querySelector('source') ? (video.querySelector('source').getAttribute('src') || video.querySelector('source').src || '') : (video.src || ''));
    return !!(src && src.indexOf(bg) !== -1);
  }
  function itpApplyPreviewBackgroundWindow(video, force){
    if(!video || video.dataset.itpPreviewStarted === '1' || !itpPreviewBackgroundActive(video)) return;
    var start = itpSecondsField('vsl_bg_start');
    var end = itpSecondsField('vsl_bg_end');
    if(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(force && video.readyState >= 1){
      try{ if(start > 0 || Math.abs((video.currentTime||0) - start) > 0.35) video.currentTime = start; }catch(e){}
    }
    if(end > start && video.currentTime >= Math.max(start + 0.25, end - 0.05)){
      try{ video.currentTime = start; video.play().catch(function(){}); }catch(e){}
    }
  }

  function syncLabelSelect(sel){
    var input = sel.parentNode ? sel.parentNode.querySelector('input.itp-custom-label-input, input[name$="_label"], input[name$="[button]"]') : null;
    if(!input) return;
    if(sel.value === 'custom'){
      input.style.display = '';
      input.disabled = false;
      input.classList.add('is-custom-open');
    } else {
      input.value = sel.value;
      input.style.display = 'none';
      input.disabled = false;
      input.classList.remove('is-custom-open');
    }
  }

  function initLabelSelects(root){
    qsa('[data-itp-label-select], [data-itp-card-preset]', root || document).forEach(function(sel){
      var input = sel.parentNode ? sel.parentNode.querySelector('input.itp-custom-label-input, input[name$="_label"], input[name$="[button]"]') : null;
      if(input){
        var presetFound = false;
        qsa('option', sel).forEach(function(opt){ if(opt.value === input.value || opt.textContent === input.value){ presetFound = true; sel.value = opt.value; } });
        if(!presetFound && input.value){ sel.value = 'custom'; }
      }
      syncLabelSelect(sel);
    });
  }

  function setSectionDisabled(box, disabled){
    qsa('input, textarea, select, button[data-itp-add-card]', box).forEach(function(el){
      if(el.closest('.itp-sticky-save')) return;
      if(el.matches('input[name="template"]')) return;
      if(el.matches('[data-itp-media], [data-itp-remove-card], [data-itp-add-card], [data-itp-clear-card-image], [data-itp-clear-field]')) return;
      el.disabled = !!disabled;
    });
  }

  function isCardStyleValue(value){
  return ['blue_cards','news_cards','link_hub','offer_grid','review_clean','segment_choice'].indexOf(value) !== -1;
}

function syncTemplateOptions(){
  var selected = qs('input[name="template"]:checked');
  var value = selected ? selected.value : '';

  qsa('[data-itp-template-options]').forEach(function(box){
    var values = [box.getAttribute('data-itp-template-options') || ''];
    var also = box.getAttribute('data-itp-template-options-also') || '';
    also.split(',').forEach(function(x){ if(x.trim()) values.push(x.trim()); });
    var show = values.indexOf(value) !== -1;
    box.classList.toggle('itp-template-options-hidden', !show);
    setSectionDisabled(box, !show);
  });

  qsa('[data-itp-hide-on-template]').forEach(function(box){
    var hiddenFor = (box.getAttribute('data-itp-hide-on-template') || '').split(',').map(function(x){return x.trim();});
    var hide = hiddenFor.indexOf(value) !== -1;
    box.classList.toggle('itp-template-options-hidden', hide);
    setSectionDisabled(box, hide);
  });

}

  function openMediaFor(input, type){
    if(!input) return;
    if(!window.wp || !wp.media){
      alert('WordPress media library is not available on this screen.');
      return;
    }
    type = type || 'image';
    var frame = wp.media({
      title: type === 'video' ? 'Select video' : 'Select image',
      button: { text: type === 'video' ? 'Use this video' : 'Use this image' },
      multiple: false,
      library: { type: type }
    });
    frame.on('select', function(){
      var attachment = frame.state().get('selection').first().toJSON();
      if(attachment && attachment.url){
        input.value = attachment.url;
        input.dispatchEvent(new Event('input', {bubbles:true}));
        input.dispatchEvent(new Event('change', {bubbles:true}));
        if(input.name === 'vsl_overlay_image'){
          var sel = document.querySelector('[data-itp-overlay-template-select], select[name="vsl_overlay_template"]');
          if(sel){
            sel.value = 'custom';
            sel.dispatchEvent(new Event('input', {bubbles:true}));
            sel.dispatchEvent(new Event('change', {bubbles:true}));
          }
          setTimeout(function(){
            if(typeof syncAdminVslPreview === 'function') syncAdminVslPreview();
          }, 30);
        }
      }
    });
    frame.open();
  }

  function sendReorder(list){
    if(!window.ITP_ADMIN) return;
    var ids = qsa('[data-id]', list).map(function(row){ return row.getAttribute('data-id'); }).filter(Boolean);
    var fd = new FormData();
    fd.append('action','itp_reorder_bridges');
    fd.append('nonce',ITP_ADMIN.nonce);
    ids.forEach(function(id){ fd.append('ids[]', id); });
    fetch(ITP_ADMIN.ajax,{method:'POST',body:fd,credentials:'same-origin'}).catch(function(){});
  }

  function initReorder(){
    var list = qs('[data-itp-presell-list]');
    if(!list) return;
    var dragged = null;
    qsa('.itp-presell-row', list).forEach(function(row){
      var handle = qs('.itp-drag', row);
      if(!handle) return;
      handle.title = 'Drag to reorder';
      handle.addEventListener('mousedown', function(){ row.setAttribute('draggable','true'); });
      row.addEventListener('dragstart', function(e){
        dragged = row;
        row.classList.add('is-dragging');
        e.dataTransfer.effectAllowed = 'move';
      });
      row.addEventListener('dragend', function(){
        row.classList.remove('is-dragging');
        row.removeAttribute('draggable');
        sendReorder(list);
      });
    });
    list.addEventListener('dragover', function(e){
      if(!dragged) return;
      e.preventDefault();
      var after = qsa('.itp-presell-row:not(.is-dragging)', list).reduce(function(closest, child){
        var box = child.getBoundingClientRect();
        var offset = e.clientY - box.top - box.height / 2;
        if(offset < 0 && offset > closest.offset) return {offset: offset, element: child};
        return closest;
      }, {offset: Number.NEGATIVE_INFINITY}).element;
      if(after == null) list.appendChild(dragged); else list.insertBefore(dragged, after);
    });
  }

  document.addEventListener('DOMContentLoaded',function(){
    qsa('.itp-template').forEach(function(label){
      label.addEventListener('click',function(){
        qsa('.itp-template').forEach(function(x){x.classList.remove('selected')});
        label.classList.add('selected');
        var input=qs('input[type=radio]',label); if(input) input.checked=true;
        syncTemplateOptions();
      });
    });

    var slugInputs=qsa('input[name="slug"]');
    if(slugInputs.length){
      var normalizeSlug=function(value){
        return (value||'').toLowerCase().trim().replace(/[^a-z0-9\-]+/g,'-').replace(/^-+|-+$/g,'') || 'your-slug';
      };
      var updateSlugPreview=function(inp){
        var value = inp ? inp.value : '';
        var s = normalizeSlug(value);
        var ctx = inp ? (inp.closest('[data-itp-vsl-panel], [data-itp-cookie-studio], [data-itp-card-studio], .itp-card') || document) : document;
        qsa('[data-itp-final-url]', ctx).forEach(function(f){
          if(!f.dataset.itpBaseUrl){ f.dataset.itpBaseUrl = f.textContent.replace(/[^\/]+\/?$/,''); }
          f.textContent = f.dataset.itpBaseUrl + s + '/';
        });
      };
      slugInputs.forEach(function(inp){
        updateSlugPreview(inp);
        inp.addEventListener('input',function(){ updateSlugPreview(inp); });
      });
    }

    var landingSlugInput = qs('input[name="elementor_landing_slug"]');
    var landingUrlPreview = qs('[data-itp-landing-final-url]');
    if(landingSlugInput && landingUrlPreview){
      var normalizeLandingSlug=function(value){
        return (value||'').toLowerCase().trim().replace(/[^a-z0-9\-]+/g,'-').replace(/^-+|-+$/g,'') || 'your-landing';
      };
      var updateLandingUrlPreview=function(){
        var base = landingUrlPreview.getAttribute('data-itp-landing-base-url') || landingUrlPreview.textContent.replace(/[^\/]+\/?$/,'');
        if(base.slice(-1) !== '/') base += '/';
        landingUrlPreview.textContent = base + normalizeLandingSlug(landingSlugInput.value) + '/';
      };
      updateLandingUrlPreview();
      landingSlugInput.addEventListener('input', updateLandingUrlPreview);
      landingSlugInput.addEventListener('change', updateLandingUrlPreview);
    }

    var search=qs('.itp-search');
    if(search){
      search.addEventListener('input',function(){
        var v=search.value.toLowerCase();
        qsa('.itp-presell-row').forEach(function(row){ row.style.display=(row.getAttribute('data-search')||'').indexOf(v)>-1?'grid':'none'; });
      });
    }

    initLabelSelects(document);
    syncTemplateOptions();
    initElementorLandingTemplateSafety();
    document.addEventListener('change',function(e){
  if(e.target.matches('[data-itp-label-select], [data-itp-card-preset]')) {
    syncLabelSelect(e.target);
    if(typeof syncBridgePreview === 'function') syncBridgePreview();
  }
});


    function initElementorLandingTemplateSafety(){
      var sel = qs('[data-itp-elementor-template-select]');
      if(!sel) return;
      var mode = qs('[data-itp-landing-mode]');
      var modal = qs('[data-itp-landing-template-modal]');
      var status = qs('[data-itp-landing-choice-status]');
      var hasLanding = sel.getAttribute('data-itp-has-landing') === '1';
      var current = sel.getAttribute('data-itp-current-template') || sel.value || '';
      var pendingValue = '';
      var landingSlugField = qs('input[name="elementor_landing_slug"]');
      var initialLandingSlug = landingSlugField ? (landingSlugField.value || '') : '';
      var landingPageIdInput = qs('input[name="elementor_landing_page_id"]');
      var originalLandingPageId = landingPageIdInput ? landingPageIdInput.value : '';
      var pendingPill = qs('[data-itp-pending-landing]');
      var pendingPillPath = qs('[data-itp-pending-landing-path]');
      var pendingPillTemplate = qs('[data-itp-pending-landing-template]');
      var submitAfterModal = false;

      function normalizeLandingSlugValue(value){
        return (value||'').toLowerCase().trim().replace(/[^a-z0-9\-]+/g,'-').replace(/^-+|-+$/g,'') || 'landing';
      }
      function suggestNextLandingSlug(value){
        var slug = normalizeLandingSlugValue(value || 'landing');
        var m = slug.match(/^(.*?)(?:-?(\d+))?$/);
        if(!m) return slug + '-2';
        var base = (m[1] || slug).replace(/-+$/,'') || slug;
        var n = m[2] ? (parseInt(m[2],10) + 1) : 2;
        return base + '-' + n;
      }
      function selectedLabel(){
        var opt = sel.options[sel.selectedIndex];
        return opt ? (opt.textContent || opt.value || '').trim() : (sel.value || 'selected template');
      }
      function currentLandingPreviewUrl(){
        var preview = qs('[data-itp-landing-final-url]');
        var base = preview ? (preview.getAttribute('data-itp-landing-base-url') || '') : '';
        if(!base) base = window.location.origin + '/';
        if(base.slice(-1) !== '/') base += '/';
        var slug = normalizeLandingSlugValue(landingSlugField ? landingSlugField.value : 'landing');
        return base + slug + '/';
      }
      function refreshPendingLandingPill(show){
        if(!pendingPill) return;
        var isNew = !!(mode && mode.value === 'copy');
        pendingPill.hidden = !(show && isNew);
        if(show && isNew && pendingPillPath){
          pendingPillPath.textContent = '/' + normalizeLandingSlugValue(landingSlugField ? landingSlugField.value : 'landing') + '/';
        }
        if(show && isNew && pendingPillTemplate){
          pendingPillTemplate.textContent = selectedLabel();
        }
      }
      function setStatus(html, cls){
        if(!status) return;
        status.hidden = false;
        status.className = 'itp-landing-choice-status ' + (cls || '');
        status.innerHTML = html;
      }
      function clearStatus(){
        if(status){ status.hidden = true; status.textContent = ''; status.className = 'itp-landing-choice-status'; }
        refreshPendingLandingPill(false);
      }
      function showReadyStatus(){
        if(!hasLanding) return;
        var label = selectedLabel();
        var url = currentLandingPreviewUrl();
        setStatus('<strong>Ready:</strong> use <em>+ New landing page</em> to create <em>'+label+'</em> at <code>'+url+'</code>. Existing landing pages stay connected.', 'is-copy');
      }
      function setCopyMode(suggestSlug){
        if(!mode) return;
        mode.value = 'copy';
        if(landingPageIdInput) landingPageIdInput.value = '0';
        if(suggestSlug && landingSlugField){
          var now = normalizeLandingSlugValue(landingSlugField.value);
          var initial = normalizeLandingSlugValue(initialLandingSlug);
          if(!landingSlugField.value || (hasLanding && now === initial)){
            landingSlugField.value = suggestNextLandingSlug(landingSlugField.value || initial || 'landing');
            landingSlugField.dispatchEvent(new Event('input', {bubbles:true}));
            landingSlugField.dispatchEvent(new Event('change', {bubbles:true}));
          }
        }
        pendingValue = '';
        var label = selectedLabel();
        var url = currentLandingPreviewUrl();
        setStatus('<strong>Creating:</strong> saving now to create <em>'+label+'</em> at <code>'+url+'</code> and connect this same VSL to it.', 'is-copy');
        refreshPendingLandingPill(true);
      }
      function showModal(){
        if(!modal) return;
        modal.hidden = false;
        modal.classList.add('is-open');
        document.body.classList.add('itp-landing-modal-open');
        var first = qs('[data-itp-landing-action]', modal);
        if(first) setTimeout(function(){ try{ first.focus(); }catch(e){} }, 40);
      }
      function hideModal(){
        if(!modal) return;
        modal.classList.remove('is-open');
        modal.hidden = true;
        document.body.classList.remove('itp-landing-modal-open');
      }
      function cancelChange(){
        if(pendingValue && current){
          sel.value = current;
          sel.dispatchEvent(new Event('input', {bubbles:true}));
        }
        pendingValue = '';
        submitAfterModal = false;
        if(mode) mode.value = hasLanding ? 'keep' : 'create';
        if(landingPageIdInput && originalLandingPageId) landingPageIdInput.value = originalLandingPageId;
        clearStatus();
        hideModal();
      }

      sel.addEventListener('change', function(){
        if(!mode) return;
        if(!hasLanding){ mode.value = 'create'; return; }
        var next = sel.value || '';
        if(mode.value === 'copy'){
          refreshPendingLandingPill(true);
          return;
        }
        if(!next || next === current){
          mode.value = 'keep';
          pendingValue = '';
          clearStatus();
          return;
        }
        // Do not interrupt the user with a modal while they are selecting a template.
        // If they click + New landing page, it creates a new page. If they click Save, the safety modal appears.
        pendingValue = next;
        mode.value = 'keep';
        showReadyStatus();
      });

      qsa('[data-itp-add-landing-page]').forEach(function(btn){
        btn.addEventListener('click', function(e){
          e.preventDefault();
          var form = sel.closest('form');
          setCopyMode(true);
          btn.disabled = true;
          btn.classList.add('is-saving');
          if(form){
            if(typeof form.requestSubmit === 'function') form.requestSubmit();
            else form.submit();
          }
        });
      });
      if(landingSlugField){
        landingSlugField.addEventListener('input', function(){
          if(mode && mode.value === 'copy') refreshPendingLandingPill(true);
          else if(pendingValue) showReadyStatus();
        });
        landingSlugField.addEventListener('change', function(){
          if(mode && mode.value === 'copy') refreshPendingLandingPill(true);
          else if(pendingValue) showReadyStatus();
        });
      }
      qsa('[data-itp-landing-action]', modal || document).forEach(function(btn){
        btn.addEventListener('click', function(e){
          e.preventDefault();
          var action = btn.getAttribute('data-itp-landing-action') || 'keep';
          if(action !== 'regenerate') action = 'keep';
          if(mode) mode.value = action;
          if(action === 'regenerate' && landingPageIdInput && originalLandingPageId) landingPageIdInput.value = originalLandingPageId;
          current = sel.value || pendingValue || current;
          sel.setAttribute('data-itp-current-template', current);
          pendingValue = '';
          if(action === 'regenerate'){
            setStatus('<strong>Saving:</strong> regenerating the current Elementor page with <em>'+selectedLabel()+'</em>.', 'is-regenerate');
          } else {
            clearStatus();
          }
          hideModal();
          if(submitAfterModal){
            submitAfterModal = false;
            var form = sel.closest('form');
            if(form){ setTimeout(function(){ if(typeof form.requestSubmit === 'function') form.requestSubmit(); else form.submit(); }, 30); }
          }
        });
      });
      qsa('[data-itp-landing-cancel]', modal || document).forEach(function(btn){
        btn.addEventListener('click', function(e){ e.preventDefault(); cancelChange(); });
      });
      if(modal){
        modal.addEventListener('click', function(e){ if(e.target === modal) cancelChange(); });
        document.addEventListener('keydown', function(e){ if(e.key === 'Escape' && !modal.hidden) cancelChange(); });
      }
      var form = sel.closest('form');
      refreshPendingLandingPill(false);
      if(form){
        form.addEventListener('submit', function(e){
          if(hasLanding && pendingValue && (!mode || mode.value === 'keep')){
            e.preventDefault();
            submitAfterModal = true;
            showModal();
          }
        });
      }
    }

    // VSL desktop/mobile preview toggle
    qsa('[data-itp-vsl-device]').forEach(function(btn){
      btn.addEventListener('click', function(){
        qsa('[data-itp-vsl-device]').forEach(function(x){ x.classList.remove('active'); });
        btn.classList.add('active');
        var box = qs('[data-itp-admin-vsl-preview]');
        if(box){
          box.classList.toggle('is-mobile-preview', btn.getAttribute('data-itp-vsl-device') === 'mobile');
        }
        if(typeof syncAdminVslPreview === 'function'){ requestAnimationFrame(function(){ syncAdminVslPreview(); }); }
      });
    });

    document.addEventListener('click',function(e){
      var clearBtn = e.target.closest('[data-itp-clear-field]');
      if(clearBtn){
        e.preventDefault();
        var clearName = clearBtn.getAttribute('data-itp-clear-field');
        var clearInput = clearName ? qs('[name="'+clearName+'"]') : null;
        if(clearInput){
          clearInput.value = '';
          clearInput.dispatchEvent(new Event('input', {bubbles:true}));
          clearInput.dispatchEvent(new Event('change', {bubbles:true}));
        }
        if(typeof syncBridgeDesignUI === 'function') syncBridgeDesignUI();
        if(typeof syncBridgePreview === 'function') syncBridgePreview();
        if(typeof syncCookiePreview === 'function') syncCookiePreview();
        return;
      }
      var mediaBtn = e.target.closest('[data-itp-media]');
      if(mediaBtn){
        e.preventDefault();
        var row = mediaBtn.closest('.logo-row') || mediaBtn.parentNode;
        var input = row ? row.querySelector('input') : null;
        openMediaFor(input, mediaBtn.getAttribute('data-itp-media-type') || 'image');
        return;
      }
      var clearCardImage = e.target.closest('[data-itp-clear-card-image]');
      if(clearCardImage){
        e.preventDefault();
        var imageRow = clearCardImage.closest('[data-itp-card-row]');
        var imageInput = imageRow ? qs('[name$="[image]"]', imageRow) : null;
        if(imageInput){
          imageInput.value = '';
          imageInput.dispatchEvent(new Event('input', {bubbles:true}));
          imageInput.dispatchEvent(new Event('change', {bubbles:true}));
        }
        if(typeof syncBridgePreview === 'function') syncBridgePreview();
        return;
      }
      var rem=e.target.closest('[data-itp-remove-card]');
      if(rem){
        e.preventDefault();
        var cardRow=rem.closest('[data-itp-card-row]');
        if(cardRow) cardRow.remove();
        if(typeof syncBridgePreview === 'function') syncBridgePreview();
      }
    });

    var editor=qs('[data-itp-cards-editor]');
    var add=qs('[data-itp-add-card]');
    if(editor && add){
      add.addEventListener('click',function(){
        var idx=qsa('[data-itp-card-row]',editor).length;
        var div=document.createElement('div');
        div.className='itp-card-row'; div.setAttribute('data-itp-card-row','1');
        div.innerHTML='<div class="itp-form-grid two"><label>Card title<input name="cards['+idx+'][title]" placeholder="Ex: Continue to article"></label><label>Card destination URL<input name="cards['+idx+'][url]" placeholder="https://example.com/final-page"></label></div><div class="itp-form-grid two"><label>Card short text<input name="cards['+idx+'][text]" placeholder="Short supporting text."></label><label>Button label<select data-itp-card-preset><option>Continue</option><option selected>Read more</option><option>Learn more</option><option>See details</option><option>View offer</option><option>Compare options</option><option>Start now</option><option>Get access</option><option>Open page</option><option>Shop now</option><option value="custom">Custom</option></select><input class="itp-custom-label-input" name="cards['+idx+'][button]" value="Read more" placeholder="Write custom label"></label></div><div class="itp-form-grid logo-row itp-card-image-row"><label>Card image URL optional<input name="cards['+idx+'][image]" placeholder="https://.../image.jpg"></label><button type="button" class="itp-btn itp-btn-ghost" data-itp-media="card">Media</button><button type="button" class="itp-btn itp-btn-light" data-itp-clear-card-image>Clear image</button></div><p class="itp-field-help">Recommended: 1200×675 (16:9). The image is cropped to fit the card.</p><div class="itp-card-row-actions"><button type="button" class="itp-btn itp-btn-light" data-itp-remove-card>Remove card</button></div>';
        editor.appendChild(div);
        initLabelSelects(div);
        if(typeof syncBridgePreview === 'function') syncBridgePreview();
      });
    }

    var fill=qs('[data-itp-fill-demo]');
    if(fill){
      fill.addEventListener('click',function(){
        var map={
          'title':'Sample Bridge','slug':'sample-bridge','category':'Paid Traffic','headline':'Choose where to continue','short_copy':'Select the product, guide or offer that matches what you came to see.','top_cta_url':'https://example.com/final-page','top_cta_label':'Continue','secondary_cta_url':'https://example.com/options','secondary_cta_label':'Compare options','footer_note':'Choose one option to continue.','cookie_title':'Cookie Policy','cookie_copy':'This page uses cookies to personalize content, analyze visits and improve your experience. By clicking Accept, you agree to continue.','cookie_accept_label':'Accept','cookie_close_label':'Close','cookie_policy_label':'Privacy Policy','cookie_accept_url':'','cookie_close_url':'','cookie_policy_url':''
        };
        Object.keys(map).forEach(function(k){ var el=qs('[name="'+k+'"]'); if(el){ el.value=map[k]; el.dispatchEvent(new Event('input',{bubbles:true})); } });
        var editor=qs('[data-itp-cards-editor]');
        var addBtn=qs('[data-itp-add-card]');
        while(editor && addBtn && qsa('[data-itp-card-row]', editor).length < 3){ addBtn.click(); }
        var logo=(qs('.itp-logo-image')||{}).src || '';
        var sampleCards=[
          {title:'Product 1', text:'Short product copy with one clear benefit and a simple reason to continue.', button:'View product', url:'https://example.com/product-1', image:logo},
          {title:'Product 2', text:'Second destination preview for an offer, article, guide or comparison page.', button:'See details', url:'https://example.com/product-2', image:logo},
          {title:'Product 3', text:'Third sample card so the bridge opens with a complete premium-looking preview.', button:'Continue', url:'https://example.com/product-3', image:logo}
        ];
        qsa('[data-itp-card-row]', editor || document).forEach(function(row, idx){
          var data=sampleCards[idx];
          if(!data) return;
          [['title',data.title],['text',data.text],['button',data.button],['url',data.url],['image',data.image]].forEach(function(pair){
            var el=qs('[name$="['+pair[0]+']"]', row);
            if(el){ el.value=pair[1]; el.dispatchEvent(new Event('input',{bubbles:true})); el.dispatchEvent(new Event('change',{bubbles:true})); }
          });
        });
        initLabelSelects(document);
        if(typeof syncBridgeDesignUI === 'function') syncBridgeDesignUI();
        if(typeof syncBridgePreview === 'function') syncBridgePreview();
        if(typeof syncCookiePreview === 'function') syncCookiePreview();
      });
    }

    qsa('[data-itp-validate-inline]').forEach(function(btn){
      btn.addEventListener('click',function(){
        var host=qs('[data-itp-modal-host]') || document.body;
        var fd=new FormData(); fd.append('action','itp_validate_bridge'); fd.append('nonce',ITP_ADMIN.nonce); fd.append('id',btn.getAttribute('data-itp-validate-inline'));
        fetch(ITP_ADMIN.ajax,{method:'POST',body:fd,credentials:'same-origin'}).then(function(r){return r.json()}).then(function(j){ if(j.success){ host.innerHTML=j.data.html; } });
      });
    });


    document.addEventListener('click',function(e){
      var copy=e.target.closest('[data-itp-copy-url]');
      if(copy){
        e.preventDefault();
        var url=copy.getAttribute('data-itp-copy-url') || '';
        var done=function(){ var old=copy.textContent; copy.textContent='Copied'; setTimeout(function(){ copy.textContent=old; },1200); };
        if(navigator.clipboard && navigator.clipboard.writeText){ navigator.clipboard.writeText(url).then(done).catch(function(){ window.prompt('Copy campaign URL', url); }); }
        else { window.prompt('Copy campaign URL', url); }
      }
    });



    qsa('[data-itp-vsl-tab]').forEach(function(btn){
      btn.addEventListener('click', function(){
        var studio = btn.closest('[data-itp-vsl-studio]');
        if(!studio) return;
        var target = btn.getAttribute('data-itp-vsl-tab');
        studio.setAttribute('data-active-vsl-tab', target);
        var activeField = document.querySelector('[data-itp-active-vsl-tab-field]');
        if(activeField) activeField.value = target;
        try{ localStorage.setItem('itp_vsl_active_tab', target); }catch(e){}
        if(target !== 'autoplay'){
          studio.setAttribute('data-overlay-design-active','0');
          var posToggle = qs('[data-itp-overlay-position-toggle]', studio);
          if(posToggle){ posToggle.classList.remove('active'); posToggle.textContent = 'Edit overlay position'; }
        }
        qsa('[data-itp-vsl-tab]', studio).forEach(function(x){ x.classList.toggle('active', x === btn); });
        qsa('[data-itp-vsl-panel]', studio).forEach(function(panel){ panel.classList.toggle('active', panel.getAttribute('data-itp-vsl-panel') === target); });
        if(target === 'autoplay'){
          restoreSmartAutoplayPreview(studio);
        }
      });
    });
    qsa('[data-itp-vsl-studio]').forEach(function(studio){
      var active = qs('[data-itp-vsl-tab].active', studio);
      studio.setAttribute('data-active-vsl-tab', active ? active.getAttribute('data-itp-vsl-tab') : 'video');
    });

    qsa('[data-itp-vsl-studio]').forEach(function(studio){
      try{
        var params = new URLSearchParams(window.location.search || '');
        var desired = params.get('itp_tab') || localStorage.getItem('itp_vsl_active_tab') || '';
        if(desired){
          var btn = qs('[data-itp-vsl-tab="'+desired+'"]', studio);
          if(btn && !btn.classList.contains('active')) btn.click();
        }
      }catch(e){}
      var activeField = document.querySelector('[data-itp-active-vsl-tab-field]');
      var active = qs('[data-itp-vsl-tab].active', studio);
      if(activeField && active) activeField.value = active.getAttribute('data-itp-vsl-tab') || 'video';
    });


    function valNum(name, fallback){
      var el = qs('[name="'+name+'"]');
      var n = el ? parseFloat(el.value) : NaN;
      return isFinite(n) ? n : fallback;
    }
    function setVal(name, value){
      var el = qs('[name="'+name+'"]');
      if(!el) return;
      var v = String(Math.round(value * 10) / 10);
      if(el.value !== v){
        el.value = v;
        if(!window.__itpSmartplayTemplateBatch){ el.dispatchEvent(new Event('input', {bubbles:true})); }
      }
    }
    function isVslMobilePreview(){
      var box = qs('[data-itp-admin-vsl-preview]') || qs('[data-itp-preview-video-box]');
      return !!(box && box.classList && box.classList.contains('is-mobile-preview'));
    }
    function designFieldName(key, prop){
      // v0.18.127: Smart Autoplay uses one coordinate set.
      // Mobile preview changes the video stage size/ratio only; it no longer writes separate overlay positions.
      return 'vsl_' + key + '_' + prop;
    }
    function valDesign(key, prop, fallback){ return valNum(designFieldName(key, prop), fallback); }
    function setDesign(key, prop, value){
      setVal(designFieldName(key, prop), value);
      if(key === 'overlay'){
        var mirror = prop === 'width' ? 'vsl_overlay_mobile_width' : (prop === 'rotate' ? 'vsl_overlay_mobile_rotate' : 'vsl_overlay_mobile_' + prop);
        setVal(mirror, value);
      }
    }
    function applyDesignTo(el, key){
      if(!el) return;
      var x = valDesign(key, 'x', key === 'hook' ? 4 : 50);
      var y = valDesign(key, 'y', key === 'cta' ? 82 : (key === 'hook' ? 82 : 50));
      var w = valDesign(key, 'width', key === 'overlay' ? 30 : (key === 'hook' ? 32 : 34));
      var r = valDesign(key, 'rotate', 0);
      el.style.setProperty('--itp-design-x', x + '%');
      el.style.setProperty('--itp-design-y', y + '%');
      el.style.setProperty('--itp-design-w', w + '%');
      el.style.setProperty('--itp-design-r', r + 'deg');

      // v0.18.86: reliable proportional scaling fallback.
      // Some admin contexts were not resolving cqi consistently, so every template
      // also receives a real pixel unit based on the current video stage width.
      if(key === 'overlay'){
        var stage = qs('[data-itp-preview-video-box]');
        var stageW = stage ? (stage.clientWidth || stage.getBoundingClientRect().width || 0) : 0;
        var overlayW = Math.max(1, stageW * w / 100);
        el.style.setProperty('--itp-ow', overlayW + 'px');
        el.style.setProperty('--itp-u', (overlayW / 100) + 'px');
      }
    }
    function currentVslDesignTab(){
      var studio = qs('[data-itp-vsl-studio]');
      return studio ? (studio.getAttribute('data-active-vsl-tab') || 'video') : 'video';
    }
    function overlayTemplateDefaultWidth(value){
      value = value || 'wide';
      var box = qs('[data-itp-admin-vsl-preview]') || qs('[data-itp-preview-video-box]');
      var isMobile = !!(box && box.classList && box.classList.contains('is-mobile-preview'));
      // Invalid Traffic-like defaults: the selected object starts as a designed block inside the real video stage.
      // Users can then scale it with the handles; text/icon follow via container units.
      if(value === 'large') value = 'full';
      if(value === 'full') return 100;
      // Start closer to the reference editor: a compact object that users can scale up.
      if(value === 'wide') return 42;
      if(value === 'square') return 40;
      if(value === 'play') return 40;
      if(value === 'compact') return 52;
      if(value === 'icon_sound') return 24;
      if(value === 'icon_play') return 24;
      if(value === 'icon_blink') return 24;
      if(value === 'custom') return isMobile ? 56 : 34;
      return isMobile ? 64 : 58;
    }

    function restoreSmartAutoplayPreview(studio){
      studio = studio || qs('[data-itp-vsl-studio]');
      if(!studio) return;
      var overlay = qs('[data-itp-preview-overlay]', studio) || qs('[data-itp-preview-overlay]');
      var video = qs('[data-itp-preview-video]', studio) || qs('[data-itp-preview-video]');
      if(video){
        video.dataset.itpPreviewStarted = '0';
        try{ video.muted = true; video.loop = true; }catch(e){}
      }
      if(overlay){ overlay.classList.remove('is-consumed'); overlay.removeAttribute('aria-hidden'); overlay.hidden = false; overlay.style.removeProperty('display'); }
      setTimeout(function(){ if(typeof syncAdminVslPreview === 'function') syncAdminVslPreview(); }, 20);
    }
    function designableTabFor(key){
      if(key === 'overlay') return 'autoplay';
      if(key === 'hook') return 'hook';
      if(key === 'cta') return 'cta';
      return '';
    }
    function makeDesignable(el, key){
      if(!el) return;
      if(el.__itpDesignable && el.querySelector('.itp-design-resize-handle')) return;
      el.__itpDesignable = true;
      el.setAttribute('data-itp-design-ready','1');
      var handles = ['nw','n','ne','e','se','s','sw','w','rot'];
      var resizeHandles = [];
      handles.forEach(function(pos){
        var h = document.createElement('i');
        h.className = 'itp-design-handle itp-design-handle-' + pos + (pos === 'se' ? ' itp-design-resize-handle' : '');
        h.setAttribute('aria-hidden','true');
        h.setAttribute('data-itp-design-handle', pos);
        el.appendChild(h);
        if(pos !== 'rot') resizeHandles.push(h);
      });
      var handle = el.querySelector('.itp-design-resize-handle');
      var box = qs('[data-itp-preview-video-box]');
      var start = null;
      function ensureSnapGuides(){
        if(!box) return null;
        var v = box.querySelector('.itp-vsl-snap-guide-v');
        var h = box.querySelector('.itp-vsl-snap-guide-h');
        if(!v){ v = document.createElement('span'); v.className = 'itp-vsl-snap-guide itp-vsl-snap-guide-v'; box.appendChild(v); }
        if(!h){ h = document.createElement('span'); h.className = 'itp-vsl-snap-guide itp-vsl-snap-guide-h'; box.appendChild(h); }
        return {v:v,h:h};
      }
      function setSnapGuide(axis, on){
        var g = ensureSnapGuides();
        if(!g) return;
        if(axis === 'x') g.v.classList.toggle('active', !!on);
        if(axis === 'y') g.h.classList.toggle('active', !!on);
      }
      function hideSnapGuides(){
        var g = ensureSnapGuides();
        if(!g) return;
        g.v.classList.remove('active'); g.h.classList.remove('active');
      }
      function begin(e, mode){
        if(el.hidden) return;
        if(currentVslDesignTab() !== designableTabFor(key)) return;
        var studioForDesign = qs('[data-itp-vsl-studio]');
        if(key === 'overlay' && (!studioForDesign || studioForDesign.getAttribute('data-overlay-design-active') !== '1')) return;
        if(key === 'hook' && (!studioForDesign || studioForDesign.getAttribute('data-hook-design-active') !== '1')) return;
        if(e.button !== undefined && e.button !== 0) return;
        e.preventDefault(); e.stopPropagation();
        box = qs('[data-itp-preview-video-box]');
        if(!box) return;
        var r = box.getBoundingClientRect();
        var er = el.getBoundingClientRect();
        var cx = er.left + er.width / 2;
        var cy = er.top + er.height / 2;
        var startDist = Math.max(8, Math.hypot(e.clientX - cx, e.clientY - cy));
        var startAngle = Math.atan2(e.clientY - cy, e.clientX - cx) * 180 / Math.PI;
        start = {mode:mode, handle:(e.target && e.target.getAttribute ? e.target.getAttribute('data-itp-design-handle') : '') || 'se', sx:e.clientX, sy:e.clientY, bw:r.width, bh:r.height, x:valDesign(key,'x',50), y:valDesign(key,'y',50), w:valDesign(key,'width',30), r:valDesign(key,'rotate',0), ew:er.width, cx:cx, cy:cy, startDist:startDist, startAngle:startAngle};
        document.addEventListener('pointermove', move, true);
        document.addEventListener('pointerup', end, true);
      }
      function move(e){
        if(!start) return;
        var dx = e.clientX - start.sx, dy = e.clientY - start.sy;
        if(String(start.mode || '').indexOf('resize') === 0){
          var currentDist = Math.max(8, Math.hypot(e.clientX - start.cx, e.clientY - start.cy));
          var ratio = currentDist / Math.max(8, start.startDist);
          var nw = start.w * ratio;
          setDesign(key, 'width', Math.max(8, Math.min(500, nw))); // v0.18.149: keep preview and final renderer size in sync
        } else if(start.mode === 'rotate') {
          var angle = Math.atan2(e.clientY - start.cy, e.clientX - start.cx) * 180 / Math.PI;
          var nr = start.r + (angle - start.startAngle);
          setDesign(key, 'rotate', Math.max(-360, Math.min(360, nr)));
        } else {
          var nx = Math.max(0, Math.min(100, start.x + dx / start.bw * 100));
          var ny = Math.max(0, Math.min(100, start.y + dy / start.bh * 100));
          if(Math.abs(nx - 50) <= 1.35){ nx = 50; setSnapGuide('x', true); } else { setSnapGuide('x', false); }
          if(Math.abs(ny - 50) <= 1.35){ ny = 50; setSnapGuide('y', true); } else { setSnapGuide('y', false); }
          setDesign(key, 'x', nx);
          setDesign(key, 'y', ny);
        }
        applyDesignTo(el, key);
      }
      function end(){
        start = null;
        hideSnapGuides();
        document.removeEventListener('pointermove', move, true);
        document.removeEventListener('pointerup', end, true);
      }
      el.addEventListener('pointerdown', function(e){
        if(e.target && e.target.classList && e.target.classList.contains('itp-design-handle')) return;
        begin(e,'drag');
      });
      resizeHandles.forEach(function(h){ h.addEventListener('pointerdown', function(e){ begin(e,'resize'); }); });
      var rotateHandle = el.querySelector('.itp-design-handle-rot');
      if(rotateHandle){ rotateHandle.addEventListener('pointerdown', function(e){ begin(e,'rotate'); }); }
    }
    function initDesignables(){
      [['overlay','[data-itp-preview-overlay]'], ['hook','[data-itp-preview-hook]'], ['cta','[data-itp-preview-cta]']].forEach(function(pair){
        var el = qs(pair[1]);
        if(el){ makeDesignable(el, pair[0]); applyDesignTo(el, pair[0]); }
      });
    }
    function enhanceRange(name, min, max, step){
      var input = qs('[name="'+name+'"]');
      if(!input || input.__itpRangeEnhanced || input.type === 'range') return;
      input.__itpRangeEnhanced = true;
      var range = document.createElement('input');
      range.type = 'range'; range.min = min; range.max = max; range.step = step || 1; range.value = input.value || min;
      range.className = 'itp-vsl-range';
      input.classList.add('itp-vsl-range-number');
      input.parentNode.insertBefore(range, input);
      function syncFromRange(){ input.value = range.value; input.dispatchEvent(new Event('input', {bubbles:true})); }
      function syncFromInput(){ range.value = input.value || min; }
      range.addEventListener('input', syncFromRange);
      input.addEventListener('input', syncFromInput);
    }

    function itpRestartAnimation(el){
      if(!el) return;
      el.style.animation = 'none';
      void el.offsetWidth;
      el.style.animation = '';
      if(el.querySelectorAll){
        el.querySelectorAll('.itp-vsl-wave, .itp-vsl-volume-icon, .itp-vsl-sound-animated, .itp-vsl-pulse-ring, .itp-vsl-wave-svg').forEach(function(node){
          node.style.animation = 'none';
          void node.offsetWidth;
          node.style.animation = '';
        });
      }
    }


    function itpEnsureOverlayPulseRing(overlay, key){
      if(!overlay) return null;
      var existing = overlay.querySelector(':scope > .itp-vsl-pulse-ring');
      if(existing && existing.getAttribute('data-itp-pulse-key') === key){
        return existing;
      }
      if(existing) existing.remove();
      var ring = document.createElement('span');
      ring.className = 'itp-vsl-pulse-ring';
      ring.setAttribute('aria-hidden','true');
      ring.setAttribute('data-itp-pulse-key', key || 'pulse');
      overlay.insertBefore(ring, overlay.firstChild);
      return ring;
    }

    function itpForceOverlayPulseAnimation(overlay){
      if(!overlay) return;
      var ring = overlay.querySelector(':scope > .itp-vsl-pulse-ring');
      if(!ring) return;
      ring.style.animation = 'none';
      void ring.offsetWidth;
      ring.style.animation = '';
      ring.style.webkitAnimation = 'none';
      void ring.offsetWidth;
      ring.style.webkitAnimation = '';
    }

    function itpRemoveOverlayPulseRing(overlay){
      if(!overlay) return;
      overlay.querySelectorAll(':scope > .itp-vsl-pulse-ring').forEach(function(ring){ ring.remove(); });
    }

    function enhanceVslControls(){
      enhanceRange('vsl_cta_font_size',10,48,1);
      enhanceRange('vsl_cta_radius',0,999,1);
      enhanceRange('vsl_cta_padding_y',4,60,1);
      enhanceRange('vsl_cta_padding_x',8,120,1);
      enhanceRange('vsl_hook_opacity',10,100,1);
      enhanceRange('vsl_overlay_pulse_speed',0.6,3,0.05);
      enhanceRange('vsl_cta_pulse_speed',0.6,3,0.05);
      qsa('.itp-media-pick-row').forEach(function(row){
        if(row.querySelector('[data-itp-clear-media]')) return;
        var input = row.querySelector('input.itp-media-url');
        if(!input) return;
        var btn = document.createElement('button');
        btn.type = 'button';
        btn.className = 'itp-btn itp-btn-light itp-clear-media-btn';
        btn.setAttribute('data-itp-clear-media','1');
        btn.textContent = 'Clear';
        row.appendChild(btn);
      });
      initDesignables();
      if(typeof initVslPreviewPlayback === "function") initVslPreviewPlayback();
    }
    function itpCtaFontStack(name){
      var map = {
        'system':'system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif',
        'Inter':'Inter,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif',
        'Poppins':'Poppins,Inter,system-ui,sans-serif',
        'Montserrat':'Montserrat,Inter,system-ui,sans-serif',
        'Roboto':'Roboto,Arial,system-ui,sans-serif',
        'Open Sans':'"Open Sans",Arial,system-ui,sans-serif',
        'Oswald':'Oswald,Impact,"Arial Narrow",sans-serif',
        'Bebas Neue':'"Bebas Neue",Impact,"Arial Narrow",sans-serif',
        'Arial':'Arial,Helvetica,sans-serif'
      };
      return map[name || 'Inter'] || map.Inter;
    }
    function itpEnsureCtaWoff2Font(url){
      return itpEnsurePreviewWoff2Font('cta', url, 'CTA');
    }
    function itpEnsurePreviewWoff2Font(slot, url, label){
      slot = String(slot || 'text').replace(/[^a-z0-9_-]/gi,'').toLowerCase() || 'text';
      label = label || slot;
      var id='itp-vsl-admin-' + slot + '-woff2-font';
      var st=document.getElementById(id);
      if(!url){ if(st) st.remove(); return ''; }
      if(!st){ st=document.createElement('style'); st.id=id; document.head.appendChild(st); }
      var family='ITP VSL ' + label + ' Preview';
      st.textContent='@font-face{font-family:"'+family+'";src:url("'+String(url).replace(/"/g,'%22')+'") format("woff2");font-weight:100 1000;font-style:normal;font-display:swap;}';
      return '"'+family+'",Inter,system-ui,sans-serif';
    }
    function itpPreviewFont(slot, fontField, woff2Field, label){
      var forced = itpEnsurePreviewWoff2Font(slot, (woff2Field && woff2Field.value) ? woff2Field.value : '', label);
      return forced || itpCtaFontStack(fontField ? fontField.value : 'Inter');
    }
    function syncAdminVslPreview(){
      var headline = qs('input[name="vsl_headline"]');
      var smartOn = qs('input[name="vsl_smart_autoplay"]');
      var ctaOn = qs('input[name="vsl_cta_on"]');
      var progressOn = qs('input[name="vsl_progress_on"]');
      var cta = qs('input[name="vsl_cta_text"]');
      var ctaAction = qs('[data-itp-cta-action]');
      var leadTitle = qs('input[name="vsl_lead_title"]');
      var leadCopy = qs('textarea[name="vsl_lead_copy"]');
      var leadEmailPlaceholder = qs('input[name="vsl_lead_email_placeholder"]');
      var leadNameOn = qs('input[name="vsl_lead_name_on"]');
      var leadPhoneOn = qs('input[name="vsl_lead_phone_on"]');
      var leadNamePlaceholder = qs('input[name="vsl_lead_name_placeholder"]');
      var leadPhonePlaceholder = qs('input[name="vsl_lead_phone_placeholder"]');
      var leadButtonText = qs('input[name="vsl_lead_button_text"]');
      var leadBg = qs('input[name="vsl_lead_bg"]');
      var leadBgImage = qs('input[name="vsl_lead_bg_image"]');
      var leadTitleColor = qs('input[name="vsl_lead_title_color"]');
      var leadTextColor = qs('input[name="vsl_lead_text_color"]');
      var leadButtonBg = qs('input[name="vsl_lead_button_bg"]');
      var leadButtonTextColor = qs('input[name="vsl_lead_button_text_color"]');
      var leadCloseColor = qs('input[name="vsl_lead_close_color"]');
      var leadCloseBg = qs('input[name="vsl_lead_close_bg"]');
      var leadRadius = qs('input[name="vsl_lead_radius"]');
      var leadCloseStyle = qs('select[name="vsl_lead_close_style"]');
      var ctaImage = qs('input[name="vsl_cta_image"]');
      var ctaPosition = qs('select[name="vsl_cta_position"]');
      var ctaColor = qs('input[name="vsl_cta_color"]');
      var ctaTextColor = qs('input[name="vsl_cta_text_color"]');
      var ctaSize = qs('input[name="vsl_cta_font_size"]');
      var ctaWeight = qs('select[name="vsl_cta_weight"]');
      var ctaFont = qs('select[name="vsl_cta_font"]');
      var ctaFontWoff2 = qs('input[name="vsl_cta_font_woff2"]');
      var ctaAnimation = qs('select[name="vsl_cta_animation"]');
      var ctaRadius = qs('input[name="vsl_cta_radius"]');
      var ctaPy = qs('input[name="vsl_cta_padding_y"]');
      var ctaPx = qs('input[name="vsl_cta_padding_x"]');
      var ctaPulse = qs('input[name="vsl_cta_pulse"]');
      var ctaPulseSpeed = qs('input[name="vsl_cta_pulse_speed"]');
      var ctaShadow = qs('input[name="vsl_cta_shadow"]');
      var progressColor = qs('input[name="vsl_progress_color"]');
      var progressUseCta = qs('input[name="vsl_progress_use_cta_color"]');
      var progressColorField = qs('[data-itp-progress-color-field]');
      var progressHeightOutput = qs('[data-itp-progress-height-output]');
      var progressHeight = qs('input[name="vsl_progress_height"]');
      var ctrlColor = qs('input[name="vsl_ctrl_color"]');
      var ctrlBg = qs('input[name="vsl_ctrl_bg"]');
      var overlayColor = qs('input[name="vsl_overlay_color"]');
      var overlayOpacity = qs('input[name="vsl_overlay_opacity"]');
      var overlayOpacityOutput = qs('[data-itp-overlay-opacity-output]');
      var overlayTextColor = qs('input[name="vsl_overlay_text_color"]');
      var overlayFont = qs('select[name="vsl_overlay_font"]');
      var overlayFontWoff2 = qs('input[name="vsl_overlay_font_woff2"]');
      var overlayTemplate = qs('select[name="vsl_overlay_template"]');
      var overlayImage = qs('input[name="vsl_overlay_image"]');
      var overlayPulse = qs('input[name="vsl_overlay_pulse"]');
      var overlayPulseSpeed = qs('input[name="vsl_overlay_pulse_speed"]');
      var overlayPulseMode = qs('select[name="vsl_overlay_pulse_mode"]');
      var overlayTop = qs('input[name="vsl_overlay_top"]');
      var overlayBottom = qs('input[name="vsl_overlay_bottom"]');
      var videoUrl = qs('input[name="vsl_video_url"]');
      var previewUrl = qs('input[name="vsl_preview_video_url"]');
      var posterUrl = qs('input[name="vsl_poster_url"]');
      var hookText = qs('input[name="vsl_hook_text"]');
      var hookFont = qs('select[name="vsl_hook_font"]');
      var hookFontWoff2 = qs('input[name="vsl_hook_font_woff2"]');
      var hookImage = qs('input[name="vsl_hook_image"]');
      var resumeFont = qs('select[name="vsl_resume_font"]');
      var resumeFontWoff2 = qs('input[name="vsl_resume_font_woff2"]');
      var pauseFont = qs('select[name="vsl_pause_font"]');
      var pauseFontWoff2 = qs('input[name="vsl_pause_font_woff2"]');
      var hookOn = qs('input[name="vsl_hook_on"]');
      var hookPosition = qs('select[name="vsl_hook_position"]');
      var hookOpacity = qs('input[name="vsl_hook_opacity"]');
      var ctrlBigPlay = qs('input[name="vsl_ctrl_big_play"]');
      var ctrlSmallPlay = qs('input[name="vsl_ctrl_small_play"]');
      var ctrlTime = qs('input[name="vsl_ctrl_time"]');
      var ctrlBack10 = qs('input[name="vsl_ctrl_back10"]');
      var ctrlForward10 = qs('input[name="vsl_ctrl_forward10"]');
      var ctrlVolume = qs('input[name="vsl_ctrl_volume"]');
      var ctrlFullscreen = qs('input[name="vsl_ctrl_fullscreen"]');
      var ctrlSpeed = qs('input[name="vsl_ctrl_speed"]');
      var turboSpeed = qs('select[name="vsl_speed"]');
      var b = qs('.itp-vsl-preview-cta');
      var progressWrap = qs('[data-itp-preview-progress]');
      var pbar = qs('.itp-vsl-preview-progress i');
      var overlay = qs('[data-itp-preview-overlay]');
      var overlayTopEl = qs('[data-itp-preview-overlay-top]');
      var overlayBottomEl = qs('[data-itp-preview-overlay-bottom]');
      var video = qs('[data-itp-preview-video]');
      var videoBox = qs('[data-itp-preview-video-box]');
      var empty = qs('[data-itp-preview-empty]');
      var hook = qs('[data-itp-preview-hook]');
      var previewControls = qs('[data-itp-preview-controls]');
      var previewWasStarted = !!(video && video.dataset.itpPreviewStarted === '1');
      var previewWasPaused = !!(video && video.paused);
      var previewWasMuted = !!(video && video.muted);
      var previewTime = video ? (video.currentTime || 0) : 0;
      var previewIsTeaser = !previewWasStarted && !!(smartOn && smartOn.checked);
      if(videoBox){
        videoBox.style.setProperty('--itp-vsl-preview-bg', '#050816');
        var effectiveProgressColor = (progressUseCta && progressUseCta.checked && ctrlBg && ctrlBg.value) ? ctrlBg.value : ((progressColor && progressColor.value) ? progressColor.value : '#ff5a1f');
        videoBox.style.setProperty('--itp-vsl-preview-accent', effectiveProgressColor);
        videoBox.style.setProperty('--itp-vsl-control-color', (ctrlColor && ctrlColor.value) ? ctrlColor.value : '#ffffff');
        videoBox.style.setProperty('--itp-vsl-control-bg', (ctrlBg && ctrlBg.value) ? ctrlBg.value : '#111827');
      }

      function itpSmartplayIconKey(template){
        template = template === 'large' ? 'full' : (template || 'wide');
        if(template === 'play' || template === 'icon_play') return 'play';
        if(template === 'compact' || template === 'icon_blink') return 'blink';
        return 'sound';
      }
      function itpUpdatePreviewTemplateIcon(overlay, template){
        if(!overlay) return;
        var img = overlay.querySelector('[data-itp-template-icon]');
        if(!img) return;
        var key = itpSmartplayIconKey(template);
        var base = (window.ITP_ADMIN && window.ITP_ADMIN.assetsUrl) ? window.ITP_ADMIN.assetsUrl : '';
        if(!base){
          var currentSrc = img.getAttribute('src') || '';
          base = currentSrc.replace(/invalid-traffic-smartplay-(sound|blink|play)\.svg(?:\?.*)?$/i, '');
        }
        img.src = base + 'invalid-traffic-smartplay-' + key + '.svg';
        img.className = 'itp-vsl-itbrand-icon itp-vsl-itbrand-icon-' + key;
        img.setAttribute('aria-hidden','true');
        img.alt = '';
        img.style.removeProperty('display');
        img.style.removeProperty('visibility');
        img.style.removeProperty('opacity');
      }
      var ctrlMap = {
        back10: ctrlBack10,
        small_play: ctrlSmallPlay,
        forward10: ctrlForward10,
        time: ctrlTime,
        volume: ctrlVolume,
        speed: ctrlSpeed,
        fullscreen: ctrlFullscreen
      };
      var anyCtrl = false;
      if(previewControls){
        Object.keys(ctrlMap).forEach(function(key){
          var el = qs('[data-preview-control="'+key+'"]', previewControls);
          var input = ctrlMap[key];
          var show = !previewIsTeaser && !!(input && input.checked);
          if(el) el.hidden = !show;
          if(show && el) anyCtrl = true;
        });
        previewControls.hidden = previewIsTeaser || !anyCtrl;
      }
      [['back10', ctrlBack10], ['forward10', ctrlForward10]].forEach(function(pair){
        var el = qs('[data-preview-control="'+pair[0]+'"]', videoBox || document);
        var input = pair[1];
        if(el) el.hidden = previewIsTeaser || !(input && input.checked);
      });
      var previewBig = qs('[data-preview-control="big_play"]', videoBox || document);
      if(previewBig){
        var pv = qs('[data-itp-preview-video]', videoBox || document);
        var started = pv && pv.dataset.itpPreviewStarted === '1';
        previewBig.hidden = !(ctrlBigPlay && ctrlBigPlay.checked && started && pv && pv.paused && !(overlay && !overlay.hidden));
      }
      if(overlay && smartOn){
        var studioForOverlay = overlay.closest('[data-itp-vsl-studio]') || qs('[data-itp-vsl-studio]');
        var designEditingOverlay = !!(studioForOverlay && studioForOverlay.getAttribute('data-overlay-design-active') === '1' && currentVslDesignTab() === 'autoplay');
        overlay.hidden = designEditingOverlay ? !smartOn.checked : (previewWasStarted ? true : !smartOn.checked);
        if(overlay.hidden){
          overlay.classList.add('is-consumed');
          overlay.setAttribute('aria-hidden','true');
          overlay.style.setProperty('display','none','important');
        } else {
          overlay.classList.remove('is-consumed');
          overlay.removeAttribute('aria-hidden');
          overlay.style.removeProperty('display');
        }
      }
      if(progressWrap && progressOn) progressWrap.hidden = previewIsTeaser || !progressOn.checked;
      if(b && ctaOn){
        var ctaDelayInput = qs('input[name="vsl_cta_delay"]');
        var pitchInput = qs('input[name="vsl_pitch_time"]');
        var ctaEndInput = qs('input[name="vsl_cta_end"]');
        var ctaDelayVal = parseFloat((ctaDelayInput && ctaDelayInput.value) || 0) || 0;
        var pitchVal = parseFloat((pitchInput && pitchInput.value) || 0) || 0;
        var ctaRevealVal = ctaDelayVal > 0 ? ctaDelayVal : pitchVal;
        var ctaEndVal = parseFloat((ctaEndInput && ctaEndInput.value) || 0) || 0;
        var ctaWindowOpen = previewWasStarted && !previewIsTeaser && previewTime >= ctaRevealVal && (!ctaEndVal || previewTime <= ctaEndVal);
        b.hidden = !ctaOn.checked || !ctaWindowOpen;
      }
      if(b){
        var img = b.querySelector('img');
        if(ctaImage && ctaImage.value){
          if(!img){ img = document.createElement('img'); b.innerHTML = ''; b.appendChild(img); }
          img.src = ctaImage.value;
          img.alt = cta ? (cta.value || '') : '';
          b.classList.add('has-image');
        } else {
          b.classList.remove('has-image');
          b.textContent = cta ? (cta.value || 'Continue') : 'Continue';
        }
      }
      if(b && ctaColor) b.style.background = ctaColor.value || '#16a34a';
      if(b && ctaTextColor) b.style.color = ctaTextColor.value || '#ffffff';
      if(b && ctaSize) b.style.fontSize = (ctaSize.value || 16) + 'px';
      if(b && ctaWeight) b.style.fontWeight = ctaWeight.value || '900';
      if(b){
        var forcedFont = itpEnsureCtaWoff2Font((ctaFontWoff2 && ctaFontWoff2.value) ? ctaFontWoff2.value : '');
        b.style.fontFamily = forcedFont || itpCtaFontStack(ctaFont ? ctaFont.value : 'Inter');
      }
      if(b && ctaRadius) b.style.borderRadius = (ctaRadius.value || 999) + 'px';
      if(b && ctaPy && ctaPx) b.style.padding = (ctaPy.value || 14) + 'px ' + (ctaPx.value || 28) + 'px';
      if(b && ctaPulse) b.classList.toggle('pulse', !!ctaPulse.checked);
      if(b){
        ['premium','heartbeat','breathe','bounce','flash','shake'].forEach(function(k){ b.classList.remove('effect-' + k); });
        if(ctaPulse && ctaPulse.checked){ b.classList.add('effect-' + ((ctaAnimation && ctaAnimation.value) ? ctaAnimation.value : 'premium')); }
      }
      if(b && ctaShadow) b.classList.toggle('shadow', !!ctaShadow.checked);
      qsa('[data-itp-cta-pulse-settings]').forEach(function(el){ el.hidden = !(ctaPulse && ctaPulse.checked); });
      qsa('[data-itp-cta-lead-settings]').forEach(function(el){ el.hidden = !(ctaAction && (ctaAction.value === 'lead' || ctaAction.value === 'lead_redirect')); });
      qsa('[data-itp-output-for="vsl_lead_radius"]').forEach(function(el){ if(leadRadius) el.textContent = leadRadius.value || '24'; });
      var leadPreview = qs('[data-itp-lead-preview] .itp-lead-preview-box');
      if(leadPreview){
        leadPreview.style.setProperty('--itp-lead-bg', (leadBg && leadBg.value) ? leadBg.value : '#050816');
        leadPreview.style.setProperty('--itp-lead-title', (leadTitleColor && leadTitleColor.value) ? leadTitleColor.value : '#ffffff');
        leadPreview.style.setProperty('--itp-lead-text', (leadTextColor && leadTextColor.value) ? leadTextColor.value : '#ffffff');
        leadPreview.style.setProperty('--itp-lead-btn', (leadButtonBg && leadButtonBg.value) ? leadButtonBg.value : '#16c653');
        leadPreview.style.setProperty('--itp-lead-btn-text', (leadButtonTextColor && leadButtonTextColor.value) ? leadButtonTextColor.value : '#02120a');
        leadPreview.style.setProperty('--itp-lead-close', (leadCloseColor && leadCloseColor.value) ? leadCloseColor.value : '#ffffff');
        leadPreview.style.setProperty('--itp-lead-close-bg', (leadCloseBg && leadCloseBg.value) ? leadCloseBg.value : '#060b14');
        leadPreview.style.setProperty('--itp-lead-radius', ((leadRadius && leadRadius.value) ? leadRadius.value : '24') + 'px');
        leadPreview.style.setProperty('--itp-lead-bg-image', 'url(' + ((leadBgImage && leadBgImage.value) ? leadBgImage.value : '') + ')');
        leadPreview.classList.toggle('close-plain', !!(leadCloseStyle && leadCloseStyle.value === 'plain'));
        leadPreview.classList.toggle('close-round', !(leadCloseStyle && leadCloseStyle.value === 'plain'));
        var h4 = leadPreview.querySelector('h4'); if(h4 && leadTitle) h4.textContent = leadTitle.value || 'Get the next step by email';
        var p = leadPreview.querySelector('p'); if(p && leadCopy) p.textContent = leadCopy.value || 'Enter your email below to continue.';
        var emailInp = leadPreview.querySelector('.itp-lead-preview-email'); if(emailInp && leadEmailPlaceholder) emailInp.placeholder = leadEmailPlaceholder.value || 'you@example.com';
        var nameInp = leadPreview.querySelector('.itp-lead-preview-name'); if(nameInp){ nameInp.hidden = !(leadNameOn && leadNameOn.checked); if(leadNamePlaceholder) nameInp.placeholder = leadNamePlaceholder.value || 'Full name'; }
        var phoneInp = leadPreview.querySelector('.itp-lead-preview-phone'); if(phoneInp){ phoneInp.hidden = !(leadPhoneOn && leadPhoneOn.checked); if(leadPhonePlaceholder) phoneInp.placeholder = leadPhonePlaceholder.value || 'Phone number'; }
        var btn = leadPreview.querySelector('strong'); if(btn && leadButtonText) btn.textContent = (leadButtonText.value || 'Continue by email').toUpperCase();
      }
      if(b){ b.style.setProperty('--itp-cta-pulse-duration', ((ctaPulseSpeed && ctaPulseSpeed.value) ? ctaPulseSpeed.value : '1.45') + 's'); if(b.classList && b.classList.contains('pulse')) itpRestartAnimation(b); }
      if(b && ctaPosition){ b.classList.toggle('is-inside-preview', ctaPosition.value === 'inside'); }
      var effectiveProgressColor2 = (progressUseCta && progressUseCta.checked && ctrlBg && ctrlBg.value) ? ctrlBg.value : ((progressColor && progressColor.value) ? progressColor.value : '#ff5a1f');
      if(progressColorField) progressColorField.hidden = !!(progressUseCta && progressUseCta.checked);
      if(pbar) pbar.style.background = effectiveProgressColor2;
      if(progressWrap && progressHeight){
        var ph = progressHeight.value || '6';
        progressWrap.style.height = ph + 'px';
        progressWrap.style.setProperty('--itp-preview-progress-height', ph + 'px');
        var previewVideoBox = qs('[data-itp-preview-video-box]');
        if(previewVideoBox) previewVideoBox.style.setProperty('--itp-vsl-progress-h', ph + 'px');
      }
      if(progressHeightOutput && progressHeight) progressHeightOutput.textContent = progressHeight.value || '6';
      if(overlay && overlayColor){
        var obg = overlayColor.value || '#111827';
        overlay.style.setProperty('--itp-overlay-bg', obg);
        overlay.style.setProperty('background-color', obg, 'important');
        overlay.style.setProperty('background', obg, 'important');
      }
      if(overlay && overlayOpacity){
        var op = Math.max(20, Math.min(100, parseInt(overlayOpacity.value || '92', 10)));
        overlay.style.setProperty('--itp-overlay-opacity', (op/100).toString());
        overlay.style.setProperty('--itp-overlay-opacity-pct', op + '%');
        if(overlayOpacityOutput) overlayOpacityOutput.textContent = String(op);
      }
      if(overlay && overlayTextColor){
        var ofg = overlayTextColor.value || '#ffffff';
        overlay.style.setProperty('--itp-overlay-fg', ofg);
        overlay.style.setProperty('color', ofg, 'important');
      }
      if(overlay){
        var overlayFontStack = itpPreviewFont('overlay', overlayFont, overlayFontWoff2, 'Overlay');
        overlay.style.fontFamily = overlayFontStack;
        overlay.style.setProperty('--itp-overlay-font', overlayFontStack);
      }
      if(overlay && overlayTemplate){
        ['template-wide','template-square','template-play','template-minimal','template-large','template-full','template-compact','template-icon_sound','template-icon_play','template-icon_blink','template-custom'].forEach(function(c){overlay.classList.remove(c);});
        overlay.classList.add('template-' + (overlayTemplate.value || 'wide'));
      }
      if(overlay && overlayTemplate && overlayImage){
        var hasCustomOverlayImage = overlayTemplate.value === 'custom' && !!overlayImage.value;
        overlay.classList.toggle('has-custom-image', hasCustomOverlayImage);
        overlay.classList.toggle('is-custom-image-only', hasCustomOverlayImage);
      }
      var overlayValue = overlayTemplate ? (overlayTemplate.value || 'wide') : 'wide';
      if(overlayValue === 'large'){ overlayValue = 'full'; if(overlayTemplate) overlayTemplate.value = 'full'; }
      if(typeof updateOverlayTemplateUI === 'function') updateOverlayTemplateUI();
      if(overlay){
        itpUpdatePreviewTemplateIcon(overlay, overlayValue);
      }
      setOverlayChooserMode(overlayValue);
      qsa('[data-itp-autoplay-bg]').forEach(function(el){ el.hidden = overlayValue === 'custom' && overlayImage && overlayImage.value; });
      qsa('[data-itp-count-for]').forEach(function(out){ var name = out.getAttribute('data-itp-count-for'); var field = qs('[name="'+name+'"]'); if(field) out.textContent = String((field.value || '').length); });
      var overlayAllowsPulse = overlayValue !== 'full' && overlayValue !== 'large';
      if(overlay && overlayPulse) overlay.classList.toggle('pulse', !!(overlayPulse.checked && overlayAllowsPulse));
      if(overlay) overlay.classList.toggle('pulse-disabled-template', !overlayAllowsPulse);
      qsa('[data-itp-overlay-pulse-settings]').forEach(function(el){ el.hidden = !(overlayPulse && overlayPulse.checked && overlayAllowsPulse); });
      if(overlay){
        overlay.classList.remove('pulse-scale','pulse-soft','pulse-glow','pulse-premium','pulse-heartbeat','pulse-breathe','pulse-bounce','pulse-flash','pulse-shake','effect-scale','effect-soft','effect-glow','effect-premium','effect-heartbeat','effect-breathe','effect-bounce','effect-flash','effect-shake');
        var pmode = overlayPulseMode ? (overlayPulseMode.value || 'scale') : 'scale';
        var opd = ((overlayPulseSpeed && overlayPulseSpeed.value) ? overlayPulseSpeed.value : '1.30');
        if(overlayPulse && overlayPulse.checked && overlayAllowsPulse){
          overlay.classList.add('pulse-' + pmode); overlay.classList.add('effect-' + pmode);
          var pulseRing = itpEnsureOverlayPulseRing(overlay, [overlayValue, pmode, opd].join('|'));
          overlay.style.setProperty('--itp-overlay-pulse-duration', opd + 's');
          overlay.style.setProperty('--itp-icon-blink-duration', Math.max(0.4, parseFloat(opd || '1.30') * 1.35) + 's');
          if(pulseRing){
            pulseRing.style.setProperty('animation-duration', opd + 's', 'important');
            requestAnimationFrame(function(){ itpForceOverlayPulseAnimation(overlay); });
          }
        } else {
          itpRemoveOverlayPulseRing(overlay);
          overlay.style.setProperty('--itp-overlay-pulse-duration', opd + 's');
          overlay.style.setProperty('--itp-icon-blink-duration', Math.max(0.4, parseFloat(opd || '1.30') * 1.35) + 's');
        }
      }
      if(overlayTopEl && overlayTop) overlayTopEl.textContent = overlayTop.value;
      if(overlayBottomEl && overlayBottom) overlayBottomEl.textContent = overlayBottom.value;
      if(overlay){
        var overlayImageHost = overlay.querySelector('.itp-smartplay-inner') || overlay;
        var oimg = overlayImageHost.querySelector(':scope > img.itp-vsl-custom-overlay-image');
        var overlayValueForImage = overlayTemplate ? (overlayTemplate.value || 'wide') : 'wide';
        if(overlayValueForImage === 'large') overlayValueForImage = 'full';
        if(overlayValueForImage === 'custom' && overlayImage && overlayImage.value){
          if(!oimg){
            oimg=document.createElement('img');
            oimg.className='itp-vsl-custom-overlay-image';
            overlayImageHost.insertBefore(oimg, overlayImageHost.firstChild);
          }
          oimg.src=overlayImage.value;
        }
        else if(oimg){ oimg.remove(); }
      }
      var mainSrcForPreview = videoUrl ? (videoUrl.value || '') : '';
      var teaserSrcForPreview = previewUrl ? (previewUrl.value || '') : '';
      var hasTeaserForPreview = !!teaserSrcForPreview;
      itpUpdateVslDurationBadges(mainSrcForPreview, teaserSrcForPreview);
      var nextSrc = previewWasStarted ? mainSrcForPreview : (hasTeaserForPreview ? teaserSrcForPreview : mainSrcForPreview);
      if(videoBox && !video){
        video = document.createElement('video');
        video.setAttribute('data-itp-preview-video','1');
        video.muted = true; video.autoplay = true; video.loop = true; video.playsInline = true; video.preload = 'metadata';
        videoBox.insertBefore(video, videoBox.firstChild);
      }
      if(video){
        var source = video.querySelector('source');
        if(nextSrc){
          if(!source){ source = document.createElement('source'); source.type = 'video/mp4'; video.appendChild(source); }
          var sourceSrc = nextSrc;
          if(source.getAttribute('src') !== sourceSrc){
            source.setAttribute('src', sourceSrc);
            if(!previewWasStarted){ video.dataset.itpPreviewStarted = '0'; }
            try{ video.load(); }catch(e){}
            try{ if(window.itpVslApplyPreviewAspect) setTimeout(window.itpVslApplyPreviewAspect, 80); }catch(e){}
            if(previewWasStarted){
              video.loop = false;
              video.muted = previewWasMuted;
              var restoreMain = function(){
                try{ if(previewTime && isFinite(previewTime)) video.currentTime = previewTime; }catch(e){}
                if(!previewWasPaused) video.play().catch(function(){});
              };
              if(video.readyState >= 1) restoreMain(); else setTimeout(restoreMain, 250);
            } else {
              video.dataset.itpPreviewStarted = '0';
              video.muted = true;
              /* 0.18.86: pre-start preview is always a muted teaser.
                 If a separate background/teaser video exists, it loops inside its window.
                 If not, the main video itself loops muted behind the overlay until click. */
              video.loop = true;
              video.autoplay = true;
              video.muted = true;
              video.setAttribute('muted','muted');
              try{ video.play().catch(function(){}); }catch(e){}
              if(hasTeaserForPreview && itpPreviewBackgroundActive(video)){
                itpApplyPreviewBackgroundWindow(video, true);
              } else {
                var resetMainTeaser = function(){ try{ if(video.readyState >= 1 && (video.currentTime || 0) < 0.05) video.currentTime = 0; }catch(e){} };
                resetMainTeaser(); setTimeout(resetMainTeaser, 120);
              }
            }
          } else if(previewWasStarted){
            video.dataset.itpPreviewStarted = '1';
            video.loop = false;
            video.muted = previewWasMuted;
            if(previewWasPaused){ try{ video.pause(); }catch(e){} } else { try{ video.play().catch(function(){}); }catch(e){} }
          }
          if(videoBox){ videoBox.classList.add('has-video'); videoBox.classList.remove('no-video'); }
          if(empty) empty.hidden = true;
        } else {
          if(source) source.removeAttribute('src');
          if(videoBox){ videoBox.classList.remove('has-video'); videoBox.classList.add('no-video'); }
          if(empty) empty.hidden = false;
        }
        if(posterUrl && posterUrl.value) video.setAttribute('poster', posterUrl.value); else video.removeAttribute('poster');
        itpApplyTurboSpeed(video, qs('[data-preview-control="speed"]', videoBox || document));
        itpApplyPreviewBackgroundWindow(video, false);
        video.onloadedmetadata = function(){ try{ if(window.itpVslApplyPreviewAspect) window.itpVslApplyPreviewAspect(); }catch(e){} itpApplyTurboSpeed(video, qs('[data-preview-control="speed"]', videoBox || document)); itpApplyPreviewBackgroundWindow(video, true); };
        video.oncanplay = function(){
          try{
            itpApplyTurboSpeed(video, qs('[data-preview-control="speed"]', videoBox || document));
            itpApplyPreviewBackgroundWindow(video, false);
            if(video.dataset.itpPreviewStarted !== '1' && video.muted){
              if(itpPreviewBackgroundActive(video)) itpApplyPreviewBackgroundWindow(video, false);
              video.play().catch(function(){});
            }
          }catch(e){}
        };
        video.ontimeupdate = function(){ itpApplyPreviewBackgroundWindow(video, false); };
      }
      if(hook){
        var hasHook = (!hookOn || hookOn.checked) && ((hookText && hookText.value) || (hookImage && hookImage.value));
        var hookStartInput = qs('input[name="vsl_hook_start"]');
        var hookEndInput = qs('input[name="vsl_hook_end"]');
        var hookStartVal = parseFloat((hookStartInput && hookStartInput.value) || 0) || 0;
        var hookEndVal = parseFloat((hookEndInput && hookEndInput.value) || 0) || 0;
        var hookWindowOpen = previewWasStarted && !previewIsTeaser && previewTime >= hookStartVal && (!hookEndVal || previewTime <= hookEndVal);
        hook.hidden = !hasHook || !hookWindowOpen;
        ['bottom_left','bottom_right','top_right','top_left'].forEach(function(c){hook.classList.remove(c);});
        if(hookPosition) hook.classList.add(hookPosition.value || 'bottom_left');
        if(hookOpacity) hook.style.opacity = Math.max(10, Math.min(100, parseInt(hookOpacity.value || '100',10))) / 100;
        var hookFontStack = itpPreviewFont('hook', hookFont, hookFontWoff2, 'Hook');
        hook.style.fontFamily = hookFontStack;
        hook.style.setProperty('--itp-hook-font', hookFontStack);
        var hookSpan = hook.querySelector('span');
        var hookImg = hook.querySelector('img');
        if(hookSpan && hookText) hookSpan.textContent = hookText.value || '';
        if(hookImage && hookImage.value){ if(!hookImg){ hookImg = document.createElement('img'); hook.insertBefore(hookImg, hook.firstChild); } hookImg.src = hookImage.value; }
        else if(hookImg){ hookImg.remove(); }
      }
      applyDesignTo(overlay, 'overlay');
      applyDesignTo(hook, 'hook');
      applyDesignTo(b, 'cta');
      initDesignables();
      if(typeof initVslPreviewPlayback === "function") initVslPreviewPlayback();
    }

    function setOverlayTemplateValue(value){
      var select = qs('[data-itp-overlay-template-select]');
      if(!select) return;
      value = (value === 'large') ? 'full' : (value || 'wide');
      select.value = value;

      // Template click should feel like choosing a fresh design, not reusing broken saved dimensions.
      // Batch all values first so the preview does not briefly render a half-old / half-new card.
      window.__itpSmartplayTemplateBatch = true;
      if(value !== 'custom' && typeof overlayTemplateDefaultWidth === 'function'){
        setDesign('overlay', 'width', overlayTemplateDefaultWidth(value));
        setDesign('overlay', 'x', 50);
        setDesign('overlay', 'y', 50);
        setDesign('overlay', 'rotate', 0);
      }

      var templateDefaults = {
        wide:   { top:'Your video has already started', bottom:'Click to hear', bg:'#f59a2a', fg:'#ffffff' },
        square: { top:'', bottom:'Click to hear', bg:'#9ba43a', fg:'#ffffff' },
        play:   { top:'', bottom:'CLICK TO HEAR', bg:'#435cab', fg:'#ffffff' },
        full:   { top:'Your video has already started', bottom:'Click to hear', bg:'#c044dc', fg:'#ffffff' },
        compact:{ top:'', bottom:'Click to hear', bg:'#079b5d', fg:'#ffffff' },
        icon_sound:{ top:'', bottom:'', bg:'#f59a2a', fg:'#ffffff' },
        icon_play:{ top:'', bottom:'', bg:'#435cab', fg:'#ffffff' },
        icon_blink:{ top:'', bottom:'', bg:'#079b5d', fg:'#ffffff' }
      };
      if(templateDefaults[value]){
        var d = templateDefaults[value];
        var topInput = qs('input[name="vsl_overlay_top"]');
        var bottomInput = qs('input[name="vsl_overlay_bottom"]');
        var bgInput = qs('input[name="vsl_overlay_color"]');
        var fgInput = qs('input[name="vsl_overlay_text_color"]');
        if(topInput) topInput.value = d.top;
        if(bottomInput) bottomInput.value = d.bottom;
        if(bgInput) bgInput.value = d.bg;
        if(fgInput) fgInput.value = d.fg;
      }
      window.__itpSmartplayTemplateBatch = false;

      select.dispatchEvent(new Event('change', {bubbles:true}));
      qsa('[data-itp-overlay-template-option]').forEach(function(btn){ btn.classList.toggle('active', btn.getAttribute('data-itp-overlay-template-option') === value); });
      qsa('[data-itp-overlay-mode]').forEach(function(btn){ btn.classList.toggle('active', (value === 'custom') ? btn.getAttribute('data-itp-overlay-mode') === 'custom' : btn.getAttribute('data-itp-overlay-mode') === 'template'); });
      setOverlayChooserMode(value);
      setTimeout(function(){ if(typeof syncAdminVslPreview === 'function') syncAdminVslPreview(); }, 30);
    }
    document.addEventListener('click', function(e){
      var tplBtn = e.target.closest('[data-itp-overlay-template-option]');
      if(tplBtn){
        e.preventDefault();
        setOverlayTemplateValue(tplBtn.getAttribute('data-itp-overlay-template-option') || 'wide');
        return;
      }
      var modeBtn = e.target.closest('[data-itp-overlay-mode]');
      if(modeBtn){
        e.preventDefault();
        var mode = modeBtn.getAttribute('data-itp-overlay-mode');
        setOverlayTemplateValue(mode === 'custom' ? 'custom' : (qs('[data-itp-overlay-template-option].active') ? qs('[data-itp-overlay-template-option].active').getAttribute('data-itp-overlay-template-option') : 'wide'));
        return;
      }
      var posBtn = e.target.closest('[data-itp-overlay-position-toggle]');
      if(posBtn){
        e.preventDefault();
        var studio = posBtn.closest('[data-itp-vsl-studio]') || qs('[data-itp-vsl-studio]');
        if(!studio) return;
        var active = studio.getAttribute('data-overlay-design-active') === '1';
        var nextActive = !active;
        studio.setAttribute('data-overlay-design-active', nextActive ? '1' : '0');
        posBtn.classList.toggle('active', nextActive);
        posBtn.textContent = nextActive ? 'Lock overlay position' : 'Edit overlay position';
        if(nextActive){
          restoreSmartAutoplayPreview(studio);
        } else {
          setTimeout(function(){ if(typeof syncAdminVslPreview === 'function') syncAdminVslPreview(); }, 20);
        }
      }
    });

    function setOverlayChooserMode(value){
      value = value || 'wide';
      qsa('[data-itp-overlay-template-grid]').forEach(function(grid){
        var hide = value === 'custom';
        grid.hidden = hide;
        grid.style.setProperty('display', hide ? 'none' : 'grid', hide ? 'important' : '');
      });
      qsa('[data-itp-autoplay-template-settings]').forEach(function(el){
        var hide = value === 'custom';
        el.hidden = hide;
        el.style.setProperty('display', hide ? 'none' : '', hide ? 'important' : '');
      });
      qsa('[data-itp-autoplay-custom]').forEach(function(el){
        var hide = value !== 'custom';
        el.hidden = hide;
        el.style.setProperty('display', hide ? 'none' : '', hide ? 'important' : '');
      });
      qsa('[data-itp-autoplay-text]').forEach(function(el){
        var hide = value === 'custom';
        el.hidden = hide;
        el.style.setProperty('display', hide ? 'none' : '', hide ? 'important' : '');
      });
    }
    function updateOverlayTemplateUI(){
      var select = qs('[data-itp-overlay-template-select]');
      if(!select) return;
      var value = select.value || 'wide';
      if(value === 'large'){ value = 'full'; select.value = 'full'; }
      qsa('[data-itp-overlay-template-option]').forEach(function(btn){ btn.classList.toggle('active', btn.getAttribute('data-itp-overlay-template-option') === value); });
      qsa('[data-itp-overlay-mode]').forEach(function(btn){ btn.classList.toggle('active', (value === 'custom') ? btn.getAttribute('data-itp-overlay-mode') === 'custom' : btn.getAttribute('data-itp-overlay-mode') === 'template'); });
      setOverlayChooserMode(value);
    }
    qsa('input[name^="vsl_"], textarea[name^="vsl_"], select[name^="vsl_"]').forEach(function(el){
      el.addEventListener('input', syncAdminVslPreview);
      el.addEventListener('change', syncAdminVslPreview);
    });
    qsa('[data-itp-cta-action]').forEach(function(el){
      el.addEventListener('change', function(){
        qsa('[data-itp-cta-lead-settings]').forEach(function(box){ box.hidden = !(el.value === 'lead' || el.value === 'lead_redirect'); });
        syncAdminVslPreview();
      });
    });
    updateOverlayTemplateUI();
    syncAdminVslPreview();
    enhanceVslControls();

    function initVslPreviewPlayback(){
      var box = qs('[data-itp-preview-video-box]');
      if(!box) return;
      var video = qs('[data-itp-preview-video]', box);
      var overlay = qs('[data-itp-preview-overlay]', box);
      var playBtn = qs('[data-preview-control="small_play"]', box);
      var timeEl = qs('[data-preview-control="time"]', box);
      var progress = qs('[data-itp-preview-progress] i', box);
      var speedEl = qs('[data-preview-control="speed"]', box);
      var speeds = [0.9,1,1.1,1.2,1.3,1.4,1.5,1.75,2];
      var currentSpeed = itpGetSelectedTurboSpeed();
      itpApplyTurboSpeed(video, speedEl);
      function fmt(t){ t = Math.max(0, Math.floor(t || 0)); return Math.floor(t/60)+':' + ((t%60)<10?'0':'') + (t%60); }
      function hidePreviewOverlay(){
        if(!overlay) return;
        overlay.hidden = true;
        overlay.style.setProperty('display','none','important');
        overlay.classList.add('is-consumed');
        overlay.setAttribute('aria-hidden','true');
      }
      function showPreviewOverlay(){
        if(!overlay) return;
        overlay.classList.remove('is-consumed');
        overlay.removeAttribute('aria-hidden');
        overlay.style.removeProperty('display');
        overlay.hidden = false;
      }
      function update(){
        if(!video) return;
        var bigPlayBtn = qs('[data-preview-control="big_play"]', box);
        var controlsWrap = qs('[data-itp-preview-controls]', box);
        var progressWrapEl = qs('[data-itp-preview-progress]', box);
        var userStarted = video.dataset.itpPreviewStarted === '1';
        var editingControls = currentVslDesignTab ? currentVslDesignTab() === 'style' : false;
        var inTeaser = !userStarted && !editingControls;
        var ctrlBigPlayInput = qs('input[name="vsl_ctrl_big_play"]');
        if(controlsWrap){
          var ctrlInputs = {
            back10: qs('input[name="vsl_ctrl_back10"]'),
            small_play: qs('input[name="vsl_ctrl_small_play"]'),
            forward10: qs('input[name="vsl_ctrl_forward10"]'),
            time: qs('input[name="vsl_ctrl_time"]'),
            volume: qs('input[name="vsl_ctrl_volume"]'),
            speed: qs('input[name="vsl_ctrl_speed"]'),
            fullscreen: qs('input[name="vsl_ctrl_fullscreen"]')
          };
          var anyVisibleControl = false;
          Object.keys(ctrlInputs).forEach(function(k){
            var el = qs('[data-preview-control="'+k+'"]', controlsWrap);
            var input = ctrlInputs[k];
            var show = !inTeaser && !!(input && input.checked);
            if(el) el.hidden = !show;
            if(show) anyVisibleControl = true;
          });
          controlsWrap.hidden = inTeaser || !anyVisibleControl;
        }
        if(progressWrapEl){
          var progressOnInput = qs('input[name="vsl_progress_on"]');
          progressWrapEl.hidden = inTeaser || !(progressOnInput && progressOnInput.checked);
        }
        if(bigPlayBtn){
          var overlayVisible = !!(overlay && !overlay.hidden);
          bigPlayBtn.hidden = overlayVisible || !(ctrlBigPlayInput && ctrlBigPlayInput.checked && userStarted && video.paused);
          var c = qs('input[name="vsl_ctrl_color"]');
          var bg = qs('input[name="vsl_ctrl_bg"]');
          if(c) bigPlayBtn.style.setProperty('--itp-vsl-control-color', c.value || '#ffffff');
          if(bg) bigPlayBtn.style.setProperty('--itp-vsl-control-bg', bg.value || '#111827');
        }
        if(playBtn) playBtn.textContent = video.paused ? '▶' : 'Ⅱ';
        if(timeEl) timeEl.textContent = fmt(video.currentTime || 0);
        if(progress && video.duration && isFinite(video.duration)){
          var pct = Math.max(0, Math.min(100, video.currentTime / video.duration * 100));
          var progressType = qs('select[name="vsl_progress_type"]');
          var visual = pct;
          if(!progressType || (progressType.value || 'smart') === 'smart') visual = Math.min(100, (1 - Math.exp(-pct/28)) * 100);
          progress.style.setProperty('width', visual + '%', 'important');
        }
      }
      function begin(){
        if(box.__itpPreviewBeginLock) return;
        box.__itpPreviewBeginLock = '1';
        setTimeout(function(){ box.__itpPreviewBeginLock = ''; }, 650);
        var studio = box.closest('[data-itp-vsl-studio]') || qs('[data-itp-vsl-studio]');
        if(studio && studio.getAttribute('data-overlay-design-active') === '1') return;
        hidePreviewOverlay();
        if(!video) return;
        video.dataset.itpPreviewStarted = '1';
        var mainInput = qs('input[name="vsl_video_url"]');
        var mainSrc = mainInput ? (mainInput.value || '') : '';
        var source = video.querySelector('source');
        if(mainSrc && source && source.getAttribute('src') !== mainSrc){
          source.setAttribute('src', mainSrc);
          try{ video.load(); }catch(e){}
        }
        video.loop = false;
        video.muted = false;
        video.removeAttribute('muted');
        var playNow = function(){
          try{
            if(video.readyState >= 1) video.currentTime = 0;
          }catch(e){}
          try{ itpApplyTurboSpeed(video, speedEl); video.play().catch(function(){}); }catch(e){}
          update();
          if(typeof syncAdminVslPreview === 'function') setTimeout(syncAdminVslPreview, 40);
          setTimeout(update, 90);
          setTimeout(update, 260);
        };
        if(video.readyState >= 2) playNow(); else { video.oncanplay = playNow; setTimeout(playNow, 350); }
        update();
      }
      if(box) box.__itpStartPreview = begin;
      if(box && !box.__itpOverlayForceStartBound){
        box.__itpOverlayForceStartBound = '1';
        box.addEventListener('click', function(e){
          var freshOverlay = qs('[data-itp-preview-overlay]', box);
          if(!freshOverlay || freshOverlay.hidden) return;
          if(e.target && e.target.closest && e.target.closest('.itp-design-handle, [data-itp-design-handle]')) return;
          var studio = box.closest('[data-itp-vsl-studio]') || qs('[data-itp-vsl-studio]');
          if(studio && studio.getAttribute('data-overlay-design-active') === '1') return;
          e.preventDefault();
          e.stopPropagation();
          begin();
        }, true);
      }
      if(overlay && !overlay.dataset.itpPreviewBound){
        overlay.dataset.itpPreviewBound='1';
        overlay.addEventListener('click', function(e){
          e.preventDefault(); e.stopPropagation();
          var studio = overlay.closest('[data-itp-vsl-studio]') || qs('[data-itp-vsl-studio]');
          if(studio && studio.getAttribute('data-overlay-design-active') === '1') return;
          begin();
        });
      }
      if(!box.dataset.itpPreviewFrameClickBound){
        box.dataset.itpPreviewFrameClickBound = '1';
        box.addEventListener('click', function(e){
          if(!video) return;
          if(e.target.closest('[data-itp-preview-overlay], [data-itp-preview-hook], [data-preview-control], [data-itp-preview-progress], [data-itp-preview-cta], .itp-design-handle, [data-itp-design-handle], [data-itp-design-resize-handle]')) return;
          var allowPauseInput = qs('input[name="vsl_ctrl_allow_pause"]');
          var userStarted = video.dataset.itpPreviewStarted === '1';
          if(!userStarted){
            if(overlay && !overlay.hidden) begin();
            return;
          }
          if(!allowPauseInput || !allowPauseInput.checked) return;
          if(video.paused) video.play().catch(function(){}); else video.pause();
          update();
        });
      }
      qsa('[data-preview-control]', box).forEach(function(ctrl){
        if(ctrl.dataset.itpPreviewBound) return;
        ctrl.dataset.itpPreviewBound = '1';
        ctrl.addEventListener('click', function(e){
          e.preventDefault(); e.stopPropagation();
          if(!video) return;
          var key = ctrl.getAttribute('data-preview-control');
          if(key === 'small_play' || key === 'big_play'){
            if(overlay && !overlay.hidden){ begin(); }
            else if(video.paused){ video.play().catch(function(){}); }
            else {
              var allowPauseInput = qs('input[name="vsl_ctrl_allow_pause"]');
              if(allowPauseInput && allowPauseInput.checked) video.pause();
            }
          }
          if(key === 'back10') video.currentTime = Math.max(0, (video.currentTime || 0) - 10);
          if(key === 'forward10' && video.duration) video.currentTime = Math.min(video.duration, (video.currentTime || 0) + 10);
          if(key === 'volume'){ video.muted = !video.muted; ctrl.textContent = video.muted ? '🔇' : '🔊'; }
          if(key === 'speed'){
            var cur = itpNormalizeSpeed(video.playbackRate || currentSpeed || itpGetSelectedTurboSpeed());
            var i = speeds.findIndex(function(x){ return Math.abs(x - cur) < 0.01; });
            currentSpeed = speeds[((i < 0 ? speeds.indexOf(itpGetSelectedTurboSpeed()) : i) + 1) % speeds.length];
            try{ video.defaultPlaybackRate = currentSpeed; video.playbackRate = currentSpeed; }catch(err){}
            ctrl.textContent = itpFormatSpeed(currentSpeed);
          }
          if(key === 'fullscreen'){ var target = qs('[data-itp-admin-vsl-preview]') || box; if(target.requestFullscreen) target.requestFullscreen().catch(function(){}); }
          update();
        });
      });
      if(video && !video.dataset.itpPreviewPlaybackBound){
        video.dataset.itpPreviewPlaybackBound = '1';
        video.addEventListener('timeupdate', function(){ itpApplyPreviewBackgroundWindow(video, false); update(); });
        video.addEventListener('loadedmetadata', function(){ itpApplyTurboSpeed(video, speedEl); itpApplyPreviewBackgroundWindow(video, true); update(); });
        video.addEventListener('canplay', function(){ itpApplyTurboSpeed(video, speedEl); itpApplyPreviewBackgroundWindow(video, false); update(); });
        video.addEventListener('ratechange', update);
        video.addEventListener('play', update);
        video.addEventListener('pause', update);
      }
      update();
    }
    initVslPreviewPlayback();

    document.addEventListener('click', function(e){
      var clear = e.target.closest('[data-itp-clear-media]');
      if(clear){
        e.preventDefault();
        var row = clear.closest('.itp-media-pick-row');
        var input = row ? row.querySelector('input.itp-media-url') : null;
        if(input){ input.value = ''; input.dispatchEvent(new Event('input', {bubbles:true})); input.dispatchEvent(new Event('change', {bubbles:true})); }
        syncAdminVslPreview();
        return;
      }
    });

    document.addEventListener('click', function(e){
      var btn = e.target.closest('[data-itp-copy-field]');
      if(!btn) return;
      e.preventDefault();
      var key = btn.getAttribute('data-itp-copy-field');
      var field = qs('[data-itp-copy-source="'+key+'"]');
      if(!field) return;
      var text = field.value || field.textContent || '';
      var old = btn.textContent;
      var done = function(){ btn.textContent = 'Copied'; setTimeout(function(){ btn.textContent = old; }, 1200); };
      if(navigator.clipboard && navigator.clipboard.writeText){ navigator.clipboard.writeText(text).then(done).catch(function(){ window.prompt('Copy embed code', text); }); }
      else { window.prompt('Copy embed code', text); }
    });


    function syncCookieStudioTabs(target){
      var studio = qs('[data-itp-cookie-studio]');
      if(!studio) return;
      target = target || 'page';
      qsa('[data-itp-cookie-tab]', studio).forEach(function(btn){ btn.classList.toggle('active', btn.getAttribute('data-itp-cookie-tab') === target); });
      qsa('[data-itp-cookie-panel]', studio).forEach(function(panel){ panel.classList.toggle('active', panel.getAttribute('data-itp-cookie-panel') === target); });
    }

    function itpIsImageLike(url){
      url = String(url || '').trim();
      return /\.(png|jpe?g|webp|gif|svg)(\?.*)?$/i.test(url) || /^data:image\//i.test(url);
    }

    function itpMshotsUrl(url){
      url = String(url || '').trim();
      if(!url || itpIsImageLike(url)) return url;
      if(!/^https?:\/\//i.test(url)) url = 'https://' + url.replace(/^\/+/, '');
      return 'https://s.wordpress.com/mshots/v1/' + encodeURIComponent(url) + '?w=1200';
    }

    function syncCookiePreview(){
      var preview = qs('[data-itp-cookie-preview]');
      if(!preview) return;
      var destination = itpFieldValue('top_cta_url');
      var bgRaw = itpFieldValue('background_image') || destination;
      var bg = itpMshotsUrl(bgRaw);
      var bgEl = qs('[data-itp-cookie-preview-bg]', preview);
      var fake = qs('.itp-cookie-mini-fake', preview);
      if(bgEl){
        if(bg){
          bgEl.style.backgroundImage = 'url("' + bg.replace(/"/g,'') + '")';
          bgEl.classList.add('has-image');
          if(fake) fake.style.display = 'none';
        } else {
          bgEl.style.backgroundImage = '';
          bgEl.classList.remove('has-image');
          if(fake) fake.style.display = '';
        }
        var blur = parseInt(itpFieldValue('cookie_blur') || '2', 10);
        bgEl.style.filter = 'blur(' + Math.max(0, Math.min(12, blur)) + 'px) saturate(.92) brightness(.9)';
      }
      var overlay = qs('[data-itp-cookie-preview-overlay]', preview);
      if(overlay){
        var op = parseInt(itpFieldValue('cookie_overlay_opacity') || '58', 10);
        overlay.style.background = 'rgba(0,0,0,' + (Math.max(0, Math.min(90, op)) / 100) + ')';
      }
      var modal = qs('[data-itp-cookie-preview-modal]', preview);
      var modalBg = itpFieldValue('cookie_modal_bg') || '#f8fafc';
      var modalText = itpFieldValue('cookie_modal_text') || '#111827';
      var acceptBg = itpFieldValue('cookie_accept_bg') || '#1683f7';
      var acceptText = itpFieldValue('cookie_accept_text') || '#ffffff';
      var linkColor = itpFieldValue('cookie_link_color') || '#2777c7';
      if(modal){ modal.style.background = modalBg; modal.style.color = modalText; }
      var title = qs('[data-itp-cookie-preview-title]', preview);
      if(title){ title.textContent = itpFieldValue('cookie_title') || ''; title.style.color = modalText; title.style.display = title.textContent ? '' : 'none'; }
      var copy = qs('[data-itp-cookie-preview-copy]', preview);
      if(copy){ copy.textContent = itpFieldValue('cookie_copy') || ''; copy.style.color = modalText; }
      var policy = qs('[data-itp-cookie-preview-policy]', preview);
      if(policy){ policy.textContent = itpFieldValue('cookie_policy_label') || ''; policy.style.color = linkColor; policy.style.display = policy.textContent ? '' : 'none'; }
      var close = qs('[data-itp-cookie-preview-close]', preview);
      if(close){ close.textContent = itpFieldValue('cookie_close_label') || ''; close.style.color = linkColor; close.style.display = close.textContent ? '' : 'none'; }
      var accept = qs('[data-itp-cookie-preview-accept]', preview);
      if(accept){ accept.textContent = itpFieldValue('cookie_accept_label') || 'Accept'; accept.style.background = acceptBg; accept.style.color = acceptText; accept.title = 'Redirects to: ' + (itpFieldValue('cookie_accept_url') || itpFieldValue('top_cta_url') || 'Destination URL'); }
      if(policy){ policy.title = 'Redirects to: ' + (itpFieldValue('cookie_policy_url') || 'Plugin privacy page'); }
      if(close){ close.title = 'Redirects to: ' + (itpFieldValue('cookie_close_url') || 'Site homepage'); }
      qsa('[data-itp-range-output]').forEach(function(out){ var name = out.getAttribute('data-itp-range-output'); var el = qs('[name="'+name+'"]'); if(el) out.textContent = el.value; });
    }

    function syncCardStudioTabs(target){
      var studio = qs('[data-itp-card-studio]');
      if(!studio) return;
      target = target || 'design';
      qsa('[data-itp-card-tab]', studio).forEach(function(btn){ btn.classList.toggle('active', btn.getAttribute('data-itp-card-tab') === target); });
      qsa('[data-itp-card-panel]', studio).forEach(function(panel){ panel.classList.toggle('active', panel.getAttribute('data-itp-card-panel') === target); });
    }

    document.addEventListener('click', function(e){
      var deviceBtn = e.target.closest('[data-itp-preview-device][data-itp-preview-target]');
      if(deviceBtn){
        e.preventDefault();
        var target = deviceBtn.getAttribute('data-itp-preview-target');
        var device = deviceBtn.getAttribute('data-itp-preview-device') || 'desktop';
        var preview = target === 'cookie' ? qs('[data-itp-cookie-preview]') : qs('[data-itp-bridge-preview]');
        if(preview){
          preview.classList.toggle('is-mobile', device === 'mobile');
          preview.classList.toggle('is-desktop', device !== 'mobile');
        }
        var wrap = deviceBtn.closest('.itp-preview-device-toggle');
        if(wrap){ qsa('button', wrap).forEach(function(btn){ btn.classList.toggle('active', btn === deviceBtn); }); }
        return;
      }
      var tab = e.target.closest('[data-itp-card-tab]');
      if(tab){
        e.preventDefault();
        syncCardStudioTabs(tab.getAttribute('data-itp-card-tab'));
        return;
      }
      var cookieTab = e.target.closest('[data-itp-cookie-tab]');
      if(cookieTab){
        e.preventDefault();
        syncCookieStudioTabs(cookieTab.getAttribute('data-itp-cookie-tab'));
        return;
      }
    });

    function syncBridgeDesignUI(){
      var modeEl = qs('[name="bridge_bg_mode"]');
      if(!modeEl) return;
      var mode = modeEl.value || 'gradient';
      var imageRow = qs('[data-itp-bg-image-row]');
      var bg2Row = qs('[data-itp-bg-color-2-row]');
      var topFields = qs('[data-itp-top-buttons-fields]');
      var topToggle = qs('[name="bridge_show_top_buttons"]');
      if(imageRow) imageRow.hidden = mode !== 'image';
      if(bg2Row) bg2Row.hidden = mode !== 'gradient';
      if(topFields) topFields.hidden = !(topToggle && topToggle.checked);
    }

    function itpFieldValue(name){
      var el = qs('[name="'+name+'"]');
      return el ? String(el.value || '') : '';
    }

    function itpCardField(row, suffix){
      var el = row ? qs('[name$="['+suffix+']"]', row) : null;
      return el ? String(el.value || '') : '';
    }

    function isProbablyImageUrl(url){
      url = String(url || '').trim();
      if(!url) return false;
      return /\.(png|jpe?g|webp|gif|svg)(\?.*)?$/i.test(url) || /^data:image\//i.test(url);
    }

    function cardRowStatus(row){
      var title = itpCardField(row, 'title').trim();
      var text = itpCardField(row, 'text').trim();
      var button = itpCardField(row, 'button').trim();
      var image = itpCardField(row, 'image').trim();
      var url = itpCardField(row, 'url').trim();
      var hasAny = title !== '' || text !== '' || image !== '' || url !== '';
      var complete = title !== '' && url !== '';
      return {title:title, text:text, button:button, image:image, url:url, hasAny:hasAny, complete:complete};
    }

    function itpPreviewText(el, value){
      if(!el) return;
      el.textContent = value;
      el.style.display = value === '' ? 'none' : '';
    }

    function syncBridgePreview(){
      var preview = qs('[data-itp-bridge-preview]');
      if(!preview) return;

      var mode = itpFieldValue('bridge_bg_mode') || 'gradient';
      var layout = itpFieldValue('bridge_card_layout') || 'stacked';
      var bg1 = itpFieldValue('bridge_bg_color') || '#0b0620';
      var bg2 = itpFieldValue('bridge_bg_color_2') || '#261044';
      var accent = itpFieldValue('bridge_button_bg') || '#24d4d9';
      var cardColor = itpFieldValue('bridge_card_bg') || '#241638';
      var titleColor = itpFieldValue('bridge_title_color') || '#ffffff';
      var textColor = itpFieldValue('bridge_text_color') || '#d8def0';
      var bgImage = itpFieldValue('bridge_bg_image');
      var logo = itpFieldValue('logo');
      var showBadge = !!(qs('[name="bridge_show_badge"]') || {}).checked;
      var showTopButtons = !!(qs('[name="bridge_show_top_buttons"]') || {}).checked;
      var headline = itpFieldValue('headline');
      var shortCopy = itpFieldValue('short_copy');
      var topLabel = itpFieldValue('top_cta_label');
      var topUrl = itpFieldValue('top_cta_url');
      var secondaryLabel = itpFieldValue('secondary_cta_label');
      var secondaryUrl = itpFieldValue('secondary_cta_url');

      preview.classList.remove('layout-stacked','layout-grid','layout-links');
      preview.classList.add('layout-' + layout);

      if(mode === 'solid'){
        preview.style.background = bg1;
      } else if(mode === 'image' && bgImage){
        preview.style.background = 'linear-gradient(180deg,rgba(0,0,0,.45),rgba(0,0,0,.55)), url("'+bgImage.replace(/"/g,'')+'") center/cover';
      } else {
        preview.style.background = 'linear-gradient(180deg,'+bg1+','+bg2+')';
      }
      preview.style.color = textColor;

      var badge = qs('[data-itp-preview-badge]', preview);
      var badgeImg = qs('[data-itp-preview-badge-img]', preview);
      if(badge){
        var useLogo = showBadge && logo !== '';
        badge.style.display = useLogo ? 'block' : 'none';
        badge.style.background = useLogo ? 'transparent' : accent;
        if(badgeImg){
          badgeImg.src = useLogo ? logo : '';
          badgeImg.style.display = useLogo ? 'block' : 'none';
        }
      }

      var h = qs('[data-itp-preview-headline]', preview);
      if(h){ itpPreviewText(h, headline); h.style.color = titleColor; }
      var p = qs('[data-itp-preview-copy]', preview);
      if(p){ itpPreviewText(p, shortCopy); p.style.color = textColor; }

      var actions = qs('[data-itp-preview-actions]', preview);
      if(actions){
        actions.innerHTML = '';
        var buttons = [];
        if(showTopButtons){
          if(topLabel !== '' || topUrl !== '') buttons.push({label: topLabel || 'Continue', cls: 'primary'});
          if(secondaryLabel !== '' || secondaryUrl !== '') buttons.push({label: secondaryLabel || 'Compare options', cls: 'secondary'});
        }
        buttons.forEach(function(item){
          var span = document.createElement('span');
          span.className = item.cls === 'secondary' ? 'secondary' : '';
          span.textContent = item.label;
          span.style.background = item.cls === 'secondary' ? 'rgba(255,255,255,.12)' : accent;
          span.style.color = item.cls === 'secondary' ? textColor : '#041526';
          actions.appendChild(span);
        });
        actions.style.display = buttons.length ? '' : 'none';
      }

      var list = qs('[data-itp-preview-card-list]', preview);
      if(list){
        list.innerHTML = '';
        var rows = qsa('[data-itp-card-row]');
        var rendered = 0;
        rows.forEach(function(row, index){
          var st = cardRowStatus(row);

          if(!st.hasAny){
            if(rows.length > 1){
              var warnEmpty = document.createElement('div');
              warnEmpty.className = 'itp-preview-empty-card warning';
              warnEmpty.textContent = 'Card ' + (index + 1) + ' is empty. Add title + destination URL or remove it.';
              list.appendChild(warnEmpty);
              rendered++;
            }
            return;
          }

          if(!st.complete){
            var warn = document.createElement('div');
            warn.className = 'itp-preview-empty-card warning';
            warn.textContent = 'Card ' + (index + 1) + ' is incomplete. Add a title and destination URL before saving.';
            list.appendChild(warn);
            rendered++;
          }

          var box = document.createElement('div');
          box.className = 'itp-preview-card' + (st.image ? ' has-image' : ' no-image');
          box.style.background = cardColor;
          box.style.borderColor = cardColor;

          if(st.image){
            var imgWrap = document.createElement('div');
            imgWrap.className = 'itp-preview-card-image';
            var img = document.createElement('img');
            img.src = st.image;
            img.alt = '';
            img.onerror = function(){
              imgWrap.classList.add('is-broken');
              imgWrap.textContent = isProbablyImageUrl(st.image) ? 'Image could not be loaded.' : 'Use a direct image URL ending in .jpg, .png, .webp, .gif or .svg.';
            };
            imgWrap.appendChild(img);
            box.appendChild(imgWrap);
          }

          var strong = document.createElement('strong');
          strong.textContent = st.title;
          strong.style.color = titleColor;
          strong.style.display = st.title === '' ? 'none' : '';
          box.appendChild(strong);

          var small = document.createElement('small');
          small.textContent = st.text;
          small.style.color = textColor;
          small.style.display = st.text === '' ? 'none' : '';
          box.appendChild(small);

          if(st.button !== '' || st.url !== ''){
            var em = document.createElement('em');
            em.textContent = (st.button || 'Read more') + ' →';
            em.style.background = accent;
            em.style.color = '#041526';
            box.appendChild(em);
          }

          list.appendChild(box);
          rendered++;
        });
        if(!rendered){
          var empty = document.createElement('div');
          empty.className = 'itp-preview-empty-card';
          empty.textContent = 'Cards are active. Add a title + destination URL to show your first clickable card.';
          list.appendChild(empty);
        }
      }
    }

    ['input','change'].forEach(function(evt){
      document.addEventListener(evt, function(e){
        if(e.target.matches('[name="bridge_bg_mode"], [name="bridge_card_layout"], [name="bridge_show_top_buttons"], [name="bridge_bg_color"], [name="bridge_bg_color_2"], [name="bridge_button_bg"], [name="bridge_card_bg"], [name="bridge_title_color"], [name="bridge_text_color"], [name="bridge_bg_image"], [name="logo"], [name="bridge_show_badge"], [name="headline"], [name="short_copy"], [name="top_cta_url"], [name="top_cta_label"], [name="secondary_cta_url"], [name="secondary_cta_label"], [name$="[title]"], [name$="[text]"], [name$="[button]"], [name$="[url]"], [name$="[image]"]')){
          syncBridgeDesignUI();
          syncBridgePreview();
        }
        if(e.target.matches('[name="title"], [name="slug"], [name="category"], [name="top_cta_url"], [name="background_image"], [name="cookie_title"], [name="cookie_copy"], [name="cookie_accept_label"], [name="cookie_close_label"], [name="cookie_policy_label"], [name="cookie_accept_url"], [name="cookie_close_url"], [name="cookie_policy_url"], [name="cookie_modal_bg"], [name="cookie_modal_text"], [name="cookie_accept_bg"], [name="cookie_accept_text"], [name="cookie_link_color"], [name="cookie_overlay_opacity"], [name="cookie_blur"]')){
          syncCookiePreview();
        }
      });
    });

    var createForm = qs('form.itp-create-form');
    if(createForm){
      createForm.addEventListener('submit', function(e){
        var selected = qs('input[name="template"]:checked');
        var value = selected ? selected.value : '';
        var isCardsBridge = value === 'cards_bridge' || ['blue_cards','news_cards','link_hub','offer_grid','review_clean','segment_choice'].indexOf(value) !== -1;
        if(!isCardsBridge) return;

        var rows = qsa('[data-itp-card-row]');
        var incomplete = [];
        var hasCardDestination = false;
        rows.forEach(function(row, index){
          var st = cardRowStatus(row);
          if(!st.hasAny){
            if(rows.length > 1) incomplete.push('Card ' + (index + 1) + ' is empty. Add title + URL or remove it.');
            return;
          }
          if(!st.complete){
            incomplete.push('Card ' + (index + 1) + ' needs a title and destination URL.');
            return;
          }
          hasCardDestination = true;
        });

        if(incomplete.length){
          e.preventDefault();
          alert(incomplete[0]);
          syncCardStudioTabs('cards');
          return;
        }

        var showTop = !!(qs('[name="bridge_show_top_buttons"]') || {}).checked;
        var hasTopDestination = showTop && (itpFieldValue('top_cta_url') !== '' || itpFieldValue('secondary_cta_url') !== '');
        if(!hasTopDestination && !hasCardDestination){
          e.preventDefault();
          alert('Add at least one card with title + destination URL, or enable top buttons with a URL.');
          syncCardStudioTabs('cards');
        }
      });
    }


    syncCardStudioTabs('design');
    syncCookieStudioTabs('page');
    syncBridgeDesignUI();
    syncBridgePreview();
    syncCookiePreview();


    initReorder();
  });
})();


/* Invalid Traffic 0.18.86 - VSL timeline duration binding
   Makes all timing fields visibly tied to detected video duration and clamps invalid values. */
(function(){
  "use strict";
  function qs(s,c){return (c||document).querySelector(s)}
  function qsa(s,c){return Array.prototype.slice.call((c||document).querySelectorAll(s))}
  function fmt(seconds){
    seconds = parseFloat(seconds || 0);
    if(!isFinite(seconds) || seconds <= 0) return 'detecting…';
    seconds = Math.floor(seconds);
    var h=Math.floor(seconds/3600), m=Math.floor((seconds%3600)/60), sec=seconds%60;
    if(h>0) return h+':'+(m<10?'0':'')+m+':'+(sec<10?'0':'')+sec;
    return m+':'+(sec<10?'0':'')+sec;
  }
  function num(v){ v=parseFloat(v||0); return isFinite(v)?v:0; }
  var cache = {};
  var durations = {main:0, background:0};
  var fieldLabels = {
    vsl_bg_start:'Background starts at',
    vsl_bg_end:'Background loops until',
    vsl_cta_delay:'CTA shows at',
    vsl_pitch_time:'Pitch marker optional',
    vsl_cta_end:'CTA hides after (0 = never)',
    vsl_pause_start:'Thumb Recovery starts after',
    vsl_pause_end:'Thumb Recovery ends after',
    vsl_hook_start:'Mini Hook appears at',
    vsl_hook_end:'Mini Hook disappears at'
  };
  var pairMap = [
    ['vsl_bg_start','vsl_bg_end','Background window'],
    ['vsl_pause_start','vsl_pause_end','Thumb Recovery window'],
    ['vsl_hook_start','vsl_hook_end','Mini Hook window'],
    ['vsl_cta_delay','vsl_cta_end','CTA window'],
    ['vsl_pitch_time','vsl_cta_end','Pitch/CTA end window']
  ];
  function getUrl(name){ var f=qs('[name="'+name+'"]'); return f ? (f.value||'').trim() : ''; }
  function markBadge(name, text){ var b=qs('[data-itp-duration-for="'+name+'"]'); if(b) b.textContent='Duration: '+text; }
  function probe(url, cb){
    if(!url){ cb(0,'no video selected'); return; }
    if(cache[url]){ cb(cache[url].seconds, cache[url].text); return; }
    var v=document.createElement('video');
    var done=false;
    v.preload='metadata'; v.muted=true; v.playsInline=true;
    function finish(seconds, text){
      if(done) return; done=true;
      seconds = num(seconds);
      if(seconds <= 0){ seconds = 0; text = text || 'unavailable'; }
      else { text = fmt(seconds); }
      cache[url]={seconds:seconds,text:text};
      cb(seconds,text);
      try{ v.removeAttribute('src'); v.load(); }catch(e){}
    }
    v.addEventListener('loadedmetadata', function(){ finish(v.duration, ''); }, {once:true});
    v.addEventListener('durationchange', function(){ if(v.duration && isFinite(v.duration)) finish(v.duration, ''); }, {once:true});
    v.addEventListener('error', function(){ finish(0,'unavailable'); }, {once:true});
    // Do not permanently fail too fast; some MP4s report metadata late on shared hosting.
    setTimeout(function(){ if(!done) cb(0,'detecting…'); }, 2200);
    setTimeout(function(){ if(!done) finish(0,'unavailable'); }, 12000);
    v.src=url;
    try{ v.load(); }catch(e){}
  }
  function ensureHelper(input){
    if(!input || input.dataset.itpTimelineEnhanced === '1') return;
    input.dataset.itpTimelineEnhanced='1';
    input.setAttribute('step','0.1');
    var helper=document.createElement('small');
    helper.className='itp-vsl-field-timeline-note';
    helper.setAttribute('data-itp-field-note', input.name || '');
    helper.textContent='Waiting for video duration…';
    if(input.parentNode) input.parentNode.appendChild(helper);
  }
  function applyToFields(source, seconds){
    seconds=num(seconds); durations[source]=seconds;
    var label=fmt(seconds);
    qsa('[data-itp-time-source="'+source+'"]').forEach(function(input){
      ensureHelper(input);
      var note=qs('[data-itp-field-note="'+input.name+'"]', input.parentNode || document);
      if(seconds>0){
        input.max=String(Math.max(0, Math.floor(seconds)));
        input.dataset.itpDetectedDuration=String(Math.floor(seconds));
        var current=num(input.value);
        // 0 means disabled for end fields; otherwise clamp values that exceed the detected timeline.
        var isEnd = /(_end|cta_end)$/.test(input.name||'');
        if(current > seconds){ input.value = String(Math.floor(seconds)); }
        input.title='Detected '+source+' timeline: '+label;
        if(note){
          var fieldLabel=fieldLabels[input.name] || 'Timing field';
          note.textContent=fieldLabel+' · timeline '+label+' · '+(input.value || '0')+'s';
        }
      } else if(note){
        note.textContent='Duration not detected yet. The player will still use this second value when metadata loads.';
      }
    });
    qsa('[data-itp-time-helper="'+source+'"]').forEach(function(el){
      if(seconds>0){
        el.innerHTML = (source==='main')
          ? '<strong>Main video duration:</strong> '+label+' — CTA, Thumb Recovery and Mini Hook use this video timeline.'
          : '<strong>Background duration:</strong> '+label+' — the muted teaser loops inside the selected window.';
      } else {
        el.textContent = source==='main'
          ? 'Main video duration is still detecting. Timing fields use seconds and will sync when metadata loads.'
          : 'Background duration is optional. If selected, start/end seconds use the background video timeline.';
      }
    });
    validatePairs();
  }
  function validatePairs(){
    pairMap.forEach(function(pair){
      var start=qs('[name="'+pair[0]+'"]'), end=qs('[name="'+pair[1]+'"]');
      if(!start || !end) return;
      [start,end].forEach(ensureHelper);
      var s=num(start.value), e=num(end.value);
      var bad = e>0 && e<=s;
      start.classList.toggle('itp-time-warning', bad);
      end.classList.toggle('itp-time-warning', bad);
      var enote=qs('[data-itp-field-note="'+end.name+'"]', end.parentNode || document);
      if(bad && enote){ enote.textContent=pair[2]+': end should be higher than start. Use 0 to keep it open.'; }
    });
  }
  function syncDurations(){
    var main=getUrl('vsl_video_url');
    var bg=getUrl('vsl_preview_video_url');
    if(main){ markBadge('vsl_video_url','detecting…'); probe(main,function(seconds,text){ markBadge('vsl_video_url', text); applyToFields('main', seconds); }); }
    else { markBadge('vsl_video_url','no video selected'); applyToFields('main', 0); }
    if(bg){ markBadge('vsl_preview_video_url','detecting…'); probe(bg,function(seconds,text){ markBadge('vsl_preview_video_url', text); applyToFields('background', seconds); }); }
    else { markBadge('vsl_preview_video_url','optional'); applyToFields('background', 0); }
  }
  function attachVideoDurationFallback(){
    var video=qs('[data-itp-preview-video]');
    if(!video || video.dataset.itpTimelineFallbackBound==='1') return;
    video.dataset.itpTimelineFallbackBound='1';
    ['loadedmetadata','durationchange','canplay'].forEach(function(evt){
      video.addEventListener(evt,function(){
        if(video.duration && isFinite(video.duration)){
          var bgUrl=getUrl('vsl_preview_video_url');
          var current = video.currentSrc || (video.querySelector('source') ? video.querySelector('source').src : video.src) || '';
          var isBg = bgUrl && current.indexOf(bgUrl) !== -1;
          applyToFields(isBg ? 'background' : 'main', video.duration);
        }
      });
    });
  }
  function bind(){
    qsa('[data-itp-time-source]').forEach(ensureHelper);
    qsa('[data-itp-time-source]').forEach(function(input){
      if(input.dataset.itpTimelineBound==='1') return;
      input.dataset.itpTimelineBound='1';
      input.addEventListener('input', function(){
        var source=input.getAttribute('data-itp-time-source') || 'main';
        var seconds=durations[source] || num(input.dataset.itpDetectedDuration);
        if(seconds>0 && num(input.value)>seconds) input.value=String(Math.floor(seconds));
        applyToFields(source, seconds);
      });
      input.addEventListener('change', function(){
        var source=input.getAttribute('data-itp-time-source') || 'main';
        applyToFields(source, durations[source] || num(input.dataset.itpDetectedDuration));
      });
    });
    ['vsl_video_url','vsl_preview_video_url'].forEach(function(name){
      var f=qs('[name="'+name+'"]');
      if(!f || f.dataset.itpTimelineMediaBound==='1') return;
      f.dataset.itpTimelineMediaBound='1';
      f.addEventListener('change', syncDurations);
      f.addEventListener('input', syncDurations);
    });
    attachVideoDurationFallback();
    syncDurations();
  }
  function ready(fn){ if(document.readyState==='loading') document.addEventListener('DOMContentLoaded',fn); else fn(); }
  ready(function(){
    bind();
    setTimeout(bind, 250);
    setTimeout(bind, 900);
    setTimeout(bind, 1800);
    document.addEventListener('click', function(e){
      if(e.target && e.target.closest && e.target.closest('[data-itp-media], .media-button-select, [data-itp-clear-media]')){
        setTimeout(bind, 300); setTimeout(syncDurations, 900);
      }
    }, true);
    document.addEventListener('input', validatePairs, true);
    document.addEventListener('change', validatePairs, true);
    if(window.MutationObserver){
      var obs=new MutationObserver(function(){ attachVideoDurationFallback(); });
      obs.observe(document.body,{childList:true,subtree:true});
    }
  });
})();


/* Invalid Traffic 0.18.86 - Safe VSL editor preview mode
   Editing tabs show CTA / recovery / hook visually before play, but never touch video source/loading.
   Once preview has started, public timeline rules take over. */
(function(){
  'use strict';
  function qs(s,c){return (c||document).querySelector(s);}
  function val(name, fallback){ var el=qs('[name="'+name+'"]'); return el ? (el.value || fallback || '') : (fallback || ''); }
  function checked(name){ var el=qs('[name="'+name+'"]'); return !!(el && el.checked); }
  function num(name, fallback){ var n=parseFloat(val(name,'')); return isFinite(n) ? n : (fallback||0); }
  function activeTab(){ var studio=qs('[data-itp-vsl-studio]'); return studio ? (studio.getAttribute('data-active-vsl-tab') || 'video') : 'video'; }
  function started(video){ return !!(video && video.dataset.itpPreviewStarted === '1'); }
  function inWindow(t,start,end){ return t >= start && (!end || t <= end); }
  function isBg(video){
    var bg=val('vsl_preview_video_url','');
    if(!bg || !video || started(video)) return false;
    var src=video.currentSrc || (video.querySelector('source') ? (video.querySelector('source').getAttribute('src') || video.querySelector('source').src || '') : (video.src || ''));
    return !!(src && src.indexOf(bg) !== -1);
  }
  function update(){
    var box=qs('[data-itp-preview-video-box]'); if(!box) return;
    var video=qs('[data-itp-preview-video]', box);
    var tab=activeTab();
    var liveStarted=started(video) && !isBg(video);
    var t=video ? (video.currentTime || 0) : 0;
    var cta=qs('[data-itp-preview-cta]');
    if(cta){
      var ctaOn=checked('vsl_cta_on');
      var show=num('vsl_cta_delay',0) || num('vsl_pitch_time',0);
      var end=num('vsl_cta_end',0);
      var editor=(tab==='cta' && !liveStarted && ctaOn);
      var live=(liveStarted && ctaOn && inWindow(t,show,end));
      cta.hidden = !(editor || live);
      cta.classList.toggle('is-editor-preview', editor);
    }
    var hook=qs('[data-itp-preview-hook]', box);
    if(hook){
      var hookOn=checked('vsl_hook_on');
      var hStart=num('vsl_hook_start',0), hEnd=num('vsl_hook_end',0);
      var editor=(tab==='hook' && !liveStarted && hookOn);
      var live=(liveStarted && hookOn && inWindow(t,hStart,hEnd));
      hook.hidden = !(editor || live);
      hook.classList.toggle('is-editor-preview', editor);
      var hookFontStack = itpEnsurePreviewWoff2Font('hook', val('vsl_hook_font_woff2',''), 'Hook') || itpCtaFontStack(val('vsl_hook_font','Inter'));
      hook.style.fontFamily = hookFontStack;
      hook.style.setProperty('--itp-hook-font', hookFontStack);
      var span=hook.querySelector('span');
      var hookTextValue = val('vsl_hook_text','');
      if(span){
        span.textContent = hookTextValue;
        span.hidden = !hookTextValue;
      }
      var image=val('vsl_hook_image',''); var img=hook.querySelector('img');
      if(image){ if(!img){ img=document.createElement('img'); hook.insertBefore(img, hook.firstChild); } img.src=image; }
      else if(img){ img.remove(); }
    }

    var resume=qs('[data-itp-preview-resume]', box);
    if(resume){
      var resumeOn=checked('vsl_resume_on');
      var editor=(tab==='resume' && !liveStarted && resumeOn);
      resume.hidden = !editor;
      resume.style.setProperty('--itp-resume-bg', val('vsl_resume_bg','#581c87') || '#581c87');
      resume.style.setProperty('--itp-resume-text', val('vsl_resume_text_color','#ffffff') || '#ffffff');
      var resumeFontStack = itpEnsurePreviewWoff2Font('resume', val('vsl_resume_font_woff2',''), 'Resume') || itpCtaFontStack(val('vsl_resume_font','Inter'));
      resume.style.fontFamily = resumeFontStack;
      resume.style.setProperty('--itp-resume-font', resumeFontStack);
      var rStrong=resume.querySelector('strong');
      if(rStrong) rStrong.textContent = val('vsl_resume_message','You already started watching this video') || 'You already started watching this video';
      var rBtns=resume.querySelectorAll('button');
      if(rBtns[0] && rBtns[0].lastChild) rBtns[0].lastChild.nodeValue = val('vsl_resume_continue_text','Continue watching?') || 'Continue watching?';
      if(rBtns[1] && rBtns[1].lastChild) rBtns[1].lastChild.nodeValue = val('vsl_resume_restart_text','Start from the beginning?') || 'Start from the beginning?';
    }

    var card=qs('[data-itp-preview-recovery]', box);
    if(card){
      var pauseOn=checked('vsl_pause_on');
      var trigger=val('vsl_pause_trigger','pause');
      var pStart=num('vsl_pause_start',0), pEnd=num('vsl_pause_end',0);
      var paused=!!(liveStarted && video && video.paused && !video.ended);
      var ended=!!(liveStarted && video && video.ended);
      var editor=(tab==='pause' && !liveStarted && pauseOn);
      var livePause=paused && pauseOn && (trigger==='pause' || trigger==='both') && inWindow(t,pStart,pEnd);
      var liveEnd=ended && pauseOn && (trigger==='end' || trigger==='both');
      card.hidden = !(editor || livePause || liveEnd);
      card.classList.toggle('is-editor-preview', editor);
      card.classList.toggle('is-final', liveEnd && !editor);
      ['pos-top','pos-center','pos-bottom'].forEach(function(c){ card.classList.remove(c); });
      card.classList.add('pos-' + (val('vsl_pause_button_position','bottom') || 'bottom'));
      var bg=card.querySelector('[data-itp-preview-recovery-resume]');
      if(bg){
        var image=val('vsl_pause_image',''); var img=bg.querySelector('img');
        if(image){ if(!img){ bg.innerHTML=''; img=document.createElement('img'); bg.appendChild(img); } img.src=image; }
        else if(!img){ bg.innerHTML='<span>Recovery preview</span><em>Appears on pause or video end based on your settings.</em>'; }
      }
      var btn=card.querySelector('[data-itp-preview-recovery-button]');
      if(btn){
        btn.hidden = !checked('vsl_pause_button_on');
        btn.textContent = val('vsl_pause_button_text','Continue') || 'Continue';
        btn.href = val('vsl_pause_button_url','#') || '#';
        var pauseFontStack = itpEnsurePreviewWoff2Font('pause', val('vsl_pause_font_woff2',''), 'Pause') || itpCtaFontStack(val('vsl_pause_font','Inter'));
        btn.style.fontFamily = pauseFontStack;
        btn.style.setProperty('--itp-pause-font', pauseFontStack);
      }
    }
  }
  function schedule(){ requestAnimationFrame(function(){ update(); setTimeout(update,80); }); }
  function bind(){
    document.addEventListener('input', schedule, true);
    document.addEventListener('change', schedule, true);
    document.addEventListener('click', function(e){ if(e.target.closest('[data-itp-vsl-tab]')) schedule(); }, true);
    var tries=0, timer=setInterval(function(){
      var v=qs('[data-itp-preview-video]');
      if(v && !v.dataset.itpSafePreviewModeBound){
        v.dataset.itpSafePreviewModeBound='1';
        ['timeupdate','play','pause','ended','loadedmetadata','seeked','ratechange'].forEach(function(evt){ v.addEventListener(evt, update); });
      }
      update(); tries++; if(tries>40) clearInterval(timer);
    },350);
    schedule();
  }
  if(document.readyState==='loading') document.addEventListener('DOMContentLoaded', bind); else bind();
})();


/* Invalid Traffic 0.18.86 - VSL main-as-teaser preview and duration recovery
   Rule: before click, either the selected background teaser OR the main video loops muted.
   On click, the main video always starts at 0 with the real timeline. */
(function(){
  'use strict';
  function qs(s,c){return (c||document).querySelector(s);}
  function val(name){ var el=qs('[name="'+name+'"]'); return el ? (el.value || '').trim() : ''; }
  function fmt(seconds){
    seconds=parseFloat(seconds||0);
    if(!isFinite(seconds) || seconds<=0) return '';
    seconds=Math.floor(seconds);
    var h=Math.floor(seconds/3600), m=Math.floor((seconds%3600)/60), s=seconds%60;
    if(h>0) return h+':'+(m<10?'0':'')+m+':'+(s<10?'0':'')+s;
    return m+':'+(s<10?'0':'')+s;
  }
  function setBadge(name, seconds){
    var b=qs('[data-itp-duration-for="'+name+'"]');
    if(!b || !seconds || !isFinite(seconds) || seconds<=0) return;
    b.textContent='Duration: '+fmt(seconds);
    b.dataset.itpDurationSeconds=String(Math.floor(seconds));
  }
  function selectedSource(){
    var main=val('vsl_video_url'), bg=val('vsl_preview_video_url');
    return {main:main, bg:bg};
  }
  function enforcePreview(){
    var box=qs('[data-itp-preview-video-box]');
    if(!box) return;
    var video=qs('[data-itp-preview-video]', box);
    var main=val('vsl_video_url'), bg=val('vsl_preview_video_url');
    var overlay=qs('[data-itp-preview-overlay]', box);
    if(!video || !main) return;

    var started = video.dataset.itpPreviewStarted === '1';
    var desired = started ? main : (bg || main);
    var source = video.querySelector('source');
    if(!source){ source=document.createElement('source'); source.type='video/mp4'; video.appendChild(source); }

    var current = source.getAttribute('src') || video.getAttribute('src') || '';
    if(desired && current !== desired){
      source.setAttribute('src', desired);
      try{ video.load(); }catch(e){}
    }

    if(!started){
      video.muted = true;
      video.setAttribute('muted','muted');
      video.loop = true;
      video.autoplay = true;
      video.playsInline = true;
      video.preload = 'metadata';
      if(overlay && overlay.hidden === true){
        /* keep overlay management from the main script; do not force it on here */
      }
      try{ video.play().catch(function(){}); }catch(e){}
    }
  }
  function bindStartReset(){
    var box=qs('[data-itp-preview-video-box]');
    if(!box || box.dataset.itpMainStartResetBound==='1') return;
    box.dataset.itpMainStartResetBound='1';
    box.addEventListener('click', function(e){
      var video=qs('[data-itp-preview-video]', box);
      var overlay=qs('[data-itp-preview-overlay]', box);
      if(!video || !overlay || overlay.hidden) return;
      setTimeout(function(){
        try{ if(video.dataset.itpPreviewStarted === '1' && video.readyState >= 1) video.currentTime = 0; }catch(err){}
      }, 60);
      setTimeout(function(){
        try{ if(video.dataset.itpPreviewStarted === '1' && video.readyState >= 1 && (video.currentTime||0) < 0.4) video.currentTime = 0; }catch(err){}
      }, 260);
    }, true);
  }
  function bindDurationFallback(){
    var video=qs('[data-itp-preview-video]');
    if(!video || video.dataset.itpDurationRecoveryBound==='1') return;
    video.dataset.itpDurationRecoveryBound='1';
    ['loadedmetadata','durationchange','canplay','loadeddata'].forEach(function(evt){
      video.addEventListener(evt,function(){
        if(video.duration && isFinite(video.duration) && video.duration > 0){
          var src = video.currentSrc || (video.querySelector('source') ? (video.querySelector('source').getAttribute('src') || video.querySelector('source').src || '') : (video.src || ''));
          var s=selectedSource();
          if(s.bg && src.indexOf(s.bg) !== -1) setBadge('vsl_preview_video_url', video.duration);
          else if(s.main && src.indexOf(s.main) !== -1) setBadge('vsl_video_url', video.duration);
          else setBadge('vsl_video_url', video.duration);
        }
      });
    });
  }
  function tick(){
    enforcePreview();
    bindStartReset();
    bindDurationFallback();
  }
  function boot(){
    tick();
    var tries=0;
    var timer=setInterval(function(){ tick(); tries++; if(tries>25) clearInterval(timer); }, 400);
    document.addEventListener('input', function(e){
      if(e.target && (e.target.name === 'vsl_video_url' || e.target.name === 'vsl_preview_video_url')) setTimeout(tick,80);
    }, true);
    document.addEventListener('change', function(e){
      if(e.target && (e.target.name === 'vsl_video_url' || e.target.name === 'vsl_preview_video_url')) setTimeout(tick,80);
    }, true);
  }
  if(document.readyState==='loading') document.addEventListener('DOMContentLoaded', boot); else boot();
})();


/* Invalid Traffic 0.18.86 - VSL controls stability, thumb/pause sync, mini hook position lock */
(function(){
  'use strict';
  function qs(s,c){ return (c||document).querySelector(s); }
  function qsa(s,c){ return Array.prototype.slice.call((c||document).querySelectorAll(s)); }
  function checked(name){ var el=qs('[name="'+name+'"]'); return !!(el && el.checked); }
  function setChecked(name, value){
    var el=qs('[name="'+name+'"]');
    if(!el) return;
    if(el.checked !== !!value){
      el.checked = !!value;
      el.dispatchEvent(new Event('change', {bubbles:true}));
      el.dispatchEvent(new Event('input', {bubbles:true}));
    }
  }
  function val(name, fallback){ var el=qs('[name="'+name+'"]'); return el ? (el.value || fallback || '') : (fallback || ''); }
  function activeVslTab(){
    var studio=qs('[data-itp-vsl-studio]');
    return studio ? (studio.getAttribute('data-active-vsl-tab') || 'video') : 'video';
  }

  function syncThumbWithPauseControls(){
    var thumb = qs('[name="vsl_pause_on"]');
    var allowPause = qs('[name="vsl_ctrl_allow_pause"]');
    if(!thumb || !allowPause) return;

    if(thumb.checked && !allowPause.checked){
      allowPause.checked = true;
      allowPause.dispatchEvent(new Event('change', {bubbles:true}));
      allowPause.dispatchEvent(new Event('input', {bubbles:true}));
    }

    var hint = qs('[data-itp-thumb-pause-sync-note]');
    if(!hint){
      var target = thumb.closest('.itp-toggle') || thumb.parentNode;
      if(target){
        hint = document.createElement('small');
        hint.setAttribute('data-itp-thumb-pause-sync-note','1');
        hint.className = 'itp-vsl-field-timeline-note itp-thumb-pause-sync-note';
        hint.textContent = 'Thumb Recovery needs pause behavior. When enabled, Allow pause / resume stays on automatically.';
        if(target.parentNode) target.parentNode.insertBefore(hint, target.nextSibling);
        else target.appendChild(hint);
      }
    }
  }

  function ensureMiniHookPositionUI(){
    var panel = qs('[data-itp-vsl-panel="hook"]');
    if(!panel || panel.dataset.itpHookPositionUiReady === '1') return;
    panel.dataset.itpHookPositionUiReady = '1';

    var design = qs('[data-itp-design-fields="hook"]', panel);
    if(!design) return;

    var strong = design.querySelector('strong');
    if(strong) strong.textContent = 'Position';

    var span = design.querySelector('span');
    if(span) span.textContent = 'Click “Edit mini hook position” to unlock drag and resize handles in the preview. Use this for text only, image only, or text + image hooks.';

    if(!design.querySelector('[data-itp-hook-position-toggle]')){
      var btn = document.createElement('button');
      btn.type = 'button';
      btn.className = 'itp-btn itp-btn-ghost';
      btn.setAttribute('data-itp-hook-position-toggle','1');
      btn.textContent = 'Edit mini hook position';
      var firstHidden = design.querySelector('input[type="hidden"]');
      design.insertBefore(btn, firstHidden || null);
    }
  }

  function updateHookHandles(){
    var studio = qs('[data-itp-vsl-studio]');
    var active = !!(studio && studio.getAttribute('data-hook-design-active') === '1');
    var hook = qs('[data-itp-preview-hook]');
    if(hook){
      hook.classList.toggle('itp-design-unlocked', active);
      qsa('[data-itp-design-handle]', hook).forEach(function(h){
        h.hidden = !active;
        h.style.display = active ? '' : 'none';
      });
    }
    var btn = qs('[data-itp-hook-position-toggle]');
    if(btn){
      btn.classList.toggle('active', active);
      btn.textContent = active ? 'Lock mini hook position' : 'Edit mini hook position';
    }
  }

  function syncControlsPreview(){
    var box = qs('[data-itp-preview-video-box]');
    if(!box) return;
    var video = qs('[data-itp-preview-video]', box);
    var userStarted = !!(video && video.dataset.itpPreviewStarted === '1');
    var editingControls = activeVslTab() === 'style';
    var inTeaser = !userStarted && !editingControls;
    var controlsWrap = qs('[data-itp-preview-controls]', box);
    if(!controlsWrap) return;

    var ctrlInputs = {
      back10: qs('input[name="vsl_ctrl_back10"]'),
      small_play: qs('input[name="vsl_ctrl_small_play"]'),
      forward10: qs('input[name="vsl_ctrl_forward10"]'),
      time: qs('input[name="vsl_ctrl_time"]'),
      volume: qs('input[name="vsl_ctrl_volume"]'),
      speed: qs('input[name="vsl_ctrl_speed"]'),
      fullscreen: qs('input[name="vsl_ctrl_fullscreen"]')
    };

    var any = false;
    Object.keys(ctrlInputs).forEach(function(k){
      var el = qs('[data-preview-control="'+k+'"]', controlsWrap);
      var input = ctrlInputs[k];
      var show = !inTeaser && !!(input && input.checked);
      if(el) el.hidden = !show;
      if(show) any = true;
    });

    controlsWrap.hidden = inTeaser || !any;
  }

  function normalizeMiniHookContent(){
    var hook = qs('[data-itp-preview-hook]');
    if(!hook) return;

    var text = val('vsl_hook_text','');
    var image = val('vsl_hook_image','');
    var span = hook.querySelector('span');
    if(!span){
      span = document.createElement('span');
      hook.appendChild(span);
    }
    span.textContent = text;
    span.hidden = !text;

    var img = hook.querySelector('img');
    if(image){
      if(!img){
        img = document.createElement('img');
        hook.insertBefore(img, hook.firstChild);
      }
      img.src = image;
      img.hidden = false;
    } else if(img){
      img.hidden = true;
    }

    hook.classList.toggle('has-hook-text', !!text);
    hook.classList.toggle('has-hook-image', !!image);
    hook.classList.toggle('image-only', !!image && !text);
    hook.classList.toggle('text-only', !!text && !image);

    if(activeVslTab() === 'hook' && checked('vsl_hook_on') && !text && !image){
      span.hidden = false;
      span.textContent = 'Mini hook preview';
      hook.classList.add('is-placeholder');
    } else {
      hook.classList.remove('is-placeholder');
    }
  }

  function updateAll(){
    ensureMiniHookPositionUI();
    syncThumbWithPauseControls();
    syncControlsPreview();
    normalizeMiniHookContent();
    updateHookHandles();
  }

  document.addEventListener('click', function(e){
    var hookBtn = e.target.closest('[data-itp-hook-position-toggle]');
    if(hookBtn){
      e.preventDefault();
      var studio = hookBtn.closest('[data-itp-vsl-studio]') || qs('[data-itp-vsl-studio]');
      if(!studio) return;
      var active = studio.getAttribute('data-hook-design-active') === '1';
      studio.setAttribute('data-hook-design-active', active ? '0' : '1');
      updateAll();
      if(typeof syncAdminVslPreview === 'function') setTimeout(syncAdminVslPreview, 20);
      return;
    }

    if(e.target.closest('[data-itp-vsl-tab]')){
      var studio = qs('[data-itp-vsl-studio]');
      if(studio){
        studio.setAttribute('data-hook-design-active','0');
      }
      setTimeout(updateAll, 50);
      setTimeout(updateAll, 250);
    }
  }, true);

  document.addEventListener('input', function(e){
    if(e.target && e.target.name === 'vsl_pause_on') syncThumbWithPauseControls();
    if(e.target && /^vsl_ctrl_|^vsl_hook_|^vsl_pause_/.test(e.target.name || '')) setTimeout(updateAll, 30);
  }, true);

  document.addEventListener('change', function(e){
    if(e.target && e.target.name === 'vsl_pause_on') syncThumbWithPauseControls();
    if(e.target && /^vsl_ctrl_|^vsl_hook_|^vsl_pause_/.test(e.target.name || '')) setTimeout(updateAll, 30);
  }, true);

  function boot(){
    updateAll();
    var tries = 0;
    var timer = setInterval(function(){
      updateAll();
      tries++;
      if(tries > 35) clearInterval(timer);
    }, 300);

    var video = qs('[data-itp-preview-video]');
    if(video && !video.dataset.itpControlsStabilityBound){
      video.dataset.itpControlsStabilityBound = '1';
      ['play','pause','timeupdate','loadedmetadata','canplay','seeked','ratechange'].forEach(function(evt){
        video.addEventListener(evt, function(){ setTimeout(updateAll, 20); });
      });
    }
  }

  if(document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot();
})();


/* Invalid Traffic 0.18.86 - admin preview uses real video proportion */
(function(){
  'use strict';
  function qs(s,c){return (c||document).querySelector(s);}
  function qsa(s,c){return Array.prototype.slice.call((c||document).querySelectorAll(s));}
  function apply(){
    qsa('[data-itp-preview-video-box]').forEach(function(box){
      var video = qs('[data-itp-preview-video]', box);
      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;
      var isV = ratio < 0.82, isS = ratio >= 0.82 && ratio <= 1.22, isH = ratio > 1.22;
      box.style.setProperty('--itp-vsl-admin-aspect', aspect);
      box.style.setProperty('--itp-vsl-preview-aspect', aspect);
      box.style.setProperty('--itp-vsl-aspect', aspect);
      box.classList.toggle('itp-admin-ratio-vertical', isV);
      box.classList.toggle('itp-admin-ratio-square', isS);
      box.classList.toggle('itp-admin-ratio-horizontal', isH);
      box.classList.toggle('itp-preview-ratio-vertical', isV);
      box.classList.toggle('itp-preview-ratio-square', isS);
      box.classList.toggle('itp-preview-ratio-horizontal', isH);
      var shell = box.closest('.itp-vsl-preview-shell');
      if(shell){
        shell.style.setProperty('--itp-vsl-admin-aspect', aspect);
        shell.style.setProperty('--itp-vsl-preview-aspect', aspect);
        shell.classList.toggle('itp-preview-ratio-vertical', isV);
        shell.classList.toggle('itp-preview-ratio-square', isS);
        shell.classList.toggle('itp-preview-ratio-horizontal', isH);
      }
      try{ window.itpVslPreviewAspect = {w:w,h:h,ratio:ratio}; }catch(e){}
    });
  }
  window.itpVslApplyPreviewAspect = apply;
  function bind(){
    qsa('[data-itp-preview-video]').forEach(function(v){
      if(v.dataset.itpAspectBound === '1') return;
      v.dataset.itpAspectBound = '1';
      ['loadedmetadata','loadeddata','canplay','emptied'].forEach(function(evt){ v.addEventListener(evt, apply); });
    });
    apply();
  }
  if(document.readyState === 'loading') document.addEventListener('DOMContentLoaded', bind); else bind();
  setInterval(bind, 800);
})();


    document.addEventListener('click', function(e){
      var go = e.target.closest('[data-itp-go-vsl-tab]');
      if(!go) return;
      e.preventDefault();
      var target = go.getAttribute('data-itp-go-vsl-tab') || 'embed';
      var studio = document.querySelector('[data-itp-vsl-studio]');
      if(!studio) return;
      var btn = studio.querySelector('[data-itp-vsl-tab="'+target+'"]');
      if(btn) {
        btn.click();
        try{ btn.scrollIntoView({block:'center', behavior:'smooth'}); }catch(err){}
      }
    });


/* Invalid Traffic 0.18.98 - authoritative admin preview surfaces
   Only admin preview: keep public/player-only embed untouched.
   - Resume and Thumb Recovery appear when their tab is open, without needing real visitor history.
   - Smart Autoplay full-screen template never pulses, even if pulse is enabled.
*/
(function(){
  'use strict';
  function qs(s,c){return (c||document).querySelector(s);}
  function qsa(s,c){return Array.prototype.slice.call((c||document).querySelectorAll(s));}
  function val(name, fallback){var el=qs('[name="'+name+'"]'); return el ? (el.value || fallback || '') : (fallback || '');}
  function checked(name){var el=qs('[name="'+name+'"]'); return !!(el && el.checked);}
  function num(name, fallback){var n=parseFloat(val(name,'')); return isFinite(n) ? n : (fallback||0);}
  function tab(){var studio=qs('[data-itp-vsl-studio]'); return studio ? (studio.getAttribute('data-active-vsl-tab') || 'video') : 'video';}
  function started(video){return !!(video && video.dataset.itpPreviewStarted === '1');}
  function inWindow(t,start,end){return t >= start && (!end || t <= end);}
  function fontStack(name, woffName, key){
    var woff = val(woffName,'');
    if(typeof window.itpEnsurePreviewWoff2Font === 'function'){
      var forced = window.itpEnsurePreviewWoff2Font(key, woff, key);
      if(forced) return forced;
    }
    if(typeof window.itpCtaFontStack === 'function') return window.itpCtaFontStack(val(name,'Inter'));
    var f = val(name,'Inter');
    return f === 'system' ? 'system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif' : f + ',system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif';
  }
  function isTeaser(video){
    if(!video || started(video)) return false;
    var bg = val('vsl_preview_video_url','');
    if(!bg) return false;
    var src = video.currentSrc || (video.querySelector('source') ? (video.querySelector('source').getAttribute('src') || video.querySelector('source').src || '') : (video.src || ''));
    return !!(src && src.indexOf(bg) !== -1);
  }
  function syncOverlayPulse(){
    var overlay = qs('[data-itp-preview-overlay]');
    var tpl = val('vsl_overlay_template','wide');
    if(tpl === 'large') tpl = 'full';
    var allow = tpl !== 'full';
    if(!overlay) return;
    if(!allow){
      overlay.classList.remove('pulse','pulse-scale','pulse-soft','pulse-glow','pulse-premium','pulse-heartbeat','pulse-breathe','pulse-bounce','pulse-flash','pulse-shake','effect-scale','effect-soft','effect-glow','effect-premium','effect-heartbeat','effect-breathe','effect-bounce','effect-flash','effect-shake');
      overlay.classList.add('pulse-disabled-template');
      qsa('.itp-vsl-pulse-ring', overlay).forEach(function(x){x.remove();});
    } else {
      overlay.classList.remove('pulse-disabled-template');
      if(checked('vsl_overlay_pulse')){
        var mode = val('vsl_overlay_pulse_mode','scale') || 'scale';
        overlay.classList.add('pulse','pulse-'+mode,'effect-'+mode);
        overlay.style.setProperty('--itp-overlay-pulse-duration', (val('vsl_overlay_pulse_speed','1.30') || '1.30') + 's');
      }
    }
    qsa('[data-itp-overlay-pulse-settings]').forEach(function(el){el.hidden = !(allow && checked('vsl_overlay_pulse'));});
  }
  function sync(){
    var box = qs('[data-itp-preview-video-box]');
    if(!box) return;
    var video = qs('[data-itp-preview-video]', box);
    var liveStarted = started(video) && !isTeaser(video);
    var t = video ? (video.currentTime || 0) : 0;
    var active = tab();
    syncOverlayPulse();

    var resume = qs('[data-itp-preview-resume]', box);
    if(resume){
      var showResumeEditor = active === 'resume' && checked('vsl_resume_on') && !liveStarted;
      resume.hidden = !showResumeEditor;
      resume.classList.toggle('is-editor-preview', showResumeEditor);
      if(showResumeEditor) resume.style.setProperty('display','flex','important'); else resume.style.removeProperty('display');
      resume.style.setProperty('--itp-resume-bg', val('vsl_resume_bg','#581c87') || '#581c87');
      resume.style.setProperty('--itp-resume-text', val('vsl_resume_text_color','#ffffff') || '#ffffff');
      var rf = fontStack('vsl_resume_font','vsl_resume_font_woff2','Resume');
      resume.style.fontFamily = rf; resume.style.setProperty('--itp-resume-font', rf);
      var strong = resume.querySelector('strong');
      if(strong) strong.textContent = val('vsl_resume_message','You already started watching this video') || 'You already started watching this video';
      var buttons = resume.querySelectorAll('button');
      if(buttons[0]) buttons[0].innerHTML = '<span>▶</span>' + (val('vsl_resume_continue_text','Continue watching?') || 'Continue watching?');
      if(buttons[1]) buttons[1].innerHTML = '<span>↻</span>' + (val('vsl_resume_restart_text','Start from the beginning?') || 'Start from the beginning?');
    }

    var rec = qs('[data-itp-preview-recovery]', box);
    if(rec){
      var pOn = checked('vsl_pause_on');
      var trigger = val('vsl_pause_trigger','pause') || 'pause';
      var pStart = num('vsl_pause_start',0), pEnd = num('vsl_pause_end',0);
      var paused = !!(liveStarted && video && video.paused && !video.ended);
      var ended = !!(liveStarted && video && video.ended);
      var editor = active === 'pause' && pOn && !liveStarted;
      var livePause = paused && pOn && (trigger === 'pause' || trigger === 'both') && inWindow(t,pStart,pEnd);
      var liveEnd = ended && pOn && (trigger === 'end' || trigger === 'both');
      var show = editor || livePause || liveEnd;
      rec.hidden = !show;
      rec.classList.toggle('is-editor-preview', editor);
      rec.classList.toggle('is-final', liveEnd && !editor);
      if(show) rec.style.setProperty('display','flex','important'); else rec.style.removeProperty('display');
      ['pos-top','pos-center','pos-bottom'].forEach(function(c){rec.classList.remove(c);});
      rec.classList.add('pos-' + (val('vsl_pause_button_position','bottom') || 'bottom'));
      var bg = qs('[data-itp-preview-recovery-resume]', rec);
      if(bg){
        var image = val('vsl_pause_image','');
        var img = bg.querySelector('img');
        if(image){ if(!img){ bg.innerHTML=''; img=document.createElement('img'); bg.appendChild(img); } img.src=image; img.hidden=false; }
        else { bg.innerHTML='<span>Recovery preview</span><em>Appears on pause or video end based on your settings.</em>'; }
      }
      var btn = qs('[data-itp-preview-recovery-button]', rec);
      if(btn){
        btn.hidden = !checked('vsl_pause_button_on');
        btn.textContent = val('vsl_pause_button_text','Continue') || 'Continue';
        btn.href = val('vsl_pause_button_url','#') || '#';
        var pf = fontStack('vsl_pause_font','vsl_pause_font_woff2','Pause');
        btn.style.fontFamily = pf; btn.style.setProperty('--itp-pause-font', pf);
        btn.style.setProperty('--itp-pause-btn', val('vsl_pause_button_color','#2563eb') || '#2563eb');
        btn.style.setProperty('--itp-pause-btn-hover', val('vsl_pause_button_hover_color','#1d4ed8') || '#1d4ed8');
        btn.style.setProperty('--itp-pause-btn-text', val('vsl_pause_button_text_color','#ffffff') || '#ffffff');
      }
    }
  }
  function schedule(){requestAnimationFrame(function(){sync(); setTimeout(sync,70); setTimeout(sync,220);});}
  function bind(){
    document.addEventListener('input', schedule, true);
    document.addEventListener('change', schedule, true);
    document.addEventListener('click', function(e){if(e.target.closest('[data-itp-vsl-tab], [data-itp-overlay-template-option], [data-itp-overlay-mode]')) schedule();}, true);
    var v = qs('[data-itp-preview-video]');
    if(v && !v.dataset.itpPreviewSurfaces98){
      v.dataset.itpPreviewSurfaces98='1';
      ['play','pause','timeupdate','seeked','ended','loadedmetadata','durationchange'].forEach(function(evt){v.addEventListener(evt, schedule);});
    }
    var tries=0, timer=setInterval(function(){sync(); tries++; if(tries>45) clearInterval(timer);},250);
    schedule();
  }
  if(document.readyState === 'loading') document.addEventListener('DOMContentLoaded', bind); else bind();
})();


/* =========================================================
   Invalid Traffic 0.18.143 - Smart Autoplay canvas preview reset
   Base: v0.18.140, not v0.18.142.
   - Keeps the picker/layout from the good 138-140 path.
   - Preview is a separate single SVG canvas object.
   - Template switch resets only the preview object dimensions.
   - Empty top/bottom inputs stay empty.
   ========================================================= */
(function(){
  'use strict';
  function qs(s,c){return (c||document).querySelector(s);}
  function qsa(s,c){return Array.prototype.slice.call((c||document).querySelectorAll(s));}
  function ready(fn){if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',fn);else fn();}
  function field(name){return qs('[name="'+name+'"]');}
  function rawValue(name, fallback){var el=field(name); return el ? String(el.value || '') : String(fallback || '');}
  function norm(t){t=t||'wide';return t==='large'?'full':t;}
  function iconKey(t){t=norm(t); return (t==='play'||t==='icon_play') ? 'play' : ((t==='compact'||t==='icon_blink') ? 'blink' : 'sound');}
  function selectedTemplate(){
    var select=qs('[data-itp-overlay-template-select], select[name="vsl_overlay_template"]');
    if(select && select.value) return norm(select.value);
    var active=qs('[data-itp-overlay-template-option].active');
    return norm(active ? active.getAttribute('data-itp-overlay-template-option') : 'wide');
  }
  function assetUrl(tpl){
    tpl=norm(tpl);
    var base=(window.ITP_ADMIN&&window.ITP_ADMIN.assetsUrl)?window.ITP_ADMIN.assetsUrl:'';
    if(tpl==='compact' || tpl==='icon_blink') return base + 'invalid-traffic-smartplay-blink.svg';
    var swatch=qs('[data-itp-overlay-template-option="'+tpl+'"] img.itp-vsl-template-main-icon');
    if(swatch && swatch.src) return swatch.src;
    return base + 'invalid-traffic-smartplay-' + iconKey(tpl) + '.svg';
  }
  function clearNode(n){while(n && n.firstChild)n.removeChild(n.firstChild);}
  function imp(el, prop, val){if(el && el.style)el.style.setProperty(prop, val, 'important');}
  function styles(el, map){Object.keys(map).forEach(function(k){imp(el,k,map[k]);});}
  function hide(el){ if(!el) return; styles(el,{display:'none',visibility:'hidden',opacity:'0'}); }
  function show(el){ if(!el) return; styles(el,{display:'block',visibility:'visible',opacity:'1'}); }
  function ensureRender(overlay){
    var r=overlay.querySelector(':scope > .itp-smartplay-preview-render');
    if(!r){r=document.createElement('div');r.className='itp-smartplay-preview-render';overlay.appendChild(r);}
    return r;
  }
  function svgEl(name, attrs){
    var el=document.createElementNS('http://www.w3.org/2000/svg', name);
    Object.keys(attrs||{}).forEach(function(k){ el.setAttribute(k, attrs[k]); });
    return el;
  }
  function textLines(text, max){
    text=String(text||'').trim();
    if(!text) return [];
    var manual=text.split(/\n+/).map(function(x){return x.trim();}).filter(Boolean);
    if(manual.length>1) return manual.slice(0,max||4);
    var words=text.split(/\s+/).filter(Boolean);
    if(!words.length) return [];
    if(words.length <= (max||3)) return words;
    var out=words.slice(0,(max||3)-1);
    out.push(words.slice((max||3)-1).join(' '));
    return out;
  }
  function addText(svg, text, x, y, size, opts){
    text=String(text||'');
    if(!text.trim()) return null;
    opts=opts||{};
    var node=svgEl('text',{
      x:String(x), y:String(y), 'text-anchor':'middle', 'dominant-baseline':'middle', fill:'currentColor',
      'font-family':'var(--itp-overlay-font, Inter, system-ui, sans-serif)',
      'font-size':String(size), 'font-weight':String(opts.weight||950),
      'letter-spacing':opts.letterSpacing||'-0.035em'
    });
    var lines=opts.lines || [text];
    var lineH=opts.lineHeight || size*1.12;
    if(lines.length>1){
      var startY=y-((lines.length-1)*lineH/2);
      lines.forEach(function(line,i){
        var t=svgEl('tspan',{x:String(x), y:String(startY+i*lineH)});
        t.textContent=line;
        node.appendChild(t);
      });
    } else {
      node.textContent=text;
    }
    svg.appendChild(node);
    return node;
  }
  function addIcon(svg, src, x, y, w, h){
    if(!src) return null;
    var img=svgEl('image',{href:src, x:String(x), y:String(y), width:String(w), height:String(h), preserveAspectRatio:'xMidYMid meet'});
    img.setAttributeNS('http://www.w3.org/1999/xlink','href',src);
    svg.appendChild(img);
    return img;
  }
  function bgDefault(tpl){
    tpl=norm(tpl);
    if(tpl==='square') return '#9ba43a';
    if(tpl==='play') return '#435cab';
    if(tpl==='full') return '#c044dc';
    if(tpl==='compact' || tpl==='icon_blink') return '#079b5d';
    if(tpl==='icon_play') return '#435cab';
    if(tpl==='icon_sound') return '#f79a27';
    return '#f79a27';
  }
  function buildSvg(tpl, top, bottom, src){
    tpl=norm(tpl);
    var spec;
    if(tpl==='square') spec={vb:'0 0 320 360', r:14, stroke:'rgba(255,255,255,.56)', strokeW:3};
    else if(tpl==='play') spec={vb:'0 0 320 320', r:2, stroke:'rgba(255,255,255,.34)', strokeW:2};
    else if(tpl==='full') spec={vb:'0 0 400 711', r:7, stroke:'rgba(255,255,255,.36)', strokeW:2};
    else if(tpl==='compact') spec={vb:'0 0 506 152', r:12, stroke:'rgba(255,255,255,.42)', strokeW:0};
    else if(tpl==='icon_sound' || tpl==='icon_play' || tpl==='icon_blink') spec={vb:'0 0 220 220', r:16, stroke:'rgba(255,255,255,.34)', strokeW:0};
    else spec={vb:'0 0 486 270', r:9, stroke:'rgba(255,255,255,.62)', strokeW:2.2};

    var svg=svgEl('svg',{class:'itp-smartplay-preview-svg', viewBox:spec.vb, preserveAspectRatio:'xMidYMid meet', role:'img', 'aria-hidden':'true'});
    svg.style.color='var(--itp-overlay-fg,#fff)';
    var p=spec.vb.split(/\s+/).map(parseFloat), W=p[2], H=p[3];
    var alphaEl=field('vsl_overlay_opacity');
    var alpha=Math.max(20, Math.min(100, parseInt(alphaEl ? (alphaEl.value || '92') : '92', 10))) / 100;
    var rect=svgEl('rect',{x:'0', y:'0', width:String(W), height:String(H), rx:String(spec.r), ry:String(spec.r), fill:'var(--itp-overlay-bg,'+bgDefault(tpl)+')', 'fill-opacity':String(alpha)});
    if(spec.strokeW){ rect.setAttribute('stroke',spec.stroke); rect.setAttribute('stroke-width',String(spec.strokeW)); }
    svg.appendChild(rect);

    if(tpl==='wide'){
      addText(svg, top, W/2, 54, 26, {weight:950});
      addIcon(svg, src, W/2-78, 82, 156, 109);
      addText(svg, bottom, W/2, 220, 27, {weight:950});
    } else if(tpl==='square'){
      addText(svg, bottom, W/2, 105, 45, {lines:textLines(bottom,3), lineHeight:51, weight:950});
      addIcon(svg, src, W/2-67, 222, 134, 96);
    } else if(tpl==='play'){
      addIcon(svg, src, W/2-92, 48, 184, 184);
      addText(svg, String(bottom||'').toUpperCase(), W/2, 272, 20, {weight:950, letterSpacing:'0.02em'});
    } else if(tpl==='full'){
      addText(svg, top, W/2, 307, 30, {lines:textLines(top,3), lineHeight:34, weight:950});
      addIcon(svg, src, W/2-54, 354, 108, 80);
      addText(svg, bottom, W/2, 482, 28, {weight:950});
    } else if(tpl==='compact'){
      addIcon(svg, src, W/2-34, 23, 68, 50);
      addText(svg, bottom, W/2, 105, 34, {weight:950});
    } else if(tpl==='icon_sound' || tpl==='icon_play' || tpl==='icon_blink'){
      var iw = (tpl==='icon_play') ? 142 : 118;
      var ih = (tpl==='icon_play') ? 142 : 100;
      addIcon(svg, src, W/2-iw/2, W/2-ih/2, iw, ih);
    }
    return svg;
  }
  function setShell(overlay){
    overlay.setAttribute('data-itp-preview-separated','1');
    overlay.setAttribute('data-itp-design-ready','1');
    styles(overlay,{
      position:'absolute', display:'block', padding:'0', margin:'0', border:'0', outline:'0',
      background:'transparent', boxShadow:'none', overflow:'visible', boxSizing:'border-box',
      transform:'translate(-50%,-50%) rotate(var(--itp-design-r,0deg))', transformOrigin:'center center',
      touchAction:'none', pointerEvents:'auto', cursor:'pointer', minWidth:'0', minHeight:'0', maxWidth:'none', maxHeight:'none'
    });
  }
  function templateAspect(tpl){
    tpl=norm(tpl);
    if(tpl==='square') return '320 / 360';
    if(tpl==='play') return '1 / 1';
    if(tpl==='full') return 'auto';
    if(tpl==='compact') return '506 / 152';
    if(tpl==='icon_sound' || tpl==='icon_play' || tpl==='icon_blink') return '1 / 1';
    return '486 / 270';
  }
  function safeSavedWidth(tpl){
    tpl=norm(tpl);
    var el=field('vsl_overlay_width');
    var w=el ? parseFloat(el.value) : NaN;
    var fallback={wide:42,square:40,play:40,compact:52,icon_sound:24,icon_play:24,icon_blink:24,full:100}[tpl] || 42;
    if(!isFinite(w) || w<=0) return fallback;
    if(tpl!=='full' && w>260) return fallback;
    return w;
  }
  function setOverlaySizing(overlay, tpl){
    tpl=norm(tpl);
    if(tpl==='full'){
      styles(overlay,{left:'50%', top:'50%', width:'100%', height:'100%', maxWidth:'100%', maxHeight:'100%', aspectRatio:'auto'});
      return;
    }
    var w=safeSavedWidth(tpl);
    styles(overlay,{left:'var(--itp-design-x,50%)', top:'var(--itp-design-y,50%)', width:'var(--itp-design-w,'+w+'%)', height:'auto', aspectRatio:templateAspect(tpl)});
  }
  function sync(){
    var overlay=qs('[data-itp-preview-overlay]');
    if(!overlay) return;
    // v0.18.161: after the preview Smart Autoplay is clicked/consumed,
    // do not let the template-render sync force display:block again.
    // This keeps Studio preview behavior aligned with the final player.
    if(overlay.hidden || (overlay.classList && overlay.classList.contains('is-consumed'))) return;
    var select=qs('[data-itp-overlay-template-select], select[name="vsl_overlay_template"]');
    if(select && !select.value) select.value='wide';
    var tpl=selectedTemplate();
    ['template-wide','template-square','template-play','template-minimal','template-large','template-full','template-compact','template-icon_sound','template-icon_play','template-icon_blink','template-custom'].forEach(function(c){overlay.classList.remove(c);});
    overlay.classList.add('template-'+tpl,'itp-smartplay-object');
    qsa('[data-itp-overlay-template-option]').forEach(function(btn){btn.classList.toggle('active', norm(btn.getAttribute('data-itp-overlay-template-option'))===tpl);});
    if(tpl==='custom'){
      overlay.removeAttribute('data-itp-preview-separated');
      var old=overlay.querySelector(':scope > .itp-smartplay-preview-render');
      if(old)old.remove();
      setShell(overlay);
      styles(overlay,{
        left:'var(--itp-design-x,50%)', top:'var(--itp-design-y,50%)', width:'var(--itp-design-w,34%)',
        height:'auto', aspectRatio:'auto', background:'transparent', boxShadow:'none', border:'0', outline:'0',
        overflow:'visible', padding:'0', margin:'0'
      });
      show(overlay.querySelector(':scope > .itp-smartplay-inner'));
      // v0.18.145: custom mode is isolated. It must not mix any preset background/icon/text with the uploaded image/GIF.
      var inner=overlay.querySelector(':scope > .itp-smartplay-inner');
      var img=inner ? inner.querySelector(':scope > img.itp-vsl-custom-overlay-image') : null;
      if(inner){
        styles(inner,{display:'block',visibility:'visible',opacity:'1',width:'100%',height:'auto',background:'transparent',overflow:'visible',padding:'0',margin:'0',border:'0',boxShadow:'none'});
        Array.prototype.slice.call(inner.children).forEach(function(ch){
          if(ch.classList && ch.classList.contains('itp-vsl-custom-overlay-image')){
            styles(ch,{display:'block',visibility:'visible',opacity:'1',width:'100%',height:'auto',maxWidth:'none',maxHeight:'none',objectFit:'contain',background:'transparent',border:'0',boxShadow:'none',margin:'0',padding:'0'});
          }
          else { hide(ch); }
        });
      }
      overlay.classList.toggle('has-custom-image', !!img);
      return;
    }
    setShell(overlay);
    setOverlaySizing(overlay, tpl);
    if(tpl==='full'){
      var oldFullRender=overlay.querySelector(':scope > .itp-smartplay-preview-render');
      if(oldFullRender) oldFullRender.remove();
      var fullInner=overlay.querySelector(':scope > .itp-smartplay-inner');
      if(fullInner){
        show(fullInner);
        styles(fullInner,{display:'flex',visibility:'visible',opacity:'1',position:'absolute',left:'0',top:'0',right:'0',bottom:'0',width:'100%',height:'100%',maxWidth:'100%',maxHeight:'100%',transform:'none',aspectRatio:'auto',overflow:'hidden',boxSizing:'border-box',flexDirection:'column',alignItems:'center',justifyContent:'center',gap:'min(6cqw,6cqh,42px)',padding:'min(7cqw,8cqh,72px)',containerType:'size',background:'color-mix(in srgb, var(--itp-overlay-bg,#c044dc) var(--itp-overlay-opacity-pct,92%), transparent)'});
        var fullTop=fullInner.querySelector('[data-itp-preview-overlay-top], .itp-vsl-overlay-top');
        var fullBottom=fullInner.querySelector('[data-itp-preview-overlay-bottom], .itp-vsl-overlay-bottom');
        var fullIcon=fullInner.querySelector('[data-itp-template-icon], .itp-vsl-itbrand-icon');
        if(fullTop){ fullTop.textContent=rawValue('vsl_overlay_top',''); show(fullTop); styles(fullTop,{position:'static',left:'auto',top:'auto',width:'min(92%,980px)',maxWidth:'92%',transform:'none',margin:'0',padding:'0',textAlign:'center',whiteSpace:'normal',overflow:'visible',fontSize:'min(6.2cqw,7cqh,46px)',lineHeight:'1.08',fontWeight:'950',letterSpacing:'-.025em'}); }
        if(fullIcon){ fullIcon.src=assetUrl(tpl); fullIcon.className='itp-vsl-itbrand-icon itp-vsl-itbrand-icon-'+iconKey(tpl); show(fullIcon); styles(fullIcon,{position:'static',left:'auto',top:'auto',width:'min(24cqw,22cqh,180px)',height:'min(18cqw,16cqh,132px)',maxWidth:'30%',maxHeight:'24%',transform:'none',objectFit:'contain',margin:'0',padding:'0',opacity:'1',visibility:'visible',flex:'0 0 auto'}); }
        if(fullBottom){ fullBottom.textContent=rawValue('vsl_overlay_bottom',''); show(fullBottom); styles(fullBottom,{position:'static',left:'auto',top:'auto',width:'min(92%,980px)',maxWidth:'92%',transform:'none',margin:'0',padding:'0',textAlign:'center',whiteSpace:'normal',overflow:'visible',fontSize:'min(5.6cqw,6.4cqh,42px)',lineHeight:'1.08',fontWeight:'950',letterSpacing:'-.025em'}); }
        Array.prototype.slice.call(fullInner.children).forEach(function(ch){
          if(ch.classList && (ch.classList.contains('itp-vsl-overlay-top') || ch.classList.contains('itp-vsl-overlay-bottom') || ch.classList.contains('itp-vsl-itbrand-icon'))){ show(ch); }
        });
      }
      overlay.setAttribute('data-itp-preview-separated','0');
      return;
    }
    hide(overlay.querySelector(':scope > .itp-smartplay-inner'));
    var render=ensureRender(overlay);
    clearNode(render);
    styles(render,{
      position:'absolute', inset:'0', width:'100%', height:'100%', display:'block', overflow:'visible',
      boxSizing:'border-box', pointerEvents:'none', margin:'0', padding:'0', border:'0', outline:'0', background:'transparent',
      color:'var(--itp-overlay-fg,#fff)', transformOrigin:'center center'
    });
    var top=rawValue('vsl_overlay_top','');
    var bottom=rawValue('vsl_overlay_bottom','');
    var src=assetUrl(tpl);
    render.appendChild(buildSvg(tpl, top, bottom, src));
    render.setAttribute('data-itp-template',tpl);
    overlay.style.setProperty('--itp-preview-icon-url','url("'+src.replace(/"/g,'%22')+'")');
  }
  function schedule(){sync();setTimeout(sync,25);setTimeout(sync,120);setTimeout(sync,360);}
  ready(function(){
    schedule();
    ['input','change','click','pointerup','touchend','keyup'].forEach(function(evt){
      document.addEventListener(evt,function(e){
        var t=e.target;if(!t)return;
        if((t.matches&&t.matches('[name="vsl_overlay_template"], [data-itp-overlay-template-select], [name="vsl_overlay_top"], [name="vsl_overlay_bottom"], [name="vsl_overlay_image"], [name="vsl_overlay_color"], [name="vsl_overlay_text_color"], [name="vsl_overlay_font"], [name="vsl_overlay_font_woff2"], [name="vsl_overlay_opacity"]')) || (t.closest&&t.closest('[data-itp-overlay-template-option], [data-itp-overlay-mode], [data-itp-design-toggle], [data-itp-overlay-position-toggle]'))){schedule();}
      },true);
    });
    var overlay=qs('[data-itp-preview-overlay]');
    if(overlay && window.MutationObserver){
      var guard=false;
      new MutationObserver(function(){ if(guard)return; guard=true; setTimeout(function(){guard=false; sync();},30); }).observe(overlay,{childList:true,attributes:true,subtree:false,attributeFilter:['class','style','hidden']});
    }
    var tries=0,timer=setInterval(function(){sync();tries++;if(tries>45)clearInterval(timer);},250);
  });
})();



/* Invalid Traffic 0.18.182 - Resume/Thumb diagnostics for Studio preview */
(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){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 tab(){var st=qs('[data-itp-vsl-studio]');return st?(st.getAttribute('data-active-vsl-tab')||'-'):'-';}
  function panel(){var p=document.getElementById('itp-vsl-stage-diag-182'); if(!p){p=document.createElement('pre');p.id='itp-vsl-stage-diag-182';p.style.cssText='position:fixed;right:8px;bottom:8px;z-index:2147483647;max-width:min(520px,92vw);max-height:48vh;overflow:auto;padding:9px 10px;border-radius:9px;background:rgba(2,6,23,.92);color:#a7f3d0;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 box=qs('[data-itp-preview-video-box]');
    var video=box?qs('[data-itp-preview-video]',box):null;
    var resume=box?qs('[data-itp-preview-resume]',box):null;
    var recovery=box?qs('[data-itp-preview-recovery]',box):null;
    var recImg=recovery?qs('img',recovery):null;
    var overlay=box?qs('[data-itp-preview-overlay]',box):null;
    var lines=[];
    lines.push('ITP STUDIO STAGE DIAG 0.18.182');
    lines.push('active tab: '+tab());
    lines.push('viewport: '+innerWidth+'x'+innerHeight);
    lines.push('stage:   '+rect(box));
    lines.push('video:   '+rect(video)+' intrinsic='+(video?(video.videoWidth+'x'+video.videoHeight):'-'));
    lines.push('stage class: '+(box?box.className:'-'));
    lines.push('stage aspect var: '+css(box,'--itp-vsl-admin-aspect'));
    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:'-'));
    panel().textContent=lines.join('\n');
  }
  [120,600,1400,2400].forEach(function(ms){setTimeout(update,ms);});
  try{setInterval(update,1000);}catch(e){}
})();


/* Invalid Traffic 0.18.187 - Smartplay editor tab isolation + custom handle repair */
(function(){
  'use strict';
  function qs(s,c){return (c||document).querySelector(s);} 
  function qsa(s,c){return Array.prototype.slice.call((c||document).querySelectorAll(s));}
  function checked(name){var el=qs('[name="'+name+'"]');return !!(el&&el.checked);} 
  function activeTab(){var st=qs('[data-itp-vsl-studio]');return st?(st.getAttribute('data-active-vsl-tab')||'video'):'video';}
  function visible(el){if(!el||el.hidden)return false;try{return getComputedStyle(el).display!=='none'&&getComputedStyle(el).visibility!=='hidden'&&getComputedStyle(el).opacity!=='0';}catch(e){return true;}}
  function smartplayShouldYieldToEditor(tab){return tab==='resume'||tab==='pause'||tab==='recovery'||tab==='thumb'||tab==='thumb_recovery';}
  function hideOverlayForFeature(overlay){
    if(!overlay)return;
    overlay.setAttribute('data-itp-hidden-by-feature-tab','1');
    overlay.hidden=true;
    overlay.classList.add('is-consumed');
    overlay.setAttribute('aria-hidden','true');
    overlay.style.setProperty('display','none','important');
    overlay.style.setProperty('visibility','hidden','important');
    overlay.style.setProperty('opacity','0','important');
    overlay.style.setProperty('pointer-events','none','important');
  }
  function restoreOverlayFromFeature(overlay){
    if(!overlay||overlay.getAttribute('data-itp-hidden-by-feature-tab')!=='1')return;
    overlay.removeAttribute('data-itp-hidden-by-feature-tab');
    overlay.classList.remove('is-consumed');
    overlay.removeAttribute('aria-hidden');
    overlay.style.removeProperty('display');
    overlay.style.removeProperty('visibility');
    overlay.style.removeProperty('opacity');
    overlay.style.removeProperty('pointer-events');
    overlay.hidden=false;
  }
  function repairCustomOverlay(overlay){
    if(!overlay||!overlay.classList||!overlay.classList.contains('template-custom'))return;
    var render=overlay.querySelector(':scope > .itp-smartplay-preview-render');
    if(render){render.style.setProperty('display','none','important');render.style.setProperty('visibility','hidden','important');render.style.setProperty('opacity','0','important');}
    var inner=overlay.querySelector(':scope > span.itp-smartplay-inner');
    if(!inner)return;
    inner.style.setProperty('position','relative','important');
    inner.style.setProperty('display','block','important');
    inner.style.setProperty('width','100%','important');
    inner.style.setProperty('height','auto','important');
    inner.style.setProperty('overflow','visible','important');
    inner.style.setProperty('background','transparent','important');
    inner.style.setProperty('border','0','important');
    inner.style.setProperty('box-shadow','none','important');
    inner.style.setProperty('pointer-events','none','important');
    qsa(':scope > :not(img.itp-vsl-custom-overlay-image)', inner).forEach(function(el){el.style.setProperty('display','none','important');el.style.setProperty('visibility','hidden','important');el.style.setProperty('opacity','0','important');});
    var img=inner.querySelector(':scope > img.itp-vsl-custom-overlay-image');
    if(img){
      overlay.classList.add('has-custom-image','is-custom-image-only');
      img.style.setProperty('position','relative','important');
      img.style.setProperty('inset','auto','important');
      img.style.setProperty('display','block','important');
      img.style.setProperty('width','100%','important');
      img.style.setProperty('height','auto','important');
      img.style.setProperty('max-width','none','important');
      img.style.setProperty('max-height','none','important');
      img.style.setProperty('object-fit','contain','important');
      img.style.setProperty('transform','none','important');
      img.style.setProperty('border','0','important');
      img.style.setProperty('box-shadow','none','important');
      img.style.setProperty('pointer-events','none','important');
    }
  }
  function enforce(){
    var st=qs('[data-itp-vsl-studio]');
    if(!st)return;
    var box=qs('[data-itp-preview-video-box]',st)||qs('[data-itp-preview-video-box]');
    var overlay=box?qs('[data-itp-preview-overlay]',box):qs('[data-itp-preview-overlay]',st);
    var tab=activeTab();
    var designActive=st.getAttribute('data-overlay-design-active')==='1';
    var resume=box?qs('[data-itp-preview-resume]',box):null;
    var recovery=box?qs('[data-itp-preview-recovery]',box):null;
    var featureVisible=(smartplayShouldYieldToEditor(tab)&&!designActive)||(visible(resume)&&tab==='resume')||(visible(recovery)&&(tab==='pause'||tab==='recovery'||tab==='thumb'||tab==='thumb_recovery'));
    if(featureVisible){
      hideOverlayForFeature(overlay);
    }else if(overlay&&overlay.getAttribute('data-itp-hidden-by-feature-tab')==='1'){
      var v=box?qs('[data-itp-preview-video]',box):null;
      var started=!!(v&&v.dataset&&v.dataset.itpPreviewStarted==='1');
      if(checked('vsl_smart_autoplay')&&!started){restoreOverlayFromFeature(overlay);} else {overlay.removeAttribute('data-itp-hidden-by-feature-tab');}
    }
    repairCustomOverlay(overlay);
  }
  function schedule(){try{enforce();setTimeout(enforce,30);setTimeout(enforce,140);setTimeout(enforce,420);}catch(e){}}
  if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',schedule);else schedule();
  ['click','input','change','pointerup','touchend','keyup'].forEach(function(evt){document.addEventListener(evt,function(e){
    var t=e.target;
    if(!t)return;
    if((t.closest&&t.closest('[data-itp-vsl-tab], [data-itp-overlay-position-toggle], [data-itp-overlay-mode], [data-itp-overlay-template-option]'))||(t.matches&&t.matches('[name^="vsl_"]'))){schedule();}
  },true);});
  var tries=0,timer=setInterval(function(){enforce();tries++;if(tries>80)clearInterval(timer);},250);
})();

/* Invalid Traffic v0.18.194 - granular VSL retention frame scrubber */
(function(){
  'use strict';
  function qsa(s,c){return Array.prototype.slice.call((c||document).querySelectorAll(s));}
  function clamp(n,a,b){return Math.max(a,Math.min(b,n));}
  function mmss(t){t=Math.max(0,Math.round(t||0));var m=Math.floor(t/60),s=t%60;return String(m).padStart(2,'0')+':'+String(s).padStart(2,'0');}
  function interp(points,t){
    if(!points||!points.length) return 0;
    points=points.slice().sort(function(a,b){return (+a.t)-(+b.t);});
    if(t<=+points[0].t) return +points[0].r||0;
    for(var i=1;i<points.length;i++){
      var a=points[i-1], b=points[i], at=+a.t, bt=+b.t;
      if(t<=bt){ var ratio=(t-at)/Math.max(.01,bt-at); return Math.round(((+a.r||0)+(((+b.r||0)-(+a.r||0))*ratio))*100)/100; }
    }
    return +points[points.length-1].r||0;
  }
  function initRetentionStage(stage){
    if(!stage || stage.__itpRetentionReady) return;
    stage.__itpRetentionReady = true;
    var video = stage.querySelector('[data-itp-retention-video]');
    var caption = stage.querySelector('[data-itp-retention-caption]');
    var points=[];
    try{ points=JSON.parse(stage.getAttribute('data-points')||'[]')||[]; }catch(e){ points=[]; }
    if(!video) return;
    var duration = parseFloat(stage.getAttribute('data-duration')||'0') || 0;
    var seeking = false, pending = null, lastT = 0;
    try{ video.pause(); video.muted = true; video.playsInline = true; video.preload='auto'; video.load(); }catch(e){}
    function updateCaption(t){
      if(!caption) return;
      var r = interp(points,t);
      var strong = caption.querySelector('strong'), span = caption.querySelector('span'), em = caption.querySelector('em');
      if(strong) strong.textContent = (isFinite(r)?r:0) + '%';
      if(span) span.textContent = 'Retention preview';
      if(em) em.textContent = mmss(t) + ' on this video';
    }
    function safeSeek(t){
      var d = duration || video.duration || 0;
      if(!d || !isFinite(d)) return;
      t = clamp(t, 0.01, Math.max(0.01, d - 0.05));
      lastT = t; pending = t; updateCaption(t);
      if(seeking) return;
      seeking = true;
      requestAnimationFrame(function(){
        try{ video.currentTime = pending; }catch(e){}
        setTimeout(function(){ seeking = false; if(pending !== null && Math.abs((video.currentTime||0)-pending) > .35){ var again=pending; pending=null; safeSeek(again); } }, 70);
      });
    }
    function seekFromEvent(e){
      try{stage.classList.add('is-scrubbing'); clearTimeout(stage.__itpScrubTimer); stage.__itpScrubTimer=setTimeout(function(){stage.classList.remove('is-scrubbing');},650);}catch(_e){}
      var rect = stage.getBoundingClientRect();
      if(!rect.width) return;
      var clientX = e.clientX || (e.touches && e.touches[0] && e.touches[0].clientX) || rect.left;
      var x = clientX - rect.left;
      var pct = clamp(x / rect.width, 0, 1);
      var d = duration || video.duration || 0;
      if(d) safeSeek(d * pct);
    }
    video.addEventListener('loadedmetadata', function(){ duration = duration || video.duration || 0; safeSeek(Math.min(0.2, Math.max(0.01, (duration||1)*0.02))); });
    video.addEventListener('canplay', function(){ if(!lastT) safeSeek(Math.min(0.2, Math.max(0.01, (duration||video.duration||1)*0.02))); });
    stage.addEventListener('pointermove', seekFromEvent, {passive:true});
    stage.addEventListener('touchmove', seekFromEvent, {passive:true});
    stage.addEventListener('mouseenter', function(e){ seekFromEvent(e); }, {passive:true});
  }
  function init(){ qsa('[data-itp-vsl-retention-stage]').forEach(initRetentionStage); }
  if(document.readyState==='loading') document.addEventListener('DOMContentLoaded', init); else init();
  setTimeout(init, 600);
})();

/* v0.18.196 — admin number counters. Admin UI only; VSL player core untouched. */
(function(){
  function fmt(n, decimals){
    var fixed = (decimals > 0) ? n.toFixed(decimals) : Math.round(n).toString();
    var parts = fixed.split('.');
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    return parts.join('.');
  }
  function animate(el){
    if(!el || el.__itpCounted) return;
    el.__itpCounted = true;
    var to = parseFloat(el.getAttribute('data-itp-count-to') || '0');
    if(!isFinite(to)) to = 0;
    var decimals = parseInt(el.getAttribute('data-itp-count-decimals') || '0', 10);
    if(!isFinite(decimals) || decimals < 0) decimals = 0;
    var prefix = el.getAttribute('data-itp-count-prefix') || '';
    var suffix = el.getAttribute('data-itp-count-suffix') || '';
    var start = 0;
    var dur = 950 + Math.min(750, Math.abs(to) * 12);
    var t0 = performance.now();
    function tick(now){
      var p = Math.min(1, (now - t0) / dur);
      var eased = 1 - Math.pow(1 - p, 3);
      el.textContent = prefix + fmt(start + ((to - start) * eased), decimals) + suffix;
      if(p < 1) requestAnimationFrame(tick);
    }
    requestAnimationFrame(tick);
  }
  function init(){
    var els = Array.prototype.slice.call(document.querySelectorAll('[data-itp-count-up]'));
    if(!els.length) return;
    if('IntersectionObserver' in window){
      var io = new IntersectionObserver(function(entries){
        entries.forEach(function(entry){ if(entry.isIntersecting){ animate(entry.target); io.unobserve(entry.target); } });
      }, {threshold:0.15});
      els.forEach(function(el){ io.observe(el); });
    } else {
      els.forEach(animate);
    }
  }
  if(document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init); else init();
  setTimeout(init, 500);
})();


/* v0.18.197 — Command Orbit hover depth. Admin UI only; VSL player core untouched. */
(function(){
  function initOrbit(stage){
    if(!stage || stage.__itpOrbitInit) return;
    stage.__itpOrbitInit = true;
    if(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    var cards = Array.prototype.slice.call(stage.querySelectorAll('.itp-command-card-v2'));
    cards.forEach(function(card, i){
      card.style.setProperty('--delay', (i * 0.23).toFixed(2) + 's');
      card.setAttribute('data-itp-orbit-ready','1');
    });
    stage.addEventListener('mousemove', function(ev){
      var rect = stage.getBoundingClientRect();
      var px = ((ev.clientX - rect.left) / rect.width) - 0.5;
      var py = ((ev.clientY - rect.top) / rect.height) - 0.5;
      stage.style.setProperty('--itp-orbit-x', (px * 12).toFixed(2) + 'px');
      stage.style.setProperty('--itp-orbit-y', (py * 10).toFixed(2) + 'px');
      cards.forEach(function(card, idx){
        var depth = 1 + (idx * .12);
        card.style.translate = (px * 8 * depth).toFixed(2) + 'px ' + (py * 6 * depth).toFixed(2) + 'px';
      });
    });
    stage.addEventListener('mouseleave', function(){
      cards.forEach(function(card){ card.style.translate = ''; });
    });
  }
  function init(){ document.querySelectorAll('[data-itp-command-orbit]').forEach(initOrbit); }
  if(document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init); else init();
  setTimeout(init, 600);
})();

/* v0.18.198 — Real Command Motion. Admin UI only; VSL player core untouched. */
(function(){
  function reducedMotion(){
    return !!(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches);
  }
  function initRealMotion(stage){
    if(!stage || stage.__itpRealCommandMotion) return;
    stage.__itpRealCommandMotion = true;
    stage.setAttribute('data-itp-motion-step','0');
    if(reducedMotion()) return;
    var step = 0;
    var timer = null;
    function advance(){
      step = (step + 1) % 4;
      stage.setAttribute('data-itp-motion-step', String(step));
    }
    window.setTimeout(advance, 650);
    timer = window.setInterval(advance, 2200);
    stage.addEventListener('mouseenter', function(){
      stage.classList.add('is-motion-paused');
      if(timer){ window.clearInterval(timer); timer = null; }
    });
    stage.addEventListener('mouseleave', function(){
      stage.classList.remove('is-motion-paused');
      if(!timer) timer = window.setInterval(advance, 2200);
    });
    document.addEventListener('visibilitychange', function(){
      if(document.hidden && timer){ window.clearInterval(timer); timer = null; }
      if(!document.hidden && !timer && !stage.classList.contains('is-motion-paused')) timer = window.setInterval(advance, 2200);
    });
  }
  function init(){
    document.querySelectorAll('[data-itp-command-orbit]').forEach(initRealMotion);
  }
  if(document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init); else init();
  setTimeout(init, 700);
})();

/* v0.18.199 — Cinematic Command Hero tuning. Admin UI only; VSL player core untouched. */
(function(){
  function initCinematic(stage){
    if(!stage || stage.__itpCinematicCommand) return;
    stage.__itpCinematicCommand = true;
    stage.classList.add('itp-command-cinematic-ready');
    var cards = Array.prototype.slice.call(stage.querySelectorAll('.itp-command-card-v2'));
    cards.forEach(function(card, index){ card.style.setProperty('--cinematic-index', String(index)); });
  }
  function init(){ document.querySelectorAll('[data-itp-command-orbit]').forEach(initCinematic); }
  if(document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init); else init();
  setTimeout(init, 800);
})();


/* v0.18.200 — Premium Cards System motion. Admin UI only; VSL player core untouched. */
(function(){
  function init(board){
    if(!board || board.__itpFeatureBoard) return;
    board.__itpFeatureBoard = true;
    var cards = Array.prototype.slice.call(board.querySelectorAll('.itp-feature-card'));
    if(!cards.length) return;
    var reduced = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if(!reduced){
      var index = 0;
      cards[index % cards.length].classList.add('is-lifted');
      setInterval(function(){
        cards.forEach(function(card){ card.classList.remove('is-lifted'); });
        index = (index + 1) % cards.length;
        cards[index].classList.add('is-lifted');
      }, 2200);
    }
    cards.forEach(function(card){
      card.addEventListener('mousemove', function(ev){
        if(reduced) return;
        var r = card.getBoundingClientRect();
        var x = (ev.clientX - r.left) / Math.max(1, r.width) - 0.5;
        var y = (ev.clientY - r.top) / Math.max(1, r.height) - 0.5;
        card.style.transform = 'translateY(-8px) rotateX(' + (-y * 6).toFixed(2) + 'deg) rotateY(' + (x * 7).toFixed(2) + 'deg)';
      });
      card.addEventListener('mouseleave', function(){ card.style.transform = ''; });
    });
  }
  function boot(){ document.querySelectorAll('[data-itp-feature-board]').forEach(init); }
  if(document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot();
})();


/* v0.18.201 — Real SaaS Dashboard Engine micro-interactions. Admin only; VSL core untouched. */
(function(){
  function boot(engine){
    if(!engine || engine.__itpSaasEngine) return;
    engine.__itpSaasEngine = true;
    engine.classList.add('is-ready');
    var reduced = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if(reduced) return;
    Array.prototype.slice.call(engine.querySelectorAll('.itp-saas-kpi,.itp-saas-chart-card,.itp-saas-table-card,.itp-saas-radial-card,.itp-saas-source-card')).forEach(function(card){
      card.classList.add('itp-saas-tilt');
      card.addEventListener('mousemove', function(ev){
        var r = card.getBoundingClientRect();
        var x = (ev.clientX - r.left) / Math.max(1, r.width) - 0.5;
        var y = (ev.clientY - r.top) / Math.max(1, r.height) - 0.5;
        card.style.transform = 'translateY(-6px) rotateX(' + (-y * 4).toFixed(2) + 'deg) rotateY(' + (x * 5).toFixed(2) + 'deg)';
      });
      card.addEventListener('mouseleave', function(){ card.style.transform = ''; });
    });
  }
  function init(){ document.querySelectorAll('[data-itp-saas-engine]').forEach(boot); }
  if(document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init); else init();
  setTimeout(init, 700);
})();

// v0.18.204 — Destructive metrics reset confirmation modal. Admin only; VSL core untouched.
(function(){
  var activeLink = null;
  var modal = null;

  function labelFor(link){
    var raw = link.getAttribute('data-itp-reset-label') || (link.textContent ? link.textContent.trim() : 'metrics');
    var map = {
      all: 'all metrics',
      cards: 'Cards metrics',
      cookie: 'Cookie metrics',
      vsl_video: 'VSL / Video metrics',
      vsl_landing: 'VSL + Landing metrics',
      bridge: 'this bridge metrics'
    };
    var scope = link.getAttribute('data-itp-reset-scope') || link.getAttribute('data-itp-reset-confirm') || '';
    return map[scope] || raw || 'metrics';
  }

  function ensureModal(){
    if (modal) return modal;
    modal = document.createElement('div');
    modal.className = 'itp-reset-modal-backdrop';
    modal.innerHTML = '' +
      '<div class="itp-reset-modal" role="dialog" aria-modal="true" aria-labelledby="itp-reset-modal-title">' +
        '<button type="button" class="itp-reset-modal-x" data-itp-reset-cancel aria-label="Cancel">×</button>' +
        '<span class="itp-kicker">Confirmation required</span>' +
        '<h3 id="itp-reset-modal-title">Are you sure you want to reset these metrics?</h3>' +
        '<p data-itp-reset-message>This will permanently delete the selected metrics data.</p>' +
        '<label>To confirm, type <strong>DELETE</strong><input type="text" data-itp-reset-input placeholder="type DELETE here" autocomplete="off"></label>' +
        '<div class="itp-reset-modal-actions">' +
          '<button type="button" class="itp-btn itp-btn-ghost" data-itp-reset-cancel>Cancel</button>' +
          '<button type="button" class="itp-btn itp-reset-confirm-button" data-itp-reset-go disabled>Reset metrics</button>' +
        '</div>' +
      '</div>';
    document.body.appendChild(modal);
    var input = modal.querySelector('[data-itp-reset-input]');
    var go = modal.querySelector('[data-itp-reset-go]');
    function close(){
      modal.classList.remove('is-open');
      activeLink = null;
      if (input) input.value = '';
      if (go) go.disabled = true;
    }
    modal.querySelectorAll('[data-itp-reset-cancel]').forEach(function(btn){ btn.addEventListener('click', close); });
    modal.addEventListener('click', function(ev){ if(ev.target === modal) close(); });
    document.addEventListener('keydown', function(ev){ if(ev.key === 'Escape' && modal.classList.contains('is-open')) close(); });
    input.addEventListener('input', function(){
      go.disabled = input.value.trim().toLowerCase() !== 'delete';
    });
    go.addEventListener('click', function(){
      if (!activeLink || input.value.trim().toLowerCase() !== 'delete') return;
      try {
        var targetUrl = activeLink.getAttribute('data-itp-reset-url') || activeLink.href;
        var url = new URL(targetUrl, window.location.href);
        url.searchParams.set('itp_reset_confirm', 'delete');
        window.location.href = url.toString();
      } catch(err) {
        var fallbackUrl = activeLink.getAttribute('data-itp-reset-url') || activeLink.href;
        window.location.href = fallbackUrl + (fallbackUrl.indexOf('?') === -1 ? '?' : '&') + 'itp_reset_confirm=delete';
      }
    });
    return modal;
  }

  function openModal(link){
    activeLink = link;
    var m = ensureModal();
    var label = labelFor(link);
    var msg = m.querySelector('[data-itp-reset-message]');
    var input = m.querySelector('[data-itp-reset-input]');
    var go = m.querySelector('[data-itp-reset-go]');
    if (msg) msg.textContent = 'This will permanently reset ' + label + '. Charts and reports for this scope will start from zero.';
    if (input) input.value = '';
    if (go) go.disabled = true;
    m.classList.add('is-open');
    setTimeout(function(){ if(input) input.focus(); }, 50);
  }

  function attachResetConfirm(){
    document.querySelectorAll('[data-itp-reset-url]').forEach(function(link){
      if (link.dataset.itpResetBound === '1') return;
      link.dataset.itpResetBound = '1';
      link.addEventListener('click', function(e){
        e.preventDefault();
        openModal(link);
        return false;
      });
    });
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', attachResetConfirm); else attachResetConfirm();
})();

/* Invalid Traffic 0.18.224 - Pixels / Conversions repeaters */
(function(){
  'use strict';
  function qs(sel, ctx){ return (ctx || document).querySelector(sel); }
  function qsa(sel, ctx){ return Array.prototype.slice.call((ctx || document).querySelectorAll(sel)); }
  function esc(s){ return String(s || '').replace(/[&<>"']/g, function(c){ return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c]; }); }
  function nextIndex(list, rowSelector){
    var max = -1;
    qsa(rowSelector, list).forEach(function(row){
      qsa('input,textarea,select', row).forEach(function(el){
        var m = String(el.name || '').match(/\[(\d+)\]/);
        if(m) max = Math.max(max, parseInt(m[1],10));
      });
    });
    return max + 1;
  }
  function pixelRow(i){
    return ''+
    '<div class="itp-pixel-row" data-itp-custom-pixel-row>'+
      '<div class="itp-repeater-row-head">'+
        '<strong>Custom pixel</strong>'+
        '<label class="itp-mini-switch"><input type="checkbox" name="custom_pixels['+i+'][enabled]" value="1" checked><span></span> Enabled</label>'+
        '<button type="button" class="itp-btn itp-btn-light" data-itp-remove-repeater-row>Remove</button>'+
      '</div>'+
      '<div class="itp-form-grid two">'+
        '<label>Pixel name<input name="custom_pixels['+i+'][name]" placeholder="Ex: Taboola base, Microsoft UET, Meta"></label>'+
        '<label>Placement<select name="custom_pixels['+i+'][placement]"><option value="head">Head</option><option value="footer">Footer / body</option></select></label>'+
      '</div>'+
      '<label>Pixel code<textarea class="itp-code-area" name="custom_pixels['+i+'][code]" placeholder="Paste the pixel script here."></textarea></label>'+
    '</div>';
  }
  function conversionRow(i){
    return ''+
    '<div class="itp-conversion-row" data-itp-conversion-event-row>'+
      '<div class="itp-repeater-row-head">'+
        '<strong>Conversion rule</strong>'+
        '<label class="itp-mini-switch"><input type="checkbox" name="conversion_events['+i+'][enabled]" value="1" checked><span></span> Enabled</label>'+
        '<label class="itp-mini-switch"><input type="checkbox" name="conversion_events['+i+'][internal]" value="1" checked><span></span> Save as Invalid Traffic conversion</label>'+
        '<button type="button" class="itp-btn itp-btn-light" data-itp-remove-repeater-row>Remove</button>'+
      '</div>'+
      '<div class="itp-form-grid four">'+
        '<label>Event name<input name="conversion_events['+i+'][name]" placeholder="Ex: Purchase, Subscribe, Checkout"></label>'+
        '<label>Trigger<select name="conversion_events['+i+'][trigger]">'+
          '<option value="page_view">Thank-you / URL match</option>'+
          '<option value="lead_submit" selected>Lead submitted</option>'+
          '<option value="vsl_cta_click">VSL CTA clicked</option>'+
          '<option value="click">Any bridge click</option>'+
          '<option value="vsl_play">VSL play</option>'+
          '<option value="vsl_50">VSL watched 50%</option>'+
          '<option value="vsl_100">VSL watched 100%</option>'+
          '<option value="conversion">Manual JS conversion</option>'+
          '<option value="lead_view">Lead popup opened</option>'+
          '<option value="lead_redirect">Lead redirect</option>'+
          '<option value="vsl_cta_view">VSL CTA appeared</option>'+
        '</select></label>'+
        '<label>Value optional<input name="conversion_events['+i+'][value]" placeholder="Ex: 29.90"></label>'+
        '<label>Currency<input name="conversion_events['+i+'][currency]" value="USD" placeholder="USD"></label>'+
      '</div>'+
      '<label>URL contains optional<input name="conversion_events['+i+'][url_contains]" placeholder="Ex: /thank-you/ or /success.php. Used mainly with URL match."></label>'+
      '<label>Custom conversion JavaScript<textarea class="itp-code-area" name="conversion_events['+i+'][code]" placeholder="Example: _tfa.push({notify:\'event\', name:\'make_purchase\', id:123}); or window.uetq.push(\'event\',\'purchase\',{});"></textarea></label>'+
    '</div>';
  }
  document.addEventListener('click', function(e){
    var addPixel = e.target.closest('[data-itp-add-custom-pixel]');
    if(addPixel){
      e.preventDefault();
      var wrap = addPixel.closest('[data-itp-custom-pixels]');
      var list = qs('[data-itp-custom-pixel-list]', wrap);
      if(!list) return;
      list.insertAdjacentHTML('beforeend', pixelRow(nextIndex(list, '[data-itp-custom-pixel-row]')));
      return;
    }
    var addConv = e.target.closest('[data-itp-add-conversion-event]');
    if(addConv){
      e.preventDefault();
      var cwrap = addConv.closest('[data-itp-conversion-events]');
      var clist = qs('[data-itp-conversion-event-list]', cwrap);
      if(!clist) return;
      clist.insertAdjacentHTML('beforeend', conversionRow(nextIndex(clist, '[data-itp-conversion-event-row]')));
      return;
    }
    var remove = e.target.closest('[data-itp-remove-repeater-row]');
    if(remove){
      e.preventDefault();
      var row = remove.closest('[data-itp-custom-pixel-row], [data-itp-conversion-event-row]');
      if(row) row.remove();
    }
  });
})();

/* Invalid Traffic 0.18.229 - Global pixel/webhook test center */
(function(){
  'use strict';

  function syncPixelTestAnalyticsLink(root){
    root = root || document;
    var bridge = root.querySelector('[data-itp-pixel-test-bridge]');
    var link = root.querySelector('[data-itp-pixel-test-open-analytics]');
    if(!bridge || !link) return;
    var base = link.getAttribute('data-base') || '';
    if(base){ link.href = base + encodeURIComponent(bridge.value || '0'); }
  }

  document.addEventListener('change', function(e){
    if(!e.target || !e.target.matches('[data-itp-pixel-test-bridge]')) return;
    syncPixelTestAnalyticsLink(e.target.closest('.itp-pixel-test-card') || document);
  });

  document.addEventListener('click', function(e){
    var btn = e.target.closest('[data-itp-admin-pixel-test]');
    if(!btn) return;
    e.preventDefault();
    var root = btn.closest('.itp-pixel-test-card') || document;
    var status = root.querySelector('[data-itp-pixel-test-status]');
    var bridge = root.querySelector('[data-itp-pixel-test-bridge]');
    var name = root.querySelector('[data-itp-pixel-test-name]');
    var source = root.querySelector('[data-itp-pixel-test-source]');
    var external = root.querySelector('[data-itp-pixel-test-external]');
    var value = root.querySelector('[data-itp-pixel-test-value]');
    var currency = root.querySelector('[data-itp-pixel-test-currency]');
    var openLink = root.querySelector('[data-itp-pixel-test-open-analytics]');
    syncPixelTestAnalyticsLink(root);
    if(status) status.textContent = 'Sending webhook-style test delivery...';
    btn.disabled = true;
    var fd = new FormData();
    fd.append('action', 'itp_admin_pixel_test');
    fd.append('nonce', btn.getAttribute('data-nonce') || '');
    fd.append('presell_id', bridge ? bridge.value : '0');
    fd.append('event_name', name ? name.value : 'purchase_test');
    fd.append('source', source ? source.value : 'pixel-test');
    fd.append('external_id', external ? external.value : ('TEST-' + Date.now()));
    fd.append('value', value ? value.value : '');
    fd.append('currency', currency ? currency.value : 'USD');
    fetch(btn.getAttribute('data-ajax') || ajaxurl, {method:'POST', body:fd, 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) || 'Test failed.'); }
        if(status) status.textContent = res.data.message || 'Webhook test received. No analytics conversion was created.';
        var resultBridge = res.data && res.data.result && res.data.result.bridge_id ? String(res.data.result.bridge_id) : (bridge ? bridge.value : '');
        if(openLink && resultBridge){
          var base = openLink.getAttribute('data-base') || '';
          if(base) openLink.href = base + encodeURIComponent(resultBridge);
        }
      })
      .catch(function(err){ if(status) status.textContent = (err && err.message) ? err.message : 'Test failed.'; })
      .finally(function(){ btn.disabled = false; });
  });

  document.addEventListener('DOMContentLoaded', function(){
    document.querySelectorAll('.itp-pixel-test-card').forEach(syncPixelTestAnalyticsLink);
  });
})();

/* Invalid Traffic 0.18.229 - source cards copy + test shortcuts */
(function(){
  'use strict';
  function closestField(btn){
    var box = btn.closest('.itp-source-card,.itp-source-endpoint-panel,.itp-pixel-sources-panel');
    if(!box) return null;
    var target = btn.getAttribute('data-itp-copy-target');
    if(target){
      var explicit = box.querySelector(target);
      if(explicit) return explicit;
    }
    var fields = Array.prototype.slice.call(box.querySelectorAll('.itp-copy-field,.itp-source-url'));
    var before = fields.filter(function(field){
      return !!(field.compareDocumentPosition(btn) & Node.DOCUMENT_POSITION_FOLLOWING);
    });
    if(before.length) return before[before.length - 1];
    return fields[0] || null;
  }
  document.addEventListener('click', function(e){
    var copy = e.target.closest('[data-itp-copy-nearest]');
    if(copy){
      e.preventDefault();
      var field = closestField(copy);
      var text = field ? (field.value || field.textContent || '') : '';
      if(!text) return;
      var original = copy.textContent;
      if(navigator.clipboard && navigator.clipboard.writeText){
        navigator.clipboard.writeText(text).then(function(){ copy.textContent = 'Copied'; setTimeout(function(){ copy.textContent = original; }, 1200); });
      } else {
        if(field && field.select) field.select();
        document.execCommand('copy');
        copy.textContent = 'Copied'; setTimeout(function(){ copy.textContent = original; }, 1200);
      }
      return;
    }
    var sourceTest = e.target.closest('[data-itp-source-test]');
    if(sourceTest){
      e.preventDefault();
      var card = document.querySelector('.itp-pixel-test-card');
      if(!card) return;
      var source = card.querySelector('[data-itp-pixel-test-source]');
      var name = card.querySelector('[data-itp-pixel-test-name]');
      var external = card.querySelector('[data-itp-pixel-test-external]');
      if(source) source.value = sourceTest.getAttribute('data-itp-source-test') || 'pixel-test';
      if(name) name.value = sourceTest.getAttribute('data-itp-source-event') || 'purchase_test';
      if(external) external.value = 'TEST-' + Date.now();
      card.scrollIntoView({behavior:'smooth', block:'center'});
      var send = card.querySelector('[data-itp-admin-pixel-test]');
      if(send) setTimeout(function(){ send.focus(); }, 350);
    }
  });
})();
