import React, { useEffect, useRef } from 'react';
import { Message } from './useClassroom';
import { useClassroomContext } from './ClassroomProvider';
import { MessageBubble } from './MessageBubble';
import { ScrollArea } from '@/client/components/ui/scroll-area';

interface MessageListProps {
  messages: Message[];
}

export const MessageList: React.FC<MessageListProps> = ({ messages }) => {
  const { userId } = useClassroomContext();
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 自动滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 判断消息是否是自己发送的
  const isOwnMessage = (message: Message): boolean => {
    // 系统消息不算自己的消息
    if (message.type === 'system') return false;
    
    // 只有有senderId且与当前用户ID匹配时才认为是自己的消息
    return message.senderId === userId;
  };

  return (
    <ScrollArea className="flex-1 min-h-0 bg-white p-4">
      <div className="space-y-2">
        {messages.map((message, index) => (
          <MessageBubble
            key={`${message.timestamp}-${index}`}
            message={message}
            isOwnMessage={isOwnMessage(message)}
          />
        ))}
        <div ref={messagesEndRef} />
      </div>
    </ScrollArea>
  );
};