"use client"

import { useEffect, useState } from "react"
import dynamic from "next/dynamic"
import { api } from "@/convex/_generated/api"
import { useAuth } from "@/lib/auth-client"
import { isAgentOrAdmin } from "@/lib/authz"

// Verifica se a API do liveChat existe
function checkLiveChatApiExists() {
  try {
    return typeof api.liveChat?.listAgentSessions !== "undefined"
  } catch {
    return false
  }
}

// Importacao dinamica para evitar problemas de SSR
const ChatWidget = dynamic(
  () => import("./chat-widget").then((mod) => ({ default: mod.ChatWidget })),
  { ssr: false, loading: () => null }
)

export function ChatWidgetProvider() {
  const { role, isLoading } = useAuth()
  const [mounted, setMounted] = useState(false)

  useEffect(() => {
    setMounted(true)
  }, [])

  // Evita hydration mismatch - so renderiza apos montar no cliente
  if (!mounted) return null
  if (isLoading) return null
  if (!isAgentOrAdmin(role)) return null

  // Nao renderiza se a API nao existir (Convex nao sincronizado)
  if (!checkLiveChatApiExists()) {
    return null
  }

  return <ChatWidget />
}
