"use client"; import { useEffect, useRef } from "react"; import { ref, onChildAdded, off, get } from "firebase/database"; import { db } from "@/lib/firebase"; import { useAuth } from "@/hooks/useAuth"; import { useToast } from "@/components/ui/toast"; export function NotificationMonitor() { const { user } = useAuth(); const { toast } = useToast(); const isInitialLoad = useRef(true); const seenReservas = useRef>(new Set()); useEffect(() => { if (!user?.email) return; const reservasRef = ref(db, "reservas"); // Primeiro, marcamos todas as reservas existentes como "vistas" // para não disparar notificações para o passado const loadExisting = async () => { try { const snapshot = await get(reservasRef); if (snapshot.exists()) { const data = snapshot.val(); Object.keys(data).forEach(id => seenReservas.current.add(id)); } } catch (error) { console.error("[NotificationMonitor] Error loading existing reservas:", error); } finally { isInitialLoad.current = false; } }; loadExisting(); const unsubscribe = onChildAdded(reservasRef, (snapshot) => { const id = snapshot.key; if (!id || seenReservas.current.has(id)) return; // Adiciona ao set para não repetir se o listener reiniciar seenReservas.current.add(id); // Se ainda estivermos no load inicial (do get), ignoramos o toast if (isInitialLoad.current) return; try { const data = snapshot.val(); if (data?.restauranteEmail === user.email && data?.estado === "Pendente") { toast(`Nova reserva recebida de ${data?.clienteEmail || "cliente"}!`, "info"); } } catch (error) { console.error("[NotificationMonitor] Error processing new reserva:", error); } }); return () => { off(reservasRef, "child_added", unsubscribe); }; }, [user?.email, toast]); return null; // Componente apenas lógico }