"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 { useWidgetNotification } from "@/hooks/use-widget-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 { triggerNotification } = useWidgetNotification(); 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 = -1; // Set to -1 to trigger on first load console.log('[Parole] Initial unread count:', currentUnreadCount); } // Si le count a changé (ou premier chargement), déclencher notification if (currentUnreadCount !== lastUnreadCountRef.current) { const previousCount = lastUnreadCountRef.current; lastUnreadCountRef.current = currentUnreadCount; // Préparer les items pour les notifications (messages, max 10) const notificationItems = data.messages .slice(0, 10) .map((msg: any) => ({ id: msg.id, title: msg.sender.name || msg.sender.username, message: msg.text || msg.message || '', link: '/parole', timestamp: new Date(msg.rawTimestamp || msg.timestamp), metadata: { roomName: msg.roomName, roomType: msg.roomType, }, })); // Déclencher notification update (for badge) await triggerNotification({ source: 'rocketchat', count: currentUnreadCount, items: notificationItems, }); // Dispatch event for Outlook-style notifications (only for new messages) // We detect new messages by comparing message count, not unread count // because new messages might be read immediately if (previousCount >= 0 && data.messages.length > 0) { // Get the most recent messages (first ones in the array, sorted by date desc) // We'll let the hook determine which are truly new const totalMessages = data.messages.length; console.log('[Parole Widget] 💬 Dispatching messages event', { totalMessages, previousUnreadCount: previousCount, currentUnreadCount, }); window.dispatchEvent(new CustomEvent('new-messages-detected', { detail: { messages: data.messages, previousCount: previousCount, currentCount: 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}
)}
)) )}
)}
); }