File size: 14,548 Bytes
057576a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import React, { useState, useEffect } from 'react';
import { useAuth } from '../../contexts/AuthContext';
import { useSocket } from '../../contexts/SocketContext';
import Sidebar from './Sidebar';
import UserSearch from './UserSearch';
import ChatArea from '../Chat/ChatArea';
import { conversationService } from '../../services/api';
import { X } from 'lucide-react';

const Dashboard = ({ user, onLogout }) => {
  const { logout } = useAuth();
  const { socket, isConnected } = useSocket();
  const [conversations, setConversations] = useState([]);
  const [selectedConversation, setSelectedConversation] = useState(null);
  const [messages, setMessages] = useState([]);
  const [onlineUsers, setOnlineUsers] = useState(new Set());
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState('');
  const [showNewConversation, setShowNewConversation] = useState(false);

  // بارگیری مکالمات هنگام بارگذاری اولیه
  useEffect(() => {
    loadConversations();
  }, []);

  // اشتراک در رویدادهای سوکت
  useEffect(() => {
    if (!socket || !isConnected) return;

    // گرفتن وضعیت آنلاین کاربران
    socket.emit('get-online-users');
    
    // مدیریت رویدادهای سوکت
    const setupSocketListeners = () => {
      socket.on('message:receive', handleMessageReceive);
      socket.on('message:read', handleMessageRead);
      socket.on('conversation:updated', handleConversationUpdate);
      socket.on('conversation:created', handleConversationCreate);
      socket.on('user:status', handleUserStatusChange);
      socket.on('typing:start', handleTypingStart);
      socket.on('typing:stop', handleTypingStop);
    };

    const cleanupSocketListeners = () => {
      socket.off('message:receive', handleMessageReceive);
      socket.off('message:read', handleMessageRead);
      socket.off('conversation:updated', handleConversationUpdate);
      socket.off('conversation:created', handleConversationCreate);
      socket.off('user:status', handleUserStatusChange);
      socket.off('typing:start', handleTypingStart);
      socket.off('typing:stop', handleTypingStop);
    };

    setupSocketListeners();
    return cleanupSocketListeners;
  }, [socket, isConnected, selectedConversation]);

  const loadConversations = async () => {
    try {
      setIsLoading(true);
      setError('');
      
      const response = await conversationService.getAll();
      setConversations(response.conversations || []);
      
      // اگر مکالمه ای وجود داشته باشد، اولین مکالمه را انتخاب کن
      if (response.conversations && response.conversations.length > 0) {
        handleSelectConversation(response.conversations[0]);
      }
    } catch (err) {
      console.error('Error loading conversations:', err);
      setError('Failed to load conversations. Please try again later.');
    } finally {
      setIsLoading(false);
    }
  };

  const handleSelectConversation = async (conversation) => {
    setSelectedConversation(conversation);
    
    try {
      // بارگیری پیام‌های مکالمه
      const response = await conversationService.getMessages(conversation._id);
      setMessages(response.messages || []);
      
      // علامت‌گذاری پیام‌های خوانده شده
      if (socket && socket.connected) {
        socket.emit('message:read-all', {
          conversationId: conversation._id
        });
      }
      
      // به‌روزرسانی لیست مکالمات
      setConversations(prev => prev.map(conv => 
        conv._id === conversation._id ? { ...conv, unreadCount: 0 } : conv
      ));
    } catch (err) {
      console.error('Error loading messages:', err);
      setError('Failed to load messages for this conversation.');
    }
  };

  const handleNewMessage = (message) => {
    // اضافه کردن پیام به لیست پیام‌ها
    setMessages(prev => [...prev, message]);
    
    // به‌روزرسانی آخرین پیام در مکالمه
    if (selectedConversation) {
      setConversations(prev => prev.map(conv => 
        conv._id === selectedConversation._id 
          ? { ...conv, lastMessage: message, updatedAt: new Date() } 
          : conv
      ));
    }
  };

  const handleConversationUpdate = (data) => {
    if (!data.conversationId) return;
    
    setConversations(prev => prev.map(conv => 
      conv._id === data.conversationId ? { ...conv, ...data } : conv
    ));
  };

  const handleConversationCreate = (conversation) => {
    setConversations(prev => [conversation, ...prev]);
    setSelectedConversation(conversation);
  };

  const handleUserStatusChange = (data) => {
    if (data.userId) {
      if (data.status === 'online') {
        setOnlineUsers(prev => new Set(prev).add(data.userId));
      } else {
        setOnlineUsers(prev => {
          const newSet = new Set(prev);
          newSet.delete(data.userId);
          return newSet;
        });
      }
    }
  };

  const handleTypingStart = (data) => {
    if (selectedConversation && data.conversationId === selectedConversation._id) {
      console.log(`${data.userId} is typing...`);
    }
  };

  const handleTypingStop = (data) => {
    if (selectedConversation && data.conversationId === selectedConversation._id) {
      console.log(`${data.userId} stopped typing`);
    }
  };

  const handleMessageReceive = (message) => {
    // اگر پیام مربوط به مکالمه فعلی باشد
    if (selectedConversation && selectedConversation._id === message.conversation) {
      setMessages(prev => [...prev, message]);
    } else {
      // به‌روزرسانی تعداد پیام‌های خوانده نشده
      setConversations(prev => prev.map(conv => 
        conv._id === message.conversation 
          ? { ...conv, unreadCount: (conv.unreadCount || 0) + 1 } 
          : conv
      ));
    }
  };

  const handleMessageRead = (data) => {
    if (selectedConversation && selectedConversation._id === data.conversationId) {
      setMessages(prev => prev.map(msg => 
        msg._id === data.messageId ? { ...msg, readBy: [...(msg.readBy || []), { user: data.userId }] } : msg
      ));
    }
  };

  const handleNewConversation = () => {
    setShowNewConversation(true);
  };

  const handleConversationCreated = (conversation) => {
    setShowNewConversation(false);
    handleSelectConversation(conversation);
  };

  const handleLogoutUser = async () => {
    try {
      await logout();
      onLogout();
    } catch (error) {
      console.error('Logout failed:', error);
    }
  };

  if (error) {
    return (
      <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center p-4">

        <div className="bg-white dark:bg-gray-800 rounded-xl p-6 max-w-md w-full text-center shadow-lg">

          <div className="w-12 h-12 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center mx-auto mb-4">

            <span className="text-red-500 text-2xl">⚠️</span>

          </div>

          <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-2">Connection Error</h2>

          <p className="text-gray-600 dark:text-gray-400 mb-4">{error}</p>

          <button

            onClick={loadConversations}

            className="bg-primary-500 hover:bg-primary-600 text-white font-medium py-2 px-6 rounded-lg transition-colors"

          >

            Try Again

          </button>

        </div>

      </div>
    );
  }

  return (
    <div className="flex h-screen bg-gray-50 dark:bg-gray-900">

      {/* Sidebar */}

      <Sidebar

        conversations={conversations}

        selectedConversation={selectedConversation}

        onSelectConversation={handleSelectConversation}

        onNewConversation={handleNewConversation}

        onlineUsers={onlineUsers}

      />



      {/* Main Content */}

      <div className="flex-1 flex flex-col min-h-0">

        {isLoading ? (

          <div className="flex-1 flex items-center justify-center">

            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-500"></div>

          </div>

        ) : !selectedConversation ? (

          <div className="flex-1 flex items-center justify-center bg-gray-50 dark:bg-gray-800">

            <div className="text-center p-8 max-w-md">

              <div className="w-24 h-24 mx-auto mb-6 bg-gradient-to-br from-blue-100 to-blue-200 dark:from-blue-900 dark:to-blue-800 rounded-full flex items-center justify-center">

                <svg className="w-12 h-12 text-blue-500 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">

                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />

                </svg>

              </div>

              <h3 className="text-2xl font-bold text-gray-900 dark:text-white mb-2">

                Welcome to YSNRFD Messenger

              </h3>

              <p className="text-gray-600 dark:text-gray-400 mb-6">

                Select a conversation from the sidebar to start messaging, or create a new one to begin connecting.

              </p>

              <div className="space-y-3 text-sm text-gray-500 dark:text-gray-400">

                <div className="flex items-center justify-center space-x-2">

                  <span className="w-2 h-2 bg-green-500 rounded-full"></span>

                  <span>Real-time messaging</span>

                </div>

                <div className="flex items-center justify-center space-x-2">

                  <span className="w-2 h-2 bg-green-500 rounded-full"></span>

                  <span>File sharing</span>

                </div>

                <div className="flex items-center justify-center space-x-2">

                  <span className="w-2 h-2 bg-green-500 rounded-full"></span>

                  <span>Group chats</span>

                </div>

                <div className="flex items-center justify-center space-x-2">

                  <span className="w-2 h-2 bg-green-500 rounded-full"></span>

                  <span>Read receipts</span>

                </div>

              </div>

            </div>

          </div>

        ) : (

          <>

            <div className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between px-4 sm:px-6 py-3">

              <div className="flex items-center space-x-3">

                <button

                  className="sm:hidden p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 focus:outline-none"

                  onClick={() => document.querySelector('.sidebar-container')?.classList.toggle('hidden')}

                >

                  <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">

                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h7" />

                  </svg>

                </button>

                <div className="flex items-center space-x-3">

                  <div className="w-10 h-10 bg-gradient-to-br from-primary-400 to-primary-600 rounded-full flex items-center justify-center text-white font-medium">

                    {selectedConversation.type === 'direct' ? (

                      <span>{selectedConversation.participants.find(p => p.user._id !== user.id)?.user.displayName.charAt(0) || 'U'}</span>

                    ) : (

                      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">

                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />

                      </svg>

                    )}

                  </div>

                  <div>

                    <h1 className="text-lg font-semibold text-gray-900 dark:text-white">

                      {selectedConversation.type === 'direct'

                        ? selectedConversation.participants.find(p => p.user._id !== user.id)?.user.displayName

                        : selectedConversation.name}

                    </h1>

                    <p className="text-sm text-gray-500 dark:text-gray-400">

                      {selectedConversation.type === 'direct'

                        ? 'Direct message'

                        : `${selectedConversation.participants.length} members`}

                    </p>

                  </div>

                </div>

              </div>

              <div className="flex items-center space-x-3">

                <button

                  onClick={handleLogoutUser}

                  className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"

                  title="Logout"

                >

                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">

                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />

                  </svg>

                </button>

              </div>

            </div>



            {/* Chat Area */}

            <ChatArea

              conversation={selectedConversation}

              messages={messages}

              onNewMessage={handleNewMessage}

              onConversationUpdate={handleConversationUpdate}

            />

          </>

        )}

      </div>

      {/* User Search Modal */}
      {showNewConversation && (
        <UserSearch

          onClose={() => setShowNewConversation(false)}

          onConversationCreated={handleConversationCreated}

        />
      )}
    </div>
  );
};

export default Dashboard;