;(function () {
  // Inject critical CSS immediately (antes de qualquer outra lógica)
  if (!document.getElementById('widde-critical-css')) {
    const style = document.createElement('style')
    style.id = 'widde-critical-css'
    style.textContent = `.mm-wrapper--opened,.mm-wrapper_opened,.mm-opened,html.js-drawer-open,body.snapjs-left{widde-story-floating,widde-story-inline,widde-configuration-previewe{display:none!important}}widde-configuration-preview,widde-story-inline,widde-story-floating,widde-fullscreen{box-sizing:content-box!important;display:inline!important}widde-feed{width:100%!important}widde-pro-carousel,widde-pro-carousel-two{display:block!important;width:100%!important;contain:layout style}widde-pro-carousel[data-widde-ready],widde-pro-carousel-two[data-widde-ready]{contain:none}@keyframes wddPulse{0%,100%{opacity:1}50%{opacity:.5}}`
    document.head.appendChild(style)
  }

  // Prefetch setup data while main bundle downloads (runs in parallel).
  // Uses msgpack for obfuscation/compression. Decoder is inlined (~3KB) to avoid
  // a separate script download that Lighthouse flagged for cache policy.
  ;(function () {
    try {
      var API_URL = 'https://api-admin.widde.io'
      var hostname = window.location.hostname
      // Skip prefetch for CDN app (uses query param domain, handled by main bundle)
      if (hostname === 'cdn.widde.io') return
      var params = new URLSearchParams(window.location.search)
      var demoUrl = params.get('widde-demo-url')
      var domain = demoUrl || window.location.host

      // Minimal msgpack decoder inlined (~3KB minified, avoids separate script request)
      var mp = (function () {
        var T = new TextDecoder()
        function u8(d) {
          return d instanceof Uint8Array ? d : new Uint8Array(d)
        }
        function dec(b) {
          var a = u8(b),
            p = 0
          function r8() {
            return a[p++]
          }
          function r16() {
            return (r8() << 8) | r8()
          }
          function r32() {
            return r8() * 16777216 + (r8() << 16) + (r8() << 8) + r8()
          }
          function rf32() {
            var v = new DataView(a.buffer, a.byteOffset + p, 4)
            p += 4
            return v.getFloat32(0)
          }
          function rf64() {
            var v = new DataView(a.buffer, a.byteOffset + p, 8)
            p += 8
            return v.getFloat64(0)
          }
          function rstr(n) {
            var s = T.decode(a.subarray(p, p + n))
            p += n
            return s
          }
          function rbin(n) {
            var s = a.slice(p, p + n)
            p += n
            return s
          }
          function ri64() {
            var hi =
              (a[p] << 24) | (a[p + 1] << 16) | (a[p + 2] << 8) | a[p + 3]
            var lo =
              (a[p + 4] << 24) | (a[p + 5] << 16) | (a[p + 6] << 8) | a[p + 7]
            p += 8
            return hi * 4294967296 + lo
          }
          function rd() {
            var c = r8()
            if (c < 0x80) return c
            if (c < 0x90) {
              var n = c & 0xf,
                o = {}
              for (var i = 0; i < n; i++) {
                var k = rd(),
                  v = rd()
                o[k] = v
              }
              return o
            }
            if (c < 0xa0) {
              var n = c & 0xf,
                arr = new Array(n)
              for (var i = 0; i < n; i++) arr[i] = rd()
              return arr
            }
            if (c < 0xc0) return rstr(c & 0x1f)
            if (c === 0xc0) return null
            if (c === 0xc2) return false
            if (c === 0xc3) return true
            if (c === 0xc4) return rbin(r8())
            if (c === 0xc5) return rbin(r16())
            if (c === 0xc6) return rbin(r32())
            if (c === 0xca) return rf32()
            if (c === 0xcb) return rf64()
            if (c === 0xcc) return r8()
            if (c === 0xcd) return r16()
            if (c === 0xce) return r32()
            if (c === 0xcf) return ri64()
            if (c === 0xd0) {
              var v = r8()
              return v > 127 ? v - 256 : v
            }
            if (c === 0xd1) {
              var v = r16()
              return v > 32767 ? v - 65536 : v
            }
            if (c === 0xd2) {
              var v = r32()
              return v > 2147483647 ? v - 4294967296 : v
            }
            if (c === 0xd3) return ri64()
            if (c === 0xd9) return rstr(r8())
            if (c === 0xda) return rstr(r16())
            if (c === 0xdb) return rstr(r32())
            if (c === 0xdc) {
              var n = r16(),
                arr = new Array(n)
              for (var i = 0; i < n; i++) arr[i] = rd()
              return arr
            }
            if (c === 0xdd) {
              var n = r32(),
                arr = new Array(n)
              for (var i = 0; i < n; i++) arr[i] = rd()
              return arr
            }
            if (c === 0xde) {
              var n = r16(),
                o = {}
              for (var i = 0; i < n; i++) {
                var k = rd(),
                  v = rd()
                o[k] = v
              }
              return o
            }
            if (c === 0xdf) {
              var n = r32(),
                o = {}
              for (var i = 0; i < n; i++) {
                var k = rd(),
                  v = rd()
                o[k] = v
              }
              return o
            }
            if (c >= 0xd4 && c <= 0xd8) {
              var s = [1, 2, 4, 8, 16][c - 0xd4]
              p += 1 + s
              return undefined
            }
            if (c === 0xc7) {
              var s = r8()
              p += 1 + s
              return undefined
            }
            if (c === 0xc8) {
              var s = r16()
              p += 1 + s
              return undefined
            }
            if (c === 0xc9) {
              var s = r32()
              p += 1 + s
              return undefined
            }
            if (c >= 0xe0) return c - 256
            throw new Error('Unknown msgpack type: 0x' + c.toString(16))
          }
          return rd()
        }
        return { decode: dec }
      })()

      window.______widdeSetupPromise = fetch(
        API_URL + '/api/get-setup?domain=' + encodeURIComponent(domain),
        { headers: { Accept: 'application/x-msgpack' } }
      )
        .then(function (r) {
          if (!r.ok) throw new Error('HTTP ' + r.status)
          return r.arrayBuffer()
        })
        .then(function (buf) {
          return mp.decode(new Uint8Array(buf))
        })
        .then(function (data) {
          if (data) {
            if (!document.querySelector('script[src*="cdn-tryon.widde.io"], script[src*="localhost:4444"]')) {
              var s = document.createElement('script')
              s.src = 'https://cdn-tryon.widde.io/tryon.js'
              s.defer = true
              document.head.appendChild(s)
            }
          }
          return data
        })
        .catch(function () {
          return null
        })
    } catch (e) {}
  })()

  let CDN_URL = 'https://cdn.widde.io'
  if (window.location.href.includes('disable-widde')) return
  if (window.______widdeLoadded) return
  window.______widdeLoadded = true

  let runned = false
  const hasLVItem = !!window.LS && window.LS.ready && window.LS.ready.then

  // Detecção do domínio cdn.widde.io para fluxo otimizado
  const isCDNWiddeIoApp = window.location.hostname === 'cdn.widde.io/app'

  // Fluxo otimizado para cdn.widde.io
  if (isCDNWiddeIoApp) {
    // Carregamento imediato sem timeouts ou validações extras
    run()
    return
  }

  // Fluxo normal para outros domínios
  // TimeoutFeedVideos(0)

  if (hasLVItem)
    window.LS.ready.then(function () {
      run()
    })
  else {
    Timeout(1500)
    DocumentLoad()
  }

  function Timeout(time) {
    setTimeout(() => {
      run()
    }, time)
  }

  function TimeoutFeedVideos(time) {
    try {
      if (window.location.href.includes('video-commerce'))
        setTimeout(() => {
          run()
        }, time)
      if (window.location.href.includes('carousel'))
        setTimeout(() => {
          run()
        }, time)
    } catch (error) {}
  }

  async function run() {
    if (runned) return

    // Para cdn.widde.io, não aguardamos o body se ele não existir ainda
    if (isCDNWiddeIoApp) {
      runned = true
      // Tenta carregar imediatamente, se não conseguir, aguarda o body
      if (document.body) {
        init()
      } else {
        // Aguarda o body de forma mais eficiente para CDN
        const checkBody = () => {
          if (document.body) {
            init()
          } else {
            requestAnimationFrame(checkBody)
          }
        }
        checkBody()
      }
      return
    }

    // Fluxo normal para outros domínios
    await waitBody()
    if (document.body) {
      runned = true
      setTimeout(init, 0)
    }
  }
  function init() {
    const script = document.createElement('script')
    script.type = 'module'
    script.src = `${CDN_URL}/${'assets/main.a3qh91exsqh.js'}`

    // Para cdn.widde.io, adiciona o script imediatamente ao head se body não estiver disponível
    if (isCDNWiddeIoApp && !document.body) {
      document.head.appendChild(script)
    } else {
      document.body.appendChild(script)
    }
  }

  function waitBody() {
    return new Promise(r => {
      if (document.body) {
        r()
      } else {
        setTimeout(() => {
          waitBody().then(r)
        }, 100)
      }
    })
  }
  function DocumentLoad() {
    if (document.readyState === 'complete') {
      run()
    }
    function bodyLoad() {
      let attempts = 0
      const maxAttempts = 50

      function checkBody() {
        if (document.body) {
          run()
          window.removeEventListener('load', bodyLoad)
        } else if (attempts < maxAttempts) {
          attempts++
          setTimeout(checkBody, 100)
        } else {
          console.warn('widde: body not created')
          window.removeEventListener('load', bodyLoad)
        }
      }
      checkBody()
    }
    function listenerLoad() {
      run()
      document.removeEventListener('load', listenerLoad)
    }

    function listerner(event) {
      if (event.target.readyState === 'complete') {
        run()
        document.removeEventListener('readystatechange', listerner)
      }
    }
    document.addEventListener('readystatechange', listerner)
    window.addEventListener('load', listenerLoad)
    window.addEventListener('load', bodyLoad)
  }
})()
