'use client'

/**
 * Live support: the Chatwoot widget, loaded only when the academy has switched it on.
 *
 * What this replaced, and why it is a different thing: the old help bubble (Chat.tsx) answered with lines
 * an editor had typed and handed anything else to WhatsApp — no desk behind it. This opens a conversation
 * with a person on our own support server, which keeps its own history. Two bubbles in one corner is the
 * outcome nobody wants, so the old one is no longer rendered.
 *
 * Nothing is loaded when it is off, or when either the address or the token is missing: a bubble that
 * opens onto a dead server is worse than no bubble. That check happens before the script tag exists, so a
 * visitor on a switched-off site fetches nothing from the support host at all — which also means no
 * third-party request and no cookie from it.
 *
 * The token is not a secret. It identifies which inbox the messages land in and is visible in any page's
 * source by design; it grants nothing but the ability to start a conversation.
 */

import { useEffect } from 'react'

type Props = { baseUrl?: string | null; websiteToken?: string | null; locale?: string }

export function Support({ baseUrl, websiteToken, locale }: Props) {
  const base = (baseUrl || '').trim().replace(/\/+$/, '')
  const token = (websiteToken || '').trim()

  useEffect(() => {
    if (!base || !token) return
    // the SDK is added once per page; React in development mounts an effect twice
    if (document.getElementById('tk-support-sdk')) return

    const g = document.createElement('script')
    g.id = 'tk-support-sdk'
    g.src = `${base}/packs/js/sdk.js`
    g.async = true
    g.onload = () => {
      const sdk = (window as unknown as { chatwootSDK?: { run: (o: object) => void } }).chatwootSDK
      if (!sdk) return
      sdk.run({ websiteToken: token, baseUrl: base })
      // the widget speaks the page's language, not the browser's
      const w = window as unknown as { $chatwoot?: { setLocale?: (l: string) => void } }
      if (locale && w.$chatwoot?.setLocale) w.$chatwoot.setLocale(locale === 'en' ? 'en' : 'ar')
    }
    document.head.appendChild(g)
  }, [base, token, locale])

  if (!base || !token) return null
  return null
}
