"use client"

import { useEffect, useState } from "react"
import { ApiEndpoint } from "@/lib/services/api.service"
import { useApi } from "@/lib/services/axios.service"

/** Fired on window when chat messages were read or sent, so every chat badge updates. */
export const CHATS_CHANGED_EVENT = "rangook:chats-changed"

const POLL_MS = 30_000

export function useChatUnread(): number {
  const [count, setCount] = useState(0)
  const [, fetchCount] = useApi<{ count: number }>({ url: ApiEndpoint("chat", "unread"), method: "GET" })

  useEffect(() => {
    const load = () => {
      fetchCount().then((response) => setCount(response?.body?.data?.count ?? 0), () => { /* keep the last count */ })
    }
    const onVisible = () => {
      if (document.visibilityState === "visible") load()
    }

    load()
    const timer = setInterval(load, POLL_MS)
    window.addEventListener(CHATS_CHANGED_EVENT, load)
    document.addEventListener("visibilitychange", onVisible)

    return () => {
      clearInterval(timer)
      window.removeEventListener(CHATS_CHANGED_EVENT, load)
      document.removeEventListener("visibilitychange", onVisible)
    }
  }, [fetchCount])

  return count
}
