"use client"; import { useEffect, useState, useRef } from "react"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; import { RefreshCw, MessageSquare } from "lucide-react"; import { useRouter } from "next/navigation"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { signIn, useSession } from "next-auth/react"; import { useTriggerNotification } from "@/hooks/use-trigger-notification"; interface Message { id: string; text: string; timestamp: string; rawTimestamp: string; roomName: string; roomType: string; sender: { _id: string; username: string; name: string; initials: string; color: string; }; isOwnMessage: boolean; room: { id: string; type: string; name: string; isChannel: boolean; isPrivateGroup: boolean; isDirect: boolean; link: string; }; } export function Parole() { const [messages, setMessages] = useState([]); const [error, setError] = useState(null); const [loading, setLoading] = useState(true); const [refreshing, setRefreshing] = useState(false); const router = useRouter(); const { data: session, status } = useSession(); const { triggerNotificationRefresh } = useTriggerNotification(); const lastUnreadCountRef = useRef(-1); // Initialize to -1 to detect first load const isInitializedRef = useRef(false); const fetchMessages = async (isRefresh = false) => { try { if (isRefresh) { setRefreshing(true); } const response = await fetch('/api/rocket-chat/messages' + (isRefresh ? '?refresh=true' : ''), { cache: 'no-store', next: { revalidate: 0 }, credentials: 'include', }); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.error || 'Failed to fetch messages'); } const data = await response.json(); if (Array.isArray(data.messages)) { // Utiliser le totalUnreadCount de l'API (plus fiable) const currentUnreadCount = data.totalUnreadCount || 0; // On initialise le count au premier chargement if (!isInitializedRef.current) { isInitializedRef.current = true; lastUnreadCountRef.current = currentUnreadCount; console.log('[Parole] Initial unread count:', currentUnreadCount); } else { console.log('[Parole] Unread count check', { previous: lastUnreadCountRef.current, current: currentUnreadCount, totalUnreadCount: data.totalUnreadCount, willTrigger: currentUnreadCount > lastUnreadCountRef.current }); // Si nouveau message non lu détecté, déclencher notification // On déclenche aussi si le count a changé (augmenté ou diminué) pour forcer le refresh if (currentUnreadCount !== lastUnreadCountRef.current) { console.log('[Parole] ⚡ Unread count changed, triggering notification refresh', { previous: lastUnreadCountRef.current, current: currentUnreadCount, isIncrease: currentUnreadCount > lastUnreadCountRef.current }); triggerNotificationRefresh(); } lastUnreadCountRef.current = currentUnreadCount; } setMessages(data.messages); } else { console.warn('Unexpected data format:', data); setMessages([]); } setError(null); } catch (err) { console.error('Error fetching messages:', err); const errorMessage = err instanceof Error ? err.message : 'Failed to fetch messages'; setError(errorMessage); } finally { setLoading(false); setRefreshing(false); } }; useEffect(() => { if (status === 'authenticated') { fetchMessages(); // Set up polling every 30 seconds with force refresh to bypass cache const interval = setInterval(() => fetchMessages(true), 30000); return () => clearInterval(interval); } }, [status]); if (status === 'loading') { return ( Parole

Loading...

); } if (status === 'unauthenticated' || (error && error.includes('Session expired'))) { return ( Parole

Please sign in to view messages

); } return ( router.push('/parole')} > Parole {loading &&

Loading messages...

} {error && (

Error: {error}

)} {!loading && !error && (
{messages.length === 0 ? (

No messages found

) : ( messages.map((message) => (
{message.sender.initials}

{message.sender.name}

{message.timestamp}

{message.text}

{message.roomName && (
{message.room.isChannel ? '#' : message.room.isPrivateGroup ? '🔒' : '💬'} {message.roomName}
)}
)) )}
)}
); }