import { initLedger } from './ledger.js'

const { register, waitForConsent } = globalThis.ami

const LAUNCH_DELAY = 1000 // Give it enough time for the page to render properly first.
const LAUNCH_ID = 'adobe-launch-container-script'
const POLL_STEP = 500
const ADOBE_SERVICES = {
  statistics: ['ecid', 'aa', 'aam'],
  preferences: ['target']
}

function loadLaunch (src, consent) {
  // If no Launch link or of Launch is already loaded.
  if (!src || document.getElementById(LAUNCH_ID)) {
    return
  }

  const script = document.createElement('script')
  script.id = LAUNCH_ID
  script.setAttribute('async', '')
  script.setAttribute('defer', '')
  script.setAttribute('src', src)
  document.head.appendChild(script)

  // Launch is loaded only when consent is granted.
  adobeConsent(consent)
  googleConsent(consent)
  pageBottom()
}

function adobeConsent (consent) {
  // Wait for Adobe Opt-In to be loaded via Launch.
  if (!globalThis?.adobe?.optIn) {
    setTimeout(() => adobeConsent(consent), POLL_STEP)
    return
  }

  // Approve selected services only.
  for (const [name, services] of Object.entries(ADOBE_SERVICES)) {
    if (consent[name]) {
      globalThis.adobe.optIn.approve(services)
    } else {
      globalThis.adobe.optIn.deny(services)
    }
  }
}

function googleConsent (consent) {
  globalThis.dataLayer ||= []

  const marketingConsent = consent.marketing ? 'granted' : 'denied'
  const statisticsConsent = consent.statistics ? 'granted' : 'denied'

  ;(function () {
    // eslint-disable-next-line prefer-rest-params -- Google API requires Arguments object, not rest parameters or spread
    globalThis.dataLayer.push(arguments) // NOSONAR
  })('consent', 'default', {
    ad_storage: marketingConsent,
    ad_user_data: marketingConsent,
    ad_personalization: marketingConsent,
    analytics_storage: statisticsConsent
  })
}

function pageBottom () {
  if (!globalThis._satellite?.pageBottom) {
    setTimeout(pageBottom, POLL_STEP)
    return
  }

  globalThis._satellite.pageBottom()
}

function init (src, consent) {
  initLedger()

  // Delay Launch injection.
  setTimeout(() => {
    loadLaunch(src, consent)
  }, LAUNCH_DELAY)
}

function LaunchContainer ({ src }) {
  const force = new URLSearchParams(location.search).has('force-launch')
  const consentToCheck = { statistics: true, preferences: true, marketing: true }

  if (force) {
    init(src, consentToCheck)
  } else {
    waitForConsent(consentToCheck, false).then(consent => init(src, consent))
  }
}

register(LaunchContainer, 'launch-container')
