File size: 16,519 Bytes
57f5158
4bae792
4c47e22
4bae792
 
 
 
 
 
91939c2
 
 
 
 
4bae792
477a7c3
c7dfb39
4c47e22
4bae792
b4bf04d
 
57f5158
b4bf04d
4c47e22
 
 
57f5158
 
 
b4bf04d
57f5158
880ab03
 
 
 
 
8c762ac
4bae792
 
 
 
 
4c47e22
 
 
57f5158
4bae792
91939c2
 
 
 
aa61a49
b4bf04d
c7dfb39
 
91939c2
4c47e22
4bae792
c7dfb39
4bae792
c7dfb39
4bae792
 
 
 
 
 
c7dfb39
 
 
 
 
 
57f5158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c762ac
 
 
 
 
 
 
 
 
 
 
 
4c47e22
 
 
b4bf04d
 
 
 
 
 
 
 
 
4c47e22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57f5158
 
 
 
b4bf04d
 
 
 
 
 
 
 
 
 
 
57f5158
b4bf04d
4c47e22
b4bf04d
 
 
 
 
 
 
 
 
 
4c47e22
 
 
 
 
 
 
 
 
57f5158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c47e22
 
 
57f5158
4c47e22
 
 
 
b4bf04d
 
 
57f5158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
880ab03
1835767
880ab03
57f5158
880ab03
 
 
 
 
 
 
57f5158
 
 
 
 
 
 
 
 
 
 
 
 
 
880ab03
57f5158
1835767
57f5158
 
 
880ab03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57f5158
 
 
 
b4bf04d
57f5158
4c47e22
57f5158
b4bf04d
 
57f5158
 
 
 
 
 
b4bf04d
 
 
4bae792
 
57f5158
 
4c47e22
4bae792
 
 
 
 
 
57f5158
 
 
 
 
c7dfb39
 
 
 
91939c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bae792
 
 
 
 
4c47e22
 
 
 
 
91939c2
 
4bae792
477a7c3
 
 
 
4bae792
 
91939c2
 
 
 
 
 
 
 
 
 
 
 
 
aa61a49
91939c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bae792
 
91939c2
 
 
 
aa61a49
 
b4bf04d
 
 
4bae792
91939c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bae792
 
 
 
 
 
 
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
import { useEffect, useState, useRef } from "react";
import { useSelector, useDispatch } from "react-redux";
import { store } from "./store/store.js";
import "./App.css";
import Sidebar from "./components/Sidebar";
import RoomList from "./components/RoomList";
import ChatArea from "./components/ChatArea";
import MemberList from "./components/MemberList";
import CreateSpace from "./components/createspace/CreateSpace";
import CreateAgent from "./components/createspace/CreateAgent";
import CreateSpaceTips from "./components/createspace/CreateSpaceTips";
import CreateAgentTips from "./components/createspace/CreateAgentTips";
import ManageAgent from "./components/createspace/ManageAgent";
import ManageAgentTips from "./components/createspace/ManageAgentTips";
import LoginPage from "./pages/LoginPage";
import TADashboard from "./pages/TADashboard";
import StudentQuizPage from "./pages/StudentQuizPage";
import AppLoadingScreen from "./components/AppLoadingScreen";
import { initializeAuth } from "./store/slices/authSlice";
import {
  addMessage as addDMMessage,
  updateMessage as updateDMMessage,
  updateConversationLastMessage,
  incrementUnreadCount,
  addConversation,
  clearUnreadCount,
  setOnlineUsers,
  updateUserStatus,
  preloadAllData,
} from "./store/slices/dmSlice";
import { addMessage } from "./store/slices/messageSlice";
import {
  updateRoomLastMessage,
  incrementRoomUnreadCount,
  addJoinedRoom,
} from "./store/slices/spaceSlice";
import socketService from "./services/socket.service";

function App() {
  const dispatch = useDispatch();
  const { activeView, activeSpace, activeRoom, searchQuery, isSettings } =
    useSelector((state) => state.app);
  const { isAuthenticated, initialized, loading, isLoggingOut } = useSelector(
    (state) => state.auth,
  );
  const { appLoading, appLoadingPhase } = useSelector((state) => state.app);

  const [createTab, setCreateTab] = useState("space");
  const [editingAgent, setEditingAgent] = useState(null);
  const [roomListCollapsed, setRoomListCollapsed] = useState(false);
  const [memberListCollapsed, setMemberListCollapsed] = useState(false);
  const [isCreatingRoom, setIsCreatingRoom] = useState(false);
  const [isRoomSettingsOpen, setIsRoomSettingsOpen] = useState(false);
  const [routePath, setRoutePath] = useState(window.location.pathname);
  const quizRouteMatch = routePath.match(/^\/quiz\/([^/]+)$/);

  // 1. Auth initialization
  useEffect(() => {
    if (window.location.pathname !== "/" && !window.location.pathname.match(/^\/quiz\/[^/]+$/)) {
      window.history.replaceState(null, "", "/");
      setRoutePath("/");
    }
    if (!initialized && !loading) {
      dispatch(initializeAuth());
    }
  }, [dispatch, initialized, loading]);

  useEffect(() => {
    const handleRouteChange = () => setRoutePath(window.location.pathname);
    window.addEventListener("popstate", handleRouteChange);
    return () => window.removeEventListener("popstate", handleRouteChange);
  }, []);

  // 2. Fetch ALL data once after auth is ready
  const preloadStartTime = useRef(null);
  useEffect(() => {
    if (!isAuthenticated || !initialized) return;
    preloadStartTime.current = performance.now();
    dispatch(preloadAllData());
  }, [isAuthenticated, initialized, dispatch]);

  // Log preload time when loading finishes
  useEffect(() => {
    if (!appLoading && preloadStartTime.current !== null) {
      const elapsed = Math.round(performance.now() - preloadStartTime.current);
      console.log(`%c[Preload] Tất cả data đã load xong trong ${elapsed}ms`, "color: #22c55e; font-weight: bold; font-size: 14px;");
      preloadStartTime.current = null;
    }
  }, [appLoading]);

  // 3. Connect WebSocket when authenticated
  useEffect(() => {
    if (isAuthenticated) {
      socketService.connect();
    } else {
      socketService.disconnect();
    }

    return () => {
      socketService.disconnect();
    };
  }, [isAuthenticated]);

  // ============================================
  // Global WebSocket DM Listener — REGISTERED ONCE ONLY
  // ============================================
  useEffect(() => {
    if (!isAuthenticated) return;

    const handleNewDM = (data) => {
      if (!data?.id) return;

      const conversationId = data.conversation_id || data.conversationId;
      if (!conversationId) return;

      const now = Date.now();
      const isOwn = String(data.sender_id) === String(store.getState().auth.user?.id);
      if (!isOwn && data.clientSentAt) {
        const receiveDelay = now - data.clientSentAt;
        console.log(
          `%c[DM Latency] RECEIVE | delay: ${receiveDelay}ms | from: ${data.sender?.display_name || data.sender_id} | msgId: ${data.id}`,
          "color: #3b82f6; font-weight: bold;",
        );
      }

      const state = store.getState();
      const currentConversations = state.dm.conversations;
      const currentActiveId = state.dm.activeConversationId;
      const currentUserId = state.auth.user?.id;

      const convExists = currentConversations.some((c) => c.id === conversationId);
      if (!convExists && data.conversation) {
        dispatch(addConversation(data.conversation));
      } else if (!convExists && data.sender) {
        dispatch(
          addConversation({
            id: conversationId,
            other_user: data.sender,
            last_message: {
              id: data.id,
              content: data.content,
              created_at: data.created_at || data.timestamp,
            },
            unread_count: 0,
            created_at: data.created_at || data.timestamp,
          }),
        );
      }

      if (!convExists) {
        socketService.joinDM(conversationId);
      }

      dispatch(
        addDMMessage({
          conversationId,
          message: {
            id: data.id,
            conversation_id: conversationId,
            sender_id: data.sender_id,
            content: data.content,
            is_read: data.is_read ?? false,
            created_at: data.created_at || data.timestamp,
            sender: data.sender,
            tempId: data.tempId || data.temp_id,
          },
        }),
      );

      dispatch(
        updateConversationLastMessage({
          conversationId,
          message: {
            id: data.id,
            content: data.content,
            created_at: data.created_at || data.timestamp,
          },
        }),
      );

      const isOwnMessage = String(data.sender_id) === String(currentUserId);
      if (conversationId !== currentActiveId && !isOwnMessage) {
        dispatch(incrementUnreadCount({ conversationId }));
      }
    };

    const handleDmSent = (data) => {
      if (!data?.success || !data?.message) return;
      const msg = data.message;
      const conversationId = msg.conversation_id || msg.conversationId;
      const tempId = data.tempId || data.temp_id;
      if (!conversationId) return;

      dispatch(
        addDMMessage({
          conversationId,
          message: {
            id: msg.id,
            conversation_id: conversationId,
            sender_id: msg.sender_id,
            content: msg.content,
            is_read: msg.is_read ?? false,
            created_at: msg.created_at || msg.timestamp,
            sender: msg.sender,
            tempId,
          },
        }),
      );

      dispatch(
        updateConversationLastMessage({
          conversationId,
          message: {
            id: msg.id,
            content: msg.content,
            created_at: msg.created_at || msg.timestamp,
          },
        }),
      );
    };

    const handleDmMarkedRead = (data) => {
      if (!data?.conversationId || !data?.messageId) return;
      dispatch(
        updateDMMessage({
          conversationId: data.conversationId,
          messageId: data.messageId,
          updates: { is_read: true },
        }),
      );
    };

    const handleConnected = (data) => {
      if (data?.onlineUsers) {
        dispatch(setOnlineUsers(data.onlineUsers));
      }
    };

    const handleUserStatusChanged = (data) => {
      if (!data?.userId) return;
      dispatch(updateUserStatus({ userId: data.userId, status: data.status }));
    };

    const handleNewMessage = (data) => {
      console.log("[App] newMessage received:", JSON.stringify(data, null, 2));
      const roomId = data.room_id || data.roomId;
      const content = data.content;
      const author = data.author;
      const senderId = data.user_id || data.senderId;
      const id = data.id;
      const tempId = data.tempId;

      if (!roomId || (!content && !data.attachments?.length)) return;

      console.log("[App] newMessage parsed:", { roomId, id, tempId, author, senderId });

      const state = store.getState();
      const currentActiveRoom = state.app.activeRoom;
      const currentUserId = state.auth.user?.id;
      const isOwnMessage = String(senderId) === String(currentUserId);

      // 1. Save message to Redux
      dispatch(
        addMessage({
          roomId,
          message: {
            id: id || Date.now(),
            sender: {
              id: senderId,
              display_name: author?.display_name || author?.username || "Unknown",
              avatar_url: author?.avatar_url || null,
            },
            sender_id: senderId,
            content,
            created_at: data.created_at || new Date().toISOString(),
            isPinned: data.is_pinned || false,
            isOwn: isOwnMessage,
            tempId,
            attachments: data.attachments || [],
          },
        }),
      );

      // 2. Update room's last_message in spaceSlice (for RoomList display)
      dispatch(
        updateRoomLastMessage({
          roomId,
          message: {
            id: id || Date.now(),
            content,
            created_at: data.created_at || new Date().toISOString(),
            sender_id: senderId,
            sender: author,
          },
        }),
      );

      // 3. Increment unread count if not viewing this room and not own message
      if (roomId !== currentActiveRoom && !isOwnMessage) {
        dispatch(incrementRoomUnreadCount({ roomId }));
      }
    };

    socketService.onConnected(handleConnected);
    socketService.onUserStatusChanged(handleUserStatusChanged);
    socketService.onNewDM(handleNewDM);
    socketService.onDmSent(handleDmSent);
    socketService.onDmMarkedRead(handleDmMarkedRead);
    socketService.onNewMessage(handleNewMessage);

    return () => {
      socketService.off("connected", handleConnected);
      socketService.off("userStatusChanged", handleUserStatusChanged);
      socketService.off("newDM", handleNewDM);
      socketService.off("dmSent", handleDmSent);
      socketService.off("dmMarkedRead", handleDmMarkedRead);
      socketService.off("newMessage", handleNewMessage);
    };
  }, [isAuthenticated, dispatch]);

  const currentView = isSettings ? "settings" : activeView;

  // Not initialized yet (checking auth state) OR logging out
  if (!initialized || isLoggingOut) {
    return <AppLoadingScreen />;
  }

  if (!isAuthenticated) {
    return <LoginPage />;
  }

  // 🆕 Loading all data after login
  if (appLoading) {
    return <AppLoadingScreen />;
  }

  if (quizRouteMatch) {
    return <StudentQuizPage quizId={quizRouteMatch[1]} />;
  }

  const handleEditAgent = (agent) => {
    setEditingAgent(agent);
    setCreateTab("editAgent");
  };

  const handleCancelEdit = () => {
    setEditingAgent(null);
    setCreateTab("manageAgent");
  };

  const renderCreateContent = () => {
    switch (createTab) {
      case "agent":
        return <CreateAgent />;
      case "manageAgent":
        return <ManageAgent onEditAgent={handleEditAgent} />;
      case "editAgent":
        return (
          <CreateAgent
            editMode
            initialData={editingAgent}
            onCancel={handleCancelEdit}
          />
        );
      default:
        return <CreateSpace />;
    }
  };

  const renderCreateTips = () => {
    switch (createTab) {
      case "agent":
        return <CreateAgentTips />;
      case "manageAgent":
        return <ManageAgentTips />;
      case "editAgent":
        return <CreateAgentTips />;
      default:
        return <CreateSpaceTips />;
    }
  };

  return (
    <div className="w-screen h-screen flex overflow-hidden">
      <Sidebar />
      {currentView === "createSpace" ? (
        <>
          <RoomList
            activeView="createSpace"
            createTab={createTab}
            onCreateTabChange={setCreateTab}
          />
          {renderCreateContent()}
          {renderCreateTips()}
        </>
      ) : currentView === "dashboard" ? (
        <>
          <TADashboard />
        </>
      ) : (
        <>
          <div
            className="flex-shrink-0 h-screen overflow-hidden transition-all duration-300 ease-in-out"
            style={{
              width: roomListCollapsed ? 0 : 240,
              minWidth: roomListCollapsed ? 0 : 240,
              opacity: roomListCollapsed ? 0 : 1,
            }}
          >
            <RoomList
              activeView={currentView}
              activeSpace={activeSpace}
              activeRoom={activeRoom}
              searchQuery={searchQuery}
              onCreateRoomClick={() => setIsCreatingRoom(true)}
            />
          </div>

          {/* Collapsed room list indicator */}
          {roomListCollapsed && (
            <div
              className="flex-shrink-0 h-screen flex flex-col items-center justify-center cursor-pointer border-r transition-colors duration-200"
              style={{
                width: 8,
                minWidth: 8,
                background: "var(--bg-surface-secondary)",
                borderColor: "var(--border-primary)",
              }}
              onClick={() => setRoomListCollapsed(false)}
              onMouseEnter={(e) => {
                e.currentTarget.style.background = "var(--hover-primary)";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background = "var(--bg-surface-secondary)";
              }}
              title="Hiện danh sách room"
            >
              <div
                className="w-[2px] h-8 rounded-full"
                style={{ background: "var(--border-primary)" }}
              />
            </div>
          )}

          <ChatArea
            activeView={currentView}
            activeRoom={activeRoom}
            onToggleRoomList={() => setRoomListCollapsed((p) => !p)}
            onToggleMemberList={() => setMemberListCollapsed((p) => !p)}
            roomListCollapsed={roomListCollapsed}
            memberListCollapsed={memberListCollapsed}
            isCreatingRoom={isCreatingRoom}
            onCancelCreateRoom={() => setIsCreatingRoom(false)}
            isRoomSettingsOpen={isRoomSettingsOpen}
            onOpenRoomSettings={() => setIsRoomSettingsOpen(true)}
            onCloseRoomSettings={() => setIsRoomSettingsOpen(false)}
          />

          {/* Collapsed member list indicator */}
          {memberListCollapsed && (
            <div
              className="flex-shrink-0 h-screen flex flex-col items-center justify-center cursor-pointer border-l transition-colors duration-200"
              style={{
                width: 8,
                minWidth: 8,
                background: "var(--bg-surface-secondary)",
                borderColor: "var(--border-primary)",
              }}
              onClick={() => setMemberListCollapsed(false)}
              onMouseEnter={(e) => {
                e.currentTarget.style.background = "var(--hover-primary)";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background = "var(--bg-surface-secondary)";
              }}
              title="Hiện danh sách thành viên"
            >
              <div
                className="w-[2px] h-8 rounded-full"
                style={{ background: "var(--border-primary)" }}
              />
            </div>
          )}

          <div
            className="flex-shrink-0 h-screen overflow-hidden transition-all duration-300 ease-in-out"
            style={{
              width: memberListCollapsed ? 0 : 240,
              minWidth: memberListCollapsed ? 0 : 240,
              opacity: memberListCollapsed ? 0 : 1,
            }}
          >
            <MemberList activeView={currentView} activeRoom={activeRoom} />
          </div>
        </>
      )}
    </div>
  );
}

export default App;