(function(){
  'use strict';
  var cfg = window.ITP_GLOBAL_PIXEL || {};
  if(!cfg.ajax) return;

  var storage = window.localStorage || null;
  var fired = {};
  function readTouch(){
    try{
      if(storage){
        var raw = storage.getItem('itp_last_touch');
        if(raw){
          var data = JSON.parse(raw);
          if(data && data.bridgeId && data.ajax && (!data.expires || Date.now() <= Number(data.expires))) return data;
        }
      }
    }catch(e){}
    try{
      var p = new URLSearchParams(window.location.search || '');
      var id = p.get('itp_bridge') || p.get('itp_bid') || p.get('bridge_id') || p.get('presell_id');
      if(!id) return null;
      return {
        bridgeId: id,
        nonce: cfg.nonce || '',
        ajax: cfg.ajax,
        sessionId: p.get('itp_session') || '',
        visitorId: p.get('itp_visitor') || '',
        source: p.get('utm_source') || 'url-param',
        medium: p.get('utm_medium') || '',
        campaign: p.get('utm_campaign') || '',
        content: p.get('utm_content') || '',
        term: p.get('utm_term') || '',
        referrer: document.referrer || '',
        landingUrl: location.href,
        destination: '',
        url: location.href,
        expires: Date.now() + (24 * 60 * 60 * 1000)
      };
    }catch(err){ return null; }
  }
  function params(){ return new URLSearchParams(window.location.search || ''); }
  function detectDevice(){
    var ua = navigator.userAgent || '';
    if(/Mobi|Android|iPhone|iPad/i.test(ua)) return 'mobile';
    if(/Tablet|iPad/i.test(ua)) return 'tablet';
    return 'desktop';
  }
  function browser(){
    var ua = navigator.userAgent || '';
    if(/Edg\//.test(ua)) return 'Edge';
    if(/Chrome\//.test(ua)) return 'Chrome';
    if(/Safari\//.test(ua) && !/Chrome\//.test(ua)) return 'Safari';
    if(/Firefox\//.test(ua)) return 'Firefox';
    return 'Other';
  }
  function os(){
    var ua = navigator.userAgent || '';
    if(/Windows/i.test(ua)) return 'Windows';
    if(/Android/i.test(ua)) return 'Android';
    if(/iPhone|iPad|iOS/i.test(ua)) return 'iOS';
    if(/Mac OS/i.test(ua)) return 'macOS';
    if(/Linux/i.test(ua)) return 'Linux';
    return 'Other';
  }
  function encode(obj){
    var fd = new FormData();
    Object.keys(obj).forEach(function(k){ fd.append(k, obj[k]); });
    return fd;
  }
  function rules(){ return Array.isArray(cfg.rules) ? cfg.rules : []; }
  function buildPayload(name, opts){
    opts = opts || {};
    var touch = readTouch();
    if(!touch) return null;
    var p = params();
    var eventName = opts.name || opts.eventName || name || p.get('event') || p.get('event_name') || 'conversion';
    var value = opts.value;
    if(value === undefined || value === null || value === '') value = p.get('value') || p.get('amount') || p.get('price') || '';
    var currency = opts.currency || p.get('currency') || p.get('currency_code') || 'USD';
    var externalId = opts.external_id || opts.externalId || opts.order_id || opts.orderId || opts.transaction || p.get('external_id') || p.get('order_id') || p.get('transaction') || p.get('transaction_id') || '';
    var destination = String(opts.destination || eventName || 'conversion');
    if(value !== '') destination += '|value=' + String(value);
    if(currency) destination += '|currency=' + String(currency).toUpperCase();
    if(externalId) destination += '|external_id=' + String(externalId);
    return {
      action: 'itp_track_event',
      nonce: cfg.nonce || touch.nonce || '',
      public_token: cfg.publicToken || cfg.public_token || '',
      presell_id: touch.bridgeId,
      event_type: 'conversion',
      event_name: eventName,
      session_id: touch.sessionId || '',
      visitor_id: touch.visitorId || '',
      source: p.get('utm_source') || opts.source || touch.source || 'last-touch',
      medium: p.get('utm_medium') || opts.medium || touch.medium || '',
      campaign: p.get('utm_campaign') || opts.campaign || touch.campaign || '',
      content: p.get('utm_content') || opts.content || touch.content || '',
      term: p.get('utm_term') || opts.term || touch.term || '',
      referrer: document.referrer || touch.referrer || '',
      landing_url: location.href,
      destination: destination,
      value: value,
      currency: currency,
      external_id: externalId,
      device: detectDevice(),
      browser: browser(),
      os: os(),
      screen: (screen.width || 0)+'x'+(screen.height || 0),
      language: navigator.language || '',
      timezone: (Intl.DateTimeFormat().resolvedOptions().timeZone || ''),
      scroll_depth: '0',
      time_on_page: '0'
    };
  }
  function publicContext(payload, opts){
    opts = opts || {};
    var touch = readTouch() || {};
    return {
      bridgeId: touch.bridgeId || payload.presell_id || '',
      bridgeTitle: '',
      eventName: opts.name || 'conversion',
      destination: payload.destination || '',
      source: payload.source || '',
      medium: payload.medium || '',
      campaign: payload.campaign || '',
      content: payload.content || '',
      term: payload.term || '',
      sessionId: payload.session_id || '',
      visitorId: payload.visitor_id || '',
      landingUrl: touch.landingUrl || '',
      conversionUrl: location.href,
      url: location.href,
      value: opts.value || '',
      currency: opts.currency || 'USD'
    };
  }
  function dispatch(name, ctx){
    try{
      document.dispatchEvent(new CustomEvent('itp:conversion', {detail: ctx}));
      document.dispatchEvent(new CustomEvent('itp:' + String(name || 'conversion'), {detail: ctx}));
    }catch(e){}
  }
  function ruleMatches(rule, eventName){
    if(!rule) return false;
    var trigger = String(rule.trigger || '').trim() || 'conversion';
    var needle = String(rule.urlContains || rule.url_contains || '').trim();
    var hay = String(location.href || '') + ' ' + String(location.pathname || '');
    if(trigger === 'page_view') return !needle || hay.indexOf(needle) !== -1;
    if(trigger === 'conversion') return true;
    if(eventName && trigger === eventName) return true;
    return false;
  }
  function runRules(eventName, payload, opts){
    var matched = false;
    rules().forEach(function(rule, idx){
      if(!ruleMatches(rule, eventName)) return;
      var key = String(rule.id || rule.name || 'rule') + '_' + idx + '_' + eventName + '_' + location.href;
      if(fired[key]) return;
      fired[key] = true;
      matched = true;
      if(rule.code){
        try{
          var ctx = publicContext(payload, {name:eventName, value:opts.value || rule.value || '', currency:opts.currency || rule.currency || 'USD'});
          var cleanCode = String(rule.code).replace(/<\/?script[^>]*>/gi, '');
          var fn = new Function('eventName','destination','value','currency','ctx', cleanCode);
          fn.call(window, eventName || 'conversion', payload.destination || '', opts.value || rule.value || '', opts.currency || rule.currency || 'USD', ctx);
        }catch(err){
          try{ if(window.console && console.warn) console.warn('[Invalid Traffic] Global conversion rule failed:', rule.name || key, err); }catch(e){}
        }
      }
    });
    return matched;
  }
  function sendConversion(input){
    var opts = {};
    if(typeof input === 'object' && input){ opts = input; }
    else { opts.name = input || 'conversion'; }
    var p = params();
    var name = opts.name || opts.eventName || p.get('event') || p.get('event_name') || 'conversion';
    var payload = buildPayload(name, opts);
    if(!payload) return Promise.resolve({ok:false, reason:'no_last_touch'});
    var ctx = publicContext(payload, opts);
    dispatch(name, ctx);
    runRules(name, payload, opts);
    return fetch((readTouch() || {}).ajax || cfg.ajax, {method:'POST', body:encode(payload), credentials:'same-origin'})
      .then(function(r){ return r.json().catch(function(){ return {}; }); })
      .then(function(res){ return {ok: !!(res && res.success), response: res}; })
      .catch(function(err){ return {ok:false, error: err}; });
  }

  if(!window.ITPTrackConversion){
    window.ITPTrackConversion = sendConversion;
  }
  window.ITPGlobalTrackConversion = sendConversion;

  setTimeout(function(){
    if(window.ITP_TRACK && window.ITP_TRACK.id) return;
    if(cfg.autoUrl === false) return;
    var touch = readTouch();
    if(!touch) return;
    var urlRules = rules().filter(function(rule){ return String(rule.trigger || '') === 'page_view'; });
    if(!urlRules.length) return;
    var payload = buildPayload('url_match', {name:'url_match'});
    if(!payload) return;
    var matched = false;
    urlRules.forEach(function(rule){ if(ruleMatches(rule, 'url_match')) matched = true; });
    if(!matched) return;
    sendConversion({name:'url_match', destination:location.href});
  }, 120);
})();
