'use client'

import { useEffect } from 'react'

export function ChatwootWidget() {
  useEffect(() => {
    const chatwootToken = process.env.NEXT_PUBLIC_CHATWOOT_ACCOUNT_TOKEN

    if (!chatwootToken) {
      console.warn('[v0] Chatwoot account token not configured')
      return
    }

    // Load Chatwoot widget script
    const script = document.createElement('script')
    script.src = 'https://app.chatwoot.com/packs/js/sdk.js'
    script.async = true

    script.onload = () => {
      // Initialize Chatwoot after script loads
      if ((window as any).chatwootSDK) {
        ;(window as any).chatwootSDK.run({
          websiteToken: chatwootToken,
          baseUrl: 'https://app.chatwoot.com'
        })
      }
    }

    script.onerror = () => {
      console.error('[v0] Failed to load Chatwoot widget')
    }

    document.body.appendChild(script)

    return () => {
      // Cleanup is handled by Chatwoot itself
      // Don't remove the script as it manages its own lifecycle
    }
  }, [])

  return null
}
