"use client"

import { usePathname, useSearchParams } from "next/navigation"
import Script from "next/script"
import { useEffect } from "react"

import { shouldShowChatbot } from "@/components/ChatbotScript/utils"
import useLang from "@/hooks/useLang"

interface ChatbotClientProps {
  liveLangs: string[]
}

export function ChatbotClient({ liveLangs }: ChatbotClientProps) {
  const lang = useLang()
  const pathname = usePathname()
  const searchParams = useSearchParams()
  const currentLang = useLang()
  const isLive = liveLangs.includes(currentLang)
  const shouldShow =
    isLive && shouldShowChatbot(pathname, searchParams, currentLang)

  useEffect(() => {
    window.kindlyOptions = {
      position: {
        bottom: "130px",
        right: "20px",
      },
    }
  }, [])

  useEffect(() => {
    if (window.kindlyChat) {
      if (!shouldShow) {
        window.kindlyChat.closeChat()
        window.kindlyChat.hideBubble()
        // Hack to hide chatbot behind other elements in case the user has multiple tabs
        // open and the chat window should not be visible in the tab that becomes active
        document.documentElement.style.setProperty("--chatbot-z-index", "-1")
      } else {
        window.kindlyChat.showBubble()
        // Reset z-index when chatbot is shown, we're using the default z-index from globals.css
        document.documentElement.style.removeProperty("--chatbot-z-index")
      }
    }
  }, [shouldShow])

  return (
    <Script
      id="kindly-chat"
      src="https://chat.kindlycdn.com/kindly-chat.js"
      data-bot-key="910bd27a-7472-43a1-bcfc-955b41adc3e7"
      data-shadow-dom
      data-bubble-hidden={!shouldShow}
      data-language={lang}
      defer
    ></Script>
  )
}
