export default defineNuxtPlugin(() => {
  const loadChatwoot = () => {
    if (document.getElementById('chatwoot-sdk')) return

    const baseUrl = 'https://chatwoot.optovia.ru'
    const script = document.createElement('script')
    script.id = 'chatwoot-sdk'
    script.src = `${baseUrl}/packs/js/sdk.js`
    script.async = true
    script.defer = true
    script.onload = () => {
      window.chatwootSDK?.run({
        websiteToken: 'bc668ge3hM5ZpPeUgGEV1ZU9',
        baseUrl
      })
    }

    if (document.body) {
      document.body.appendChild(script)
    } else {
      document.addEventListener('DOMContentLoaded', () => {
        document.body?.appendChild(script)
      }, { once: true })
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', loadChatwoot, { once: true })
  } else {
    loadChatwoot()
  }
})
