/**
 * UTM & Click ID Capture
 * Reads tracking params from window.location.search on entry and persists
 * them to localStorage + sessionStorage so they survive navigation and
 * are available later at checkout (read by getUtmParams in wiinpay-checkout.js).
 */
(function () {
  try {
    var KEYS = [
      'utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term',
      'fbclid', 'ttclid', 'click_id',
      'gclid', 'gbraid', 'wbraid',
      'src', 'sck', 'xcod'
    ];

    var params = new URLSearchParams(window.location.search || '');
    var captured = 0;

    KEYS.forEach(function (key) {
      var value = params.get(key);
      if (value && value.length > 0 && value.length < 2048) {
        try { localStorage.setItem(key, value); } catch (e) {}
        try { sessionStorage.setItem(key, value); } catch (e) {}
        captured++;
      }
    });

    // Persist the full raw query string too (useful for debugging / replay)
    var raw = (window.location.search || '').replace(/^\?/, '');
    if (raw) {
      try { localStorage.setItem('utm_raw_query', raw); } catch (e) {}
      try { sessionStorage.setItem('utm_raw_query', raw); } catch (e) {}
    }

    // Stamp the first-touch timestamp once
    try {
      if (!localStorage.getItem('utm_first_seen_at')) {
        localStorage.setItem('utm_first_seen_at', String(Date.now()));
      }
    } catch (e) {}

    if (captured > 0 && window.console && console.debug) {
      console.debug('[utm-capture] persisted', captured, 'tracking params');
    }
  } catch (err) {
    // Silently ignore — never break the page over analytics
  }
})();
