(function() {
  'use strict';

  // Detect base URL from script src
  var scriptEl = document.currentScript;
  var baseUrl = '';

  if (scriptEl && scriptEl.src) {
    // Extract base URL from the embed.js script location
    // e.g., https://journey.demand-iq.com/embed.js -> https://journey.demand-iq.com/
    baseUrl = scriptEl.src.replace(/embed\.js(\?.*)?$/, '');
  }

  // Fallback for browsers that don't support currentScript or async scenarios
  if (!baseUrl) {
    var scripts = document.getElementsByTagName('script');
    for (var i = 0; i < scripts.length; i++) {
      if (scripts[i].src && scripts[i].src.indexOf('embed.js') !== -1) {
        baseUrl = scripts[i].src.replace(/embed\.js(\?.*)?$/, '');
        break;
      }
    }
  }

  // Default to production if detection fails
  if (!baseUrl) {
    baseUrl = 'https://journey.demand-iq.com/';
  }

  // Fetch manifest with cache-busting timestamp
  var manifestUrl = baseUrl + 'manifest.json?_=' + Date.now();

  fetch(manifestUrl)
    .then(function(response) {
      if (!response.ok) {
        throw new Error('Manifest fetch failed: ' + response.status);
      }
      return response.json();
    })
    .then(function(manifest) {
      // Load JS files
      if (manifest.assets && manifest.assets.js) {
        manifest.assets.js.forEach(function(file) {
          var scriptEle = document.createElement('script');
          scriptEle.src = baseUrl + file;
          scriptEle.async = true;
          scriptEle.type = 'module';
          scriptEle.setAttribute('data-demand-iq', 'true');
          document.head.appendChild(scriptEle);
        });
      }

      // Load CSS files
      if (manifest.assets && manifest.assets.css) {
        manifest.assets.css.forEach(function(file) {
          var linkEle = document.createElement('link');
          linkEle.rel = 'stylesheet';
          linkEle.href = baseUrl + file;
          linkEle.setAttribute('data-demand-iq', 'true');
          document.head.appendChild(linkEle);
        });
      }
    })
    .catch(function(error) {
      console.error('[DemandIQ] Failed to load journey assets:', error);
      // Dispatch custom event for client-side error tracking
      window.dispatchEvent(new CustomEvent('demand-iq-load-error', { detail: error }));
    });
})();
