// hooks/useNotifications.js
import { useState, useEffect, useRef } from 'react';

export function useNotifications(userId) {
    const [notifications, setNotifications] = useState([]);
    const eventSourceRef = useRef(null);

    useEffect(() => {
        if (!userId) return;

        const fetchNotifications = async () => {
            try {
                const res = await fetch('/api/notifications/all');
                const data = await res.json();
                if (data.success) {
                    setNotifications(data.notifications);
                } else {
                    console.error('Failed to fetch notifications');
                }
            } catch (error) {
                console.error('Error fetching notifications:', error);
            }
        };

        fetchNotifications();

        const connectSSE = () => {
            const es = new EventSource('/api/notifications/stream', {
                withCredentials: true
            });

            eventSourceRef.current = es;

            es.onmessage = (e) => {
                try {
                    const newNotification = JSON.parse(e.data);
                    setNotifications(prev => {
                        const exists = prev.some(n => n.id === newNotification.id);
                        return exists ? prev : [...prev, newNotification];
                    });
                } catch (err) {
                    console.error('Error parsing SSE message', err);
                }
            };

            es.addEventListener('heartbeat', () => {
                // Optional: console.log('💓 heartbeat');
            });

            es.onerror = (err) => {
                console.error('SSE connection error', err);
                es.close();
                // Retry after 5 seconds
                setTimeout(connectSSE, 5000);
            };
        };

        connectSSE();

        return () => {
            if (eventSourceRef.current) {
                eventSourceRef.current.close();
            }
        };
    }, [userId]);

    const markAsRead = async (notificationIds) => {
        try {
            await fetch('/api/notifications/mark-read', {
                method: 'PATCH',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ notificationIds }),
            });

            setNotifications(prev =>
                prev.map(n =>
                    notificationIds.includes(n.id) ? { ...n, read: true } : n
                )
            );
        } catch (error) {
            console.error('Failed to mark notifications as read', error);
        }
    };

    return { notifications, markAsRead };
}
