/**
 * Conectia Tracking Script
 *
 * Captures the affiliate click id (?ref= / ?conectid=) from the landing URL and
 * attaches it to the Shopify cart as a cart attribute so it flows through to the
 * order (read back as a note_attribute server-side).
 *
 * Attribution uses Shopify's own same-origin AJAX cart API (POST /cart/update.js)
 * plus a hidden input on any cart <form>. It does NOT override window.fetch or
 * XMLHttpRequest and does not read any customer input — it only ever handles the
 * click id it captured from the URL.
 */

(function() {
  'use strict';

  var COOKIE_NAME    = 'conectia_tracking_id';
  var COOKIE_DAYS    = 30;
  var ATTRIBUTE_NAME = 'conectid'; // cart attribute name
  var URL_PARAM      = 'ref';      // ?ref= is the ConectID

  // Get conectid from URL parameter
  function getUrlParameter(name) {
    var urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name);
  }

  // Set cookie
  function setCookie(name, value, days) {
    var expires = '';
    if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      expires = '; expires=' + date.toUTCString();
    }
    document.cookie = name + '=' + (value || '') + expires + '; path=/; SameSite=Lax';
  }

  // Get cookie
  function getCookie(name) {
    var nameEQ = name + '=';
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) === ' ') c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
  }

  // Capture conectid from the URL (?ref= or ?conectid=) and store it
  var conectidFromUrl = getUrlParameter(URL_PARAM) || getUrlParameter(ATTRIBUTE_NAME);
  if (conectidFromUrl) {
    setCookie(COOKIE_NAME, conectidFromUrl, COOKIE_DAYS);
    try { sessionStorage.setItem(COOKIE_NAME, conectidFromUrl); } catch (e) {}
  }

  // Get stored conectid
  var storedConectId = null;
  try { storedConectId = sessionStorage.getItem(COOKIE_NAME); } catch (e) {}
  storedConectId = storedConectId || getCookie(COOKIE_NAME);

  if (!storedConectId) {
    return; // No conectid to track
  }

  // Primary: set the cart attribute directly via Shopify's own AJAX cart API.
  // This is an ordinary same-origin request to the store — no interception of
  // fetch/XHR — and persists the attribute onto every subsequent add/checkout.
  function setCartAttribute() {
    if (typeof fetch !== 'function') return;
    try {
      var attrs = {};
      attrs[ATTRIBUTE_NAME] = storedConectId;
      fetch('/cart/update.js', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ attributes: attrs })
      }).catch(function () {});
    } catch (e) {}
  }

  // Fallback: inject a hidden field into any cart <form> so a full-page cart
  // submit also carries the attribute on themes that post the cart directly.
  function injectIntoCartForms() {
    var cartForms = document.querySelectorAll('form[action*="/cart"]');
    cartForms.forEach(function(form) {
      if (!form.querySelector('[name="attributes[' + ATTRIBUTE_NAME + ']"]')) {
        var input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'attributes[' + ATTRIBUTE_NAME + ']';
        input.value = storedConectId;
        form.appendChild(input);
      }
    });
  }

  function init() {
    setCartAttribute();
    injectIntoCartForms();
  }

  // Initialize on DOM ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }

})();
