"use client";

import React, { useEffect, useRef } from 'react';
import { toast, Toaster } from 'sonner';
import { BACKEND_URL } from '@/lib/api';

export function RealTimeNotifications() {
    const retryTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);
    const socketRef = useRef<WebSocket | null>(null);

    useEffect(() => {
        let isMounted = true;

        function connect() {
            if (!isMounted) return;

            try {
                // Replace http/https with ws/wss
                const wsBase = BACKEND_URL.replace(/^http/, 'ws');
                const wsUrl = `${wsBase}/ws/notifications/`;

                const socket = new WebSocket(wsUrl);
                socketRef.current = socket;

                socket.onopen = () => {
                    if (isMounted) console.log('[WS] Notifications connected.');
                };

                socket.onmessage = (event) => {
                    if (!isMounted) return;
                    try {
                        const data = JSON.parse(event.data);
                        toast.success(data.title || 'Notification', {
                            description: data.message,
                            duration: 5000,
                        });
                    } catch {
                        // Ignore malformed messages silently
                    }
                };

                socket.onclose = () => {
                    if (!isMounted) return;
                    console.log('[WS] Disconnected. Retrying in 10s...');
                    retryTimeout.current = setTimeout(connect, 10000);
                };

                // Demote to a warn — prevents surfacing as a visible React error overlay
                socket.onerror = () => {
                    console.warn('[WS] Notifications unavailable (server may not support WebSockets yet).');
                };

            } catch {
                // WebSocket API not available (SSR guard)
            }
        }

        connect();

        return () => {
            isMounted = false;
            if (retryTimeout.current) clearTimeout(retryTimeout.current);
            if (socketRef.current) socketRef.current.close();
        };
    }, []);

    return <Toaster position="top-right" richColors expand={true} />;
}
