/**
 * Klaviyo-Webflow Integration (Intelligent Redirector)
 * @version 1.0.3
 * @license MIT
 */
(function() {
  // Function to construct the correct script URL based on environment and version
  function getScriptUrl() {
    try {
      // Get current script URL
      var currentScript = document.currentScript || (function() {
        var scripts = document.getElementsByTagName('script');
        return scripts[scripts.length - 1];
      })();
      
      var currentSrc = currentScript.src || '';
      var baseUrl;
      
      // Extract base URL (everything up to /api/script)
      if (currentSrc.includes('/api/script')) {
        baseUrl = currentSrc.substring(0, currentSrc.indexOf('/api/script'));
        return baseUrl + '/api/script/latest';
      } else {
        // For direct file access
        var pathParts = currentSrc.split('/');
        pathParts.pop(); // Remove last part
        baseUrl = pathParts.join('/');
        return baseUrl + '/versions/latest.js';
      }
    } catch (e) {
      console.error('[Klaviyo-Webflow] Error constructing script URL:', e);
      return 'https://klaviyo-webflow-nextjs.vercel.app/api/script/latest';
    }
  }
  
  // Get the correct URL based on environment
  var scriptUrl = getScriptUrl();
  
  // Create and append the script
  var script = document.createElement('script');
  script.src = scriptUrl;
  script.async = true;
  
  // Copy attributes from current script
  if (document.currentScript) {
    try {
      var attrs = document.currentScript.attributes;
      for (var i = 0; i < attrs.length; i++) {
        var attr = attrs[i];
        if (attr.name !== 'src' && attr.name !== 'id') {
          script.setAttribute(attr.name, attr.value);
        }
      }
    } catch (e) {
      console.error('[Klaviyo-Webflow] Error copying attributes:', e);
    }
  }
  
  // Add error handler
  script.onerror = function() {
    console.error('[Klaviyo-Webflow] Failed to load integration script');
    console.log('[Klaviyo-Webflow] Try accessing directly: https://klaviyo-webflow-nextjs.vercel.app/api/script/latest');
    
    // Fire an event that can be listened to
    if (typeof CustomEvent === 'function') {
      document.dispatchEvent(new CustomEvent('klaviyoWebflowLoadError'));
    }
  };
  
  // Add load handler
  script.onload = function() {
    console.info('[Klaviyo-Webflow] Successfully loaded integration script');
    
    // Fire an event that can be listened to
    if (typeof CustomEvent === 'function') {
      document.dispatchEvent(new CustomEvent('klaviyoWebflowLoaded'));
    }
  };
  
  // Append to document
  document.head.appendChild(script);
})();