/*
 * SAS Visual Analytics data-driven content: earliest-possible message capture.
 *
 * Loaded as an external script from index.html (CSP-safe under a strict policy
 * — no inline script needed) and executed at HTML parse time, long before the
 * Angular app bootstraps. SAS VA posts its DDC data message once on iframe
 * load, which happens before Angular is up, so without this the very first
 * message (and any pre-set filter it carries) is lost.
 *
 * The latest captured message is stored on window.__vaLastMessage;
 * VaMessagingService reads it when it subscribes (closing the startup race) and
 * to recover the latest message across editor reloads.
 *
 * Self-guards on ?embed=va so it is completely inert in normal (non-VA) use.
 */
;(function () {
  'use strict'

  try {
    var hash = window.location.hash || ''
    var query = hash.indexOf('?') >= 0 ? hash.split('?')[1] : ''
    if (new URLSearchParams(query).get('embed') !== 'va') return
  } catch (e) {
    return
  }

  window.addEventListener(
    'message',
    function (event) {
      var data = event && event.data
      if (
        data &&
        typeof data === 'object' &&
        typeof data.resultName === 'string'
      ) {
        // Store ONLY the latest message — readers just need the most recent, so
        // a single value keeps this bounded across a long session of filters.
        window.__vaLastMessage = {
          t: Date.now(),
          origin: event.origin,
          data: data
        }
      }
    },
    false
  )
})()
