"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 notifications were read, so every bell updates. */
export const NOTIFICATIONS_CHANGED_EVENT = "rangook:notifications-changed"

/** Re-check this often while the app is open. */
const POLL_MS = 60_000

/** The learner's unread notification count, kept fresh (on open, every minute, on return to the app). */
export function useUnreadNotifications(): number {
  const [count, setCount] = useState(0)
  const [, fetchCount] = useApi<{ count: number }>({ url: ApiEndpoint("notification", "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(NOTIFICATIONS_CHANGED_EVENT, load)
    document.addEventListener("visibilitychange", onVisible)

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

  return count
}
