// QuickCheckout-managed Google tag loader, served per store by /vendors/google-tag/{storeID}.
// Placeholders are substituted server-side; the loader owns no consent defaults and sends no
// synthetic events: gtag.js is the only identity source once it runs.
;(function () {
  try {
    const measurementId = `G-7DDDPG5XCV`
    const vendorType = `bigcommerce`
    if (!measurementId) return

    // Only catches a destination configured before us; the admin toggle is the real control.
    if (window.google_tag_manager && window.google_tag_manager[measurementId]) {
      console.log('[qc] google tag already configured', measurementId)
      return
    }

    let loaded = false
    const load = () => {
      if (loaded) return
      loaded = true
      try {
        if (typeof window.gtag !== 'function') {
          window.dataLayer = window.dataLayer || []
          window.gtag = function () {
            window.dataLayer.push(arguments)
          }
        }

        const script = document.createElement('script')
        script.async = true
        script.src = 'https://www.googletagmanager.com/gtag/js?id=' + encodeURIComponent(measurementId)
        document.head.appendChild(script)

        window.gtag('js', new Date())
        window.gtag('config', measurementId)
      } catch (err) {
        console.warn('[qc] google tag failed to load', err)
      }
    }

    // BigCommerce already gated this script by consent category server-side.
    if (vendorType !== 'shopify') {
      load()
      return
    }

    // Shopify: fail closed when the Customer Privacy API is unavailable.
    const shopify = window.Shopify
    if (!shopify || typeof shopify.loadFeatures !== 'function') {
      console.log('[qc] google tag skipped: shopify consent api unavailable')
      return
    }

    shopify.loadFeatures([{ name: 'consent-tracking-api', version: '0.1' }], (error) => {
      try {
        const privacy = window.Shopify && window.Shopify.customerPrivacy
        if (error || !privacy || typeof privacy.analyticsProcessingAllowed !== 'function') {
          console.log('[qc] google tag skipped: shopify consent api failed to load', error)
          return
        }

        if (privacy.analyticsProcessingAllowed()) {
          load()
          return
        }

        document.addEventListener('visitorConsentCollected', (event) => {
          if (event && event.detail && event.detail.analyticsAllowed) load()
        })
      } catch (err) {
        console.warn('[qc] google tag consent check failed', err)
      }
    })
  } catch (err) {
    console.warn('[qc] google tag loader failed', err)
  }
})()
