(function () {
  var TWIKOO_SRC =
    'https://cdn.jsdelivr.net/npm/twikoo@1.6.44/dist/twikoo.min.js'
  var TARGET_SELECTOR = '#tcomment'
  var SCRIPT_ID = 'twikoo-cdn-script'

  function renderTwikoo() {
    var container = document.querySelector(TARGET_SELECTOR)
    if (!container) {
      console.warn('[twikoo-loader] target container not found')
      return
    }
    if (!window.twikoo) {
      console.warn('[twikoo-loader] twikoo is not ready when render called')
      return
    }

    console.info('[twikoo-loader] renderTwikoo: init comments')
    container.innerHTML = ''
    window.twikoo.init({
      envId: 'https://twikoo.hk.nvme0n1p.dev/',
      el: TARGET_SELECTOR,
    })
  }

  function ensureScript() {
    var existing = document.getElementById(SCRIPT_ID)

    if (existing) {
      if (existing.dataset.failed === 'true') {
        console.warn('[twikoo-loader] previous load failed, removing script')
        existing.remove()
      } else {
        if (!window.twikoo) {
          console.info('[twikoo-loader] script already present, waiting for load')
          existing.addEventListener('load', renderTwikoo, { once: true })
        }
        return
      }
    }

    console.info('[twikoo-loader] injecting script', TWIKOO_SRC)
    var script = document.createElement('script')
    script.id = SCRIPT_ID
    script.src = TWIKOO_SRC
    script.async = true
    script.onload = function () {
      console.info('[twikoo-loader] twikoo script loaded')
      script.dataset.loaded = 'true'
      renderTwikoo()
    }
    script.onerror = function (err) {
      script.dataset.failed = 'true'
      console.error('[twikoo-loader] Failed to load Twikoo:', err)
      console.error('Failed to load Twikoo:', err)
    }
    document.head.appendChild(script)
  }

  function init() {
    console.info('[twikoo-loader] init called')
    ensureScript()

    if (window.twikoo) {
      renderTwikoo()
    }
  }

  function onLoad() {
    init()
  }

  // 手动触发入口，便于在需要时重新初始化
  window.runTwikooComments = onLoad

  if (document.readyState === 'complete') {
    onLoad()
  } else {
    window.addEventListener('load', onLoad, { once: true })
  }

  document.addEventListener('astro:page-load', onLoad)
  document.addEventListener('astro:after-swap', onLoad)
})()
