(function () {
  'use strict';

  // Idempotency guard: bail if embed.js has already executed on this page.
  // Loading it twice causes duplicate <script>/<link> injection and (under
  // deploy races) a second main bundle, which produces a React render loop.
  if (window.__diqEmbedLoaded) {
    console.warn(
      '[DemandIQ] embed.js was loaded more than once on this page. ' +
        'Remove the duplicate <script src=".../embed.js"> tag — ' +
        'including it twice can cause the journey to render in a loop.'
    );
    return;
  }
  window.__diqEmbedLoaded = true;

  // Performance telemetry — collect timing marks before React loads
  window.__diq_perf = [];
  window.__diq_perf.push({ name: 'diq:embed_start', startTime: performance.now() });

  // 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();

  window.__diq_perf.push({ name: 'diq:manifest_fetch_start', startTime: performance.now() });

  fetch(manifestUrl)
    .then(function (response) {
      if (!response.ok) {
        throw new Error('Manifest fetch failed: ' + response.status);
      }
      return response.json();
    })
    .then(function (manifest) {
      window.__diq_perf.push({ name: 'diq:manifest_fetch_end', startTime: performance.now() });

      // Warm TLS/DNS for the API + posthog origins before the bundle starts firing
      // the session/workflow/step and /flags requests.
      if (manifest.preconnect && manifest.preconnect.length) {
        manifest.preconnect.forEach(function (origin) {
          var pre = document.createElement('link');
          pre.rel = 'preconnect';
          pre.href = origin;
          pre.crossOrigin = 'anonymous';
          pre.setAttribute('data-demand-iq', 'true');
          document.head.appendChild(pre);
        });
      }

      // Preload the entry's eager vendor chunks so they download in parallel with
      // index-*.js instead of being discovered one round-trip later (waterfall).
      if (manifest.assets && manifest.assets.modulepreload) {
        manifest.assets.modulepreload.forEach(function (file) {
          var preload = document.createElement('link');
          preload.rel = 'modulepreload';
          preload.href = baseUrl + file;
          preload.setAttribute('data-demand-iq', 'true');
          document.head.appendChild(preload);
        });
      }

      // 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);
        });
      }

      window.__diq_perf.push({ name: 'diq:assets_inject', startTime: performance.now() });

      // 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);
        });
      }

      // Resolve feature flags early — straight from PostHog's /flags endpoint, in
      // parallel with the bundle download above — so the journey's flag-gated
      // workflow fetch isn't serialized behind the lazy ~189 KB posthog-js
      // library. The main bundle reads this promise from window.__diq_flags and
      // seeds it into its flag cache (utils/posthog.ts seedFeatureFlags). Fully
      // guarded: any failure leaves __diq_flags resolving to null and the bundle
      // falls back to posthog-js + the pending-flags safety timeout.
      try {
        var ph = manifest.posthog;
        if (ph && ph.key && ph.host) {
          var journeyEl = document.querySelector('[data-journey-id]') || document.getElementById('demand-iq-journey');
          var journeyId = journeyEl && journeyEl.getAttribute('data-journey-id');
          var companyId = journeyEl && journeyEl.getAttribute('data-company-id');
          if (journeyId || companyId) {
            var groups = {};
            if (journeyId) {
              groups.workflow = journeyId;
            }
            if (companyId) {
              groups.company = companyId;
            }
            // Mirror utils/posthog.ts readEarlyDistinctId: prefer posthog-js's
            // persisted id, then the fingerprint visitor id, then a throwaway anon
            // id (fine for the group-targeted web-leads-v2 flag).
            var distinctId = null;
            try {
              var stored = localStorage.getItem('ph_' + ph.key + '_posthog');
              if (stored) {
                distinctId = (JSON.parse(stored) || {}).distinct_id || null;
              }
              if (!distinctId) {
                distinctId = localStorage.getItem('userId');
              }
            } catch (e) {
              distinctId = null;
            }
            if (!distinctId) {
              distinctId = 'anon-' + Date.now() + '-' + Math.random().toString(36).slice(2);
            }
            window.__diq_flags = fetch(ph.host.replace(/\/$/, '') + '/flags/?v=2', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ token: ph.key, distinct_id: distinctId, groups: groups }),
            })
              .then(function (response) {
                return response.ok ? response.json() : null;
              })
              .then(function (data) {
                return data && data.featureFlags ? data.featureFlags : null;
              })
              .catch(function () {
                return null;
              });
          }
        }
      } catch (e) {
        // Never let early flag resolution block the embed load.
      }
    })
    .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 }));
    });
})();
