import { useState, useEffect, useCallback } from 'react' import { notificationService } from '@/lib/notificationService' import type { Notification } from '@/lib/notificationService' export function useNotifications(userPubkey: string | null): { notifications: Notification[] unreadCount: number loading: boolean markAsRead: (notificationId: string) => void markAllAsRead: () => void deleteNotification: (notificationId: string) => void } { const [notifications, setNotifications] = useState([]) const [loading, setLoading] = useState(true) // Load stored notifications on mount and refresh periodically useEffect(() => { if (!userPubkey) { setNotifications([]) setLoading(false) return } const loadNotifications = async (): Promise => { try { setLoading(true) const storedNotifications = await notificationService.getAllNotifications(100) setNotifications(storedNotifications) } catch (error) { console.error('[useNotifications] Error loading notifications:', error) } finally { setLoading(false) } } void loadNotifications() // Refresh notifications every 30 seconds const interval = setInterval(() => { void loadNotifications() }, 30000) return () => { clearInterval(interval) } }, [userPubkey]) const unreadCount = notifications.filter((n) => !n.read).length const markAsRead = useCallback( (notificationId: string): void => { if (!userPubkey) { return } void (async (): Promise => { try { await notificationService.markAsRead(notificationId) const storedNotifications = await notificationService.getAllNotifications(100) setNotifications(storedNotifications) } catch (error) { console.error('[useNotifications] Error marking notification as read:', error) } })() }, [userPubkey] ) const markAllAsReadHandler = useCallback((): void => { if (!userPubkey) { return } void (async (): Promise => { try { await notificationService.markAllAsRead() const storedNotifications = await notificationService.getAllNotifications(100) setNotifications(storedNotifications) } catch (error) { console.error('[useNotifications] Error marking all as read:', error) } })() }, [userPubkey]) const deleteNotificationHandler = useCallback( (notificationId: string): void => { if (!userPubkey) { return } void (async (): Promise => { try { await notificationService.deleteNotification(notificationId) const storedNotifications = await notificationService.getAllNotifications(100) setNotifications(storedNotifications) } catch (error) { console.error('[useNotifications] Error deleting notification:', error) } })() }, [userPubkey] ) return { notifications, unreadCount, loading, markAsRead, markAllAsRead: markAllAsReadHandler, deleteNotification: deleteNotificationHandler, } }