"use client"

import useSWR from "swr"
import { useAuth } from "@/components/auth-provider"

const fetcher = (url: string) => fetch(url).then((res) => res.json())

export function useNotificationCount() {
  const { user } = useAuth()

  const { data, error, mutate } = useSWR(user?.id ? `/api/notifications?userId=${user.id}` : null, fetcher, {
    refreshInterval: 30000, // Refresh every 30 seconds
    revalidateOnFocus: true,
  })

  const unreadCount = data?.notifications?.filter((n: any) => !n.is_read).length || 0

  return {
    unreadCount,
    isLoading: !error && !data,
    isError: error,
    mutate,
  }
}
