"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, Loader2 } 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"; import { useUnifiedRefresh } from "@/hooks/use-unified-refresh"; import { REFRESH_INTERVALS } from "@/lib/constants/refresh-intervals"; import { Badge } from "@/components/ui/badge"; 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 [unreadCount, setUnreadCount] = useState(0); 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 (forceRefresh = false) => { // Only show loading spinner on initial load, not on auto-refresh if (!messages.length) { setLoading(true); } setRefreshing(true); setError(null); try { const response = await fetch('/api/rocket-chat/messages' + (forceRefresh ? '?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; // Update unread count state for badge display setUnreadCount(currentUnreadCount); // 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); } }; // Initial fetch on mount useEffect(() => { if (status === 'authenticated') { fetchMessages(false); // Use cache on initial load } }, [status]); // Integrate unified refresh for automatic polling const { refresh } = useUnifiedRefresh({ resource: 'parole', interval: REFRESH_INTERVALS.PAROLE, // 30 seconds enabled: status === 'authenticated', onRefresh: async () => { await fetchMessages(false); // Use cache for auto-refresh }, priority: 'high', }); // Manual refresh handler (bypasses cache) const handleManualRefresh = async (e?: React.MouseEvent) => { if (e) { e.stopPropagation(); } await fetchMessages(true); // Force refresh, bypass cache }; 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 {unreadCount > 0 && ( {unreadCount} )} {loading && messages.length === 0 ? (

Chargement des messages...

) : error ? (

{error}

) : (
{messages.length === 0 ? (

Aucun message

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

{message.sender.name}

{message.timestamp}

{message.text}

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