File size: 18,628 Bytes
4c47e22
57f5158
4c47e22
b4bf04d
4bae792
 
c7dfb39
4bae792
4c47e22
57f5158
4bae792
8c762ac
 
 
 
 
 
 
57f5158
8c762ac
fe7c2ba
 
b4bf04d
57f5158
c7dfb39
 
 
 
 
 
4bae792
 
 
 
 
b4bf04d
8c762ac
4bae792
b4bf04d
 
4bae792
 
fe7c2ba
4bae792
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57f5158
8c762ac
 
 
 
 
 
 
 
 
 
57f5158
 
 
 
 
 
 
 
 
 
 
4bae792
b4bf04d
4bae792
 
 
 
 
c7dfb39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7f19c4
4bae792
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57f5158
 
 
 
 
 
 
 
 
 
 
 
 
 
4bae792
 
 
 
 
c7dfb39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
521104b
4bae792
a7f19c4
 
 
 
 
521104b
 
 
 
 
4bae792
521104b
4bae792
 
 
521104b
 
4bae792
521104b
4bae792
 
 
521104b
 
4bae792
521104b
4bae792
 
 
521104b
4bae792
 
 
 
8c762ac
 
 
 
fe7c2ba
8c762ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
880ab03
4bae792
 
 
fe7c2ba
4bae792
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
880ab03
 
 
 
 
 
 
4bae792
 
 
 
 
880ab03
 
 
 
 
 
 
4bae792
 
 
 
 
 
 
 
 
 
 
 
 
880ab03
 
8c762ac
 
b4bf04d
57f5158
 
4bae792
4c47e22
4bae792
 
4c47e22
8c762ac
 
b4bf04d
4c47e22
 
57f5158
 
 
 
4c47e22
 
 
57f5158
8c762ac
b4bf04d
8c762ac
 
 
 
b4bf04d
 
 
 
 
8c762ac
 
 
 
4d3f8c3
8c762ac
 
 
 
 
 
 
b4bf04d
 
4bae792
 
4c47e22
 
 
 
 
 
 
57f5158
4c47e22
57f5158
a7f19c4
 
 
 
57f5158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c47e22
 
57f5158
4c47e22
4bae792
 
 
880ab03
4bae792
 
 
 
880ab03
4bae792
 
880ab03
8c762ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
880ab03
8c762ac
4bae792
 
57f5158
 
 
 
 
 
a7f19c4
 
 
 
57f5158
 
 
a7f19c4
 
 
 
57f5158
 
 
a7f19c4
 
 
 
57f5158
 
a7f19c4
 
 
 
57f5158
 
 
 
 
4bae792
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57f5158
4bae792
 
 
57f5158
4bae792
 
521104b
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
import { useState, useRef, useEffect, useCallback } from "react";
import { FiPaperclip, FiRefreshCw } from "react-icons/fi";
import { useDispatch } from "react-redux";
import { ReplyPreview } from "./MessageActions";
import { renderMessageWithMentions } from "./MessageContent";
import FileAttachment from "./FileAttachment";
import QuizCard from "./QuizCard";
import { getUserColor } from "../../utils/userColor";
import { fetchMessages } from "../../store/slices/dmSlice";
import { fetchRoomMessages } from "../../store/slices/messageSlice";

function ChatMessage({
  msg,
  isDark,
  onReply,
  onEdit,
  onShowProfile,
  isSending,
  onRetry,
}) {
  const senderColor = getUserColor(msg.sender, msg.color);
  const isOwnMessage = msg.isOwn;
  const [isHovered, setIsHovered] = useState(false);
  const isFailed = msg.failed || isSending?.failed;
  const quizCardData = parseQuizMessage(msg.content);

  const handlePlayQuiz = (quizId) => {
    window.history.pushState(null, "", `/quiz/${quizId}`);
    window.dispatchEvent(new PopStateEvent("popstate"));
  };

  return (
    <div
      className="flex gap-3 px-3 py-2 rounded-lg transition-colors relative group"
      style={{
        background: isHovered ? "var(--hover-primary)" : "transparent",
        opacity: msg.pending ? 0.6 : 1,
      }}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      <div
        className="w-9 h-9 rounded-lg flex items-center justify-center text-sm font-semibold shrink-0 cursor-pointer"
        style={{
          background: msg.isBot ? "var(--tertiary-active)" : senderColor,
          color: msg.isBot
            ? "var(--tertiary)"
            : isDark
              ? "var(--bg-surface)"
              : "#fff",
          fontSize: msg.isBot ? "1.25rem" : "0.875rem",
        }}
        onClick={() => onShowProfile && onShowProfile(msg.sender)}
      >
        {msg.avatar}
      </div>
      <div className="flex-1 min-w-0">
        {/* Sender name and timestamp first */}
        <div className="flex items-baseline gap-2 mb-1">
          <span
            className="text-[13px] font-semibold cursor-pointer"
            style={{
              color: msg.isBot ? "var(--tertiary)" : senderColor,
            }}
            onClick={() => onShowProfile && onShowProfile(msg.sender)}
          >
            {msg.sender}
          </span>
          {msg.isBot && (
            <span
              className="text-[10px] px-1.5 py-0.5 rounded font-medium"
              style={{
                background: "var(--tertiary-active)",
                color: "var(--tertiary)",
              }}
            >
              Bot
            </span>
          )}
          <span className="text-[11px]" style={{ color: "var(--text-muted)" }}>
            {msg.timestamp}
          </span>
          {msg.pending && !isFailed && (
            <span
              className="text-[10px] italic ml-1"
              style={{
                color: "var(--primary)",
                fontWeight: 500,
              }}
            >
              · Đang gửi...
            </span>
          )}
          {isFailed && (
            <span
              className="text-[10px] italic ml-1"
              style={{
                color: "#ef4444",
                fontWeight: 500,
              }}
            >
              · Gửi thất bại
            </span>
          )}
        </div>

        {/* Message content */}
        <div
          className="text-sm leading-relaxed"
          style={{ color: "var(--text-primary)" }}
        >
          {quizCardData ? (
            <QuizCard
              quizId={quizCardData.quizId}
              quizTitle={quizCardData.quizTitle}
              questionCount={quizCardData.questionCount}
              passingScore={quizCardData.passingScore}
              onPlay={handlePlayQuiz}
            />
          ) : (
            renderMessageWithMentions(
              msg.content,
              isDark,
              onShowProfile,
              msg.isBot,
            )
          )}
          {msg.isEdited && (
            <span
              className="ml-1 text-[10px] italic"
              style={{ color: "var(--text-muted)" }}
            >
              (đã chỉnh sửa)
            </span>
          )}
        </div>
        {msg.hasAttachment && msg.attachments && msg.attachments.length > 0 ? (
          <div className="mt-2 space-y-2">
            {msg.attachments.map((attachment, index) => (
              <FileAttachment
                key={index}
                attachment={attachment}
                isDark={isDark}
              />
            ))}
          </div>
        ) : msg.hasAttachment ? (
          <div
            className="flex items-center gap-2 mt-2 px-3 py-2 border rounded-md text-sm cursor-pointer"
            style={{
              background: "var(--card-bg)",
              borderColor: "var(--border-primary)",
              color: "var(--primary)",
            }}
          >
            <FiPaperclip size={14} /> {msg.attachmentName}
          </div>
        ) : null}

        {/* Retry button for failed messages */}
        {isFailed && onRetry && (
          <button
            onClick={() => onRetry(msg)}
            className="mt-1.5 flex items-center gap-1 text-xs font-medium cursor-pointer transition-colors"
            style={{ color: "#ef4444" }}
            onMouseEnter={(e) => (e.currentTarget.style.color = "#dc2626")}
            onMouseLeave={(e) => (e.currentTarget.style.color = "#ef4444")}
          >
            <FiRefreshCw size={12} />
            Thử lại
          </button>
        )}
      </div>
    </div>
  );
}

function parseQuizMessage(content) {
  if (!content || typeof content !== "string" || !content.includes("Quiz ID")) {
    return null;
  }

  const quizId = content.match(/Quiz ID:\s*`?([0-9a-f-]{36})`?/i)?.[1];
  if (!quizId) return null;

  const title =
    content.match(/\*\*([^*]+)\*\*/)?.[1]?.trim() ||
    content.match(/^#?\s*(.+)$/m)?.[1]?.trim() ||
    "Quiz";

  const questionCount = Number(content.match(/(\d+)\s*câu hỏi/i)?.[1] || 0);
  const passingScore = Number(content.match(/Cần\s*(\d+)\s*điểm/i)?.[1] || 60);

  return {
    quizId,
    quizTitle: title,
    questionCount,
    passingScore,
  };
}

function TypingIndicator({ isDark, senderName = "Đang nhập" }) {
  return (
    <div
      className="flex items-center gap-2 px-4 py-1.5"
      style={{ background: "transparent" }}
    >
      <span className="text-xs italic" style={{ color: "var(--primary)" }}>
        {senderName} đang nhập
      </span>
      <span className="flex gap-0.5">
        <span
          className="w-1 h-1 rounded-full animate-bounce"
          style={{
            background: "var(--primary)",
            animationDelay: "0ms",
          }}
        />
        <span
          className="w-1 h-1 rounded-full animate-bounce"
          style={{
            background: "var(--primary)",
            animationDelay: "150ms",
          }}
        />
        <span
          className="w-1 h-1 rounded-full animate-bounce"
          style={{
            background: "var(--primary)",
            animationDelay: "300ms",
          }}
        />
      </span>
    </div>
  );
}

function MessageSkeleton({ isDark, width = "75%", showSecondLine = true }) {
  return (
    <div className="flex gap-3 px-3 py-3 animate-pulse">
      <div
        className="w-9 h-9 rounded-lg flex-shrink-0"
        style={{
          background: isDark ? "rgba(255,255,255,0.1)" : "rgba(0,0,0,0.08)",
        }}
      />
      <div className="flex-1 min-w-0 space-y-2">
        <div className="flex items-center gap-2">
          <div
            className="h-3.5 w-24 rounded"
            style={{
              background: isDark ? "rgba(255,255,255,0.1)" : "rgba(0,0,0,0.08)",
            }}
          />
          <div
            className="h-3 w-12 rounded"
            style={{
              background: isDark
                ? "rgba(255,255,255,0.06)"
                : "rgba(0,0,0,0.05)",
            }}
          />
        </div>
        <div
          className="h-4 rounded"
          style={{
            background: isDark ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)",
            width: width,
          }}
        />
        {showSecondLine && (
          <div
            className="h-4 rounded"
            style={{
              background: isDark
                ? "rgba(255,255,255,0.08)"
                : "rgba(0,0,0,0.06)",
              width: "50%",
            }}
          />
        )}
      </div>
    </div>
  );
}

function EmptyChatState({ dmUser, isDark, hasNoSelection, spaceWelcome }) {
  return (
    <div className="flex flex-col items-center justify-center px-6 text-center">
      <div
        className="w-20 h-20 rounded-lg flex items-center justify-center mb-5"
        style={{
          background: isDark ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.03)",
        }}
      >
        <svg
          width="36"
          height="36"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinecap="round"
          strokeLinejoin="round"
          style={{ color: "var(--text-muted)" }}
        >
          <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
        </svg>
      </div>
      <div
        className="text-base font-semibold mb-2"
        style={{ color: "var(--text-primary)" }}
      >
        {spaceWelcome
          ? spaceWelcome.title
          : hasNoSelection
            ? "Chọn một cuộc trò chuyện"
            : dmUser
              ? `Bắt đầu trò chuyện với ${dmUser.name}`
              : "Chưa có tin nhắn nào"}
      </div>
      <div
        className="text-sm leading-relaxed max-w-xs"
        style={{ color: "var(--text-muted)" }}
      >
        {spaceWelcome
          ? spaceWelcome.description
          : hasNoSelection
            ? "Hãy chọn một ngườii bạn bên trái để bắt đầu nhắn tin."
            : dmUser
              ? "Hãy gửi lờii chào hoặc câu hỏi để bắt đầu cuộc trò chuyện đầu tiên nhé!"
              : "Chọn một cuộc trò chuyện để bắt đầu nhắn tin."}
      </div>
    </div>
  );
}

function ChatMessages({
  isDark,
  chatMessages,
  dmUser,
  onReply,
  onEdit,
  onShowProfile,
  hasNoSelection,
  spaceWelcome,
  isKnownEmpty,
  sendingMessages,
  isLoading,
  conversationId,
  roomId,
  onRetry,
}) {
  const dispatch = useDispatch();
  const messagesContainerRef = useRef(null);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const prevLoadingRef = useRef(isLoading);
  const prevMessagesLengthRef = useRef(chatMessages.length);
  const prevConversationIdRef = useRef(conversationId);
  const hasMoreMessagesRef = useRef(true);

  // Track if we have cached messages displayed while background loading
  const hasCachedMessages = chatMessages.length > 0 && isLoading;

  // Reset pagination state when conversation or room changes
  useEffect(() => {
    setCurrentPage(1);
    hasMoreMessagesRef.current = true;
  }, [conversationId, roomId]);

  // Auto scroll to bottom when loading finishes, new messages arrive, or conversation changes
  useEffect(() => {
    const container = messagesContainerRef.current;
    if (!container) return;

    // Scroll to bottom when conversation changes
    if (prevConversationIdRef.current !== conversationId) {
      container.scrollTop = container.scrollHeight;
    }

    // Scroll to bottom when loading finishes
    if (prevLoadingRef.current && !isLoading) {
      container.scrollTop = container.scrollHeight;
    }

    // Scroll to bottom when new messages added (but not when loading more)
    if (chatMessages.length > prevMessagesLengthRef.current && !isLoadingMore) {
      container.scrollTop = container.scrollHeight;
    }

    prevLoadingRef.current = isLoading;
    prevMessagesLengthRef.current = chatMessages.length;
    prevConversationIdRef.current = conversationId;
  }, [isLoading, chatMessages.length, isLoadingMore, conversationId]);

  // Handle scroll event to detect when user reaches the top
  const handleScroll = useCallback(
    (e) => {
      const container = e.target;
      // Check if scrolled to top (within 10px threshold)
      if (
        container.scrollTop < 10 &&
        !isLoadingMore &&
        hasMoreMessagesRef.current
      ) {
        // DM pagination
        if (
          conversationId &&
          !conversationId.toString().startsWith("temp-conv-")
        ) {
          setIsLoadingMore(true);
          const nextPage = currentPage + 1;
          dispatch(
            fetchMessages({
              conversationId,
              page: nextPage,
              limit: 50,
            }),
          )
            .unwrap()
            .then((result) => {
              const fetched = result.messages || [];
              if (fetched.length === 0) {
                hasMoreMessagesRef.current = false;
              } else {
                setCurrentPage(nextPage);
              }
            })
            .catch((err) => {
              console.error("[ChatMessages] Failed to load more DM:", err);
            })
            .finally(() => {
              setIsLoadingMore(false);
            });
        }
        // Room pagination
        else if (roomId) {
          setIsLoadingMore(true);
          const nextPage = currentPage + 1;
          dispatch(
            fetchRoomMessages({
              roomId,
              page: nextPage,
              limit: 50,
            }),
          )
            .unwrap()
            .then((result) => {
              const fetched = result.messages || [];
              if (fetched.length === 0) {
                hasMoreMessagesRef.current = false;
              } else {
                setCurrentPage(nextPage);
              }
            })
            .catch((err) => {
              console.error("[ChatMessages] Failed to load more room:", err);
            })
            .finally(() => {
              setIsLoadingMore(false);
            });
        }
      }
    },
    [isLoadingMore, currentPage, conversationId, roomId, dispatch],
  );

  const hasMessages = chatMessages.length > 0;

  const isEmpty = !hasMessages && (!isLoading || isKnownEmpty);

  return (
    <div
      ref={messagesContainerRef}
      className={`flex-1 p-4 ${isEmpty ? "flex items-center justify-center overflow-hidden" : ` ${isLoading && !isKnownEmpty ? "overflow-hidden" : "overflow-y-auto"}`}`}
      onScroll={isEmpty ? undefined : handleScroll}
    >
      {isLoading && !hasMessages && !isKnownEmpty ? (
        <div className="flex flex-col gap-2 w-full min-h-full justify-end pb-2">
          <MessageSkeleton isDark={isDark} width="60%" showSecondLine={false} />
          <MessageSkeleton isDark={isDark} width="85%" />
          <MessageSkeleton isDark={isDark} width="40%" showSecondLine={false} />
          <MessageSkeleton isDark={isDark} width="70%" />
          <MessageSkeleton isDark={isDark} width="55%" showSecondLine={false} />
          <MessageSkeleton isDark={isDark} width="90%" />
          <MessageSkeleton isDark={isDark} width="45%" showSecondLine={false} />
          <MessageSkeleton isDark={isDark} width="78%" />
          <MessageSkeleton isDark={isDark} width="35%" showSecondLine={false} />
        </div>
      ) : isEmpty ? (
        <EmptyChatState
          dmUser={dmUser}
          isDark={isDark}
          hasNoSelection={hasNoSelection}
          spaceWelcome={spaceWelcome}
        />
      ) : (
        <div className="flex flex-col min-h-full justify-end gap-1 w-full">
          {/* Background loading indicator (when showing cached messages while fetching) */}
          {hasCachedMessages && (
            <div className="flex items-center justify-center gap-2 py-1">
              <div className="flex items-center gap-1">
                <div
                  className="w-1.5 h-1.5 rounded-full animate-pulse"
                  style={{
                    background: "var(--primary)",
                    animationDelay: "0ms",
                  }}
                />
                <div
                  className="w-1.5 h-1.5 rounded-full animate-pulse"
                  style={{
                    background: "var(--primary)",
                    animationDelay: "150ms",
                  }}
                />
                <div
                  className="w-1.5 h-1.5 rounded-full animate-pulse"
                  style={{
                    background: "var(--primary)",
                    animationDelay: "300ms",
                  }}
                />
              </div>
              <span
                className="text-[10px]"
                style={{ color: "var(--text-muted)" }}
              >
                Đang cập nhật...
              </span>
            </div>
          )}

          {/* Loading indicator at top when fetching older messages */}
          {isLoadingMore && (
            <div className="flex items-center justify-center gap-2 py-3">
              <div className="flex items-center gap-1">
                <div
                  className="w-2 h-2 rounded-full animate-pulse"
                  style={{
                    background: "var(--tertiary)",
                    animationDelay: "0ms",
                  }}
                />
                <div
                  className="w-2 h-2 rounded-full animate-pulse"
                  style={{
                    background: "var(--tertiary)",
                    animationDelay: "150ms",
                  }}
                />
                <div
                  className="w-2 h-2 rounded-full animate-pulse"
                  style={{
                    background: "var(--tertiary)",
                    animationDelay: "300ms",
                  }}
                />
              </div>
            </div>
          )}

          {chatMessages.map((msg) => (
            <ChatMessage
              key={msg.id}
              msg={msg}
              isDark={isDark}
              isSending={sendingMessages?.[msg.id]}
              onReply={onReply}
              onEdit={onEdit}
              onShowProfile={onShowProfile}
              onRetry={onRetry}
            />
          ))}
          {/* Typing indicator removed — now shown in ChatInput instead */}
        </div>
      )}
    </div>
  );
}

export default ChatMessages;