// import { useChatHandler } from "@/components/chat/chat-hooks/use-chat-handler"
// import { ChatbotUIContext } from "@/context/context"
// import { Tables } from "@/supabase/types"
// import { FC, useContext, useState } from "react"
// import { Message } from "../messages/message"

// interface ChatMessagesProps {}

// export const ChatMessages: FC<ChatMessagesProps> = ({}) => {
//   const { chatMessages, chatFileItems } = useContext(ChatbotUIContext)

//   const { handleSendEdit } = useChatHandler()

//   const [editingMessage, setEditingMessage] = useState<Tables<"messages">>()

//   return chatMessages
//     .sort((a, b) => a.message.sequence_number - b.message.sequence_number)
//     .map((chatMessage, index, array) => {
//       const messageFileItems = chatFileItems.filter(
//         (chatFileItem, _, self) =>
//           chatMessage.fileItems.includes(chatFileItem.id) &&
//           self.findIndex(item => item.id === chatFileItem.id) === _
//       )

//       return (
//         <Message
//           key={chatMessage.message.sequence_number}
//           message={chatMessage.message}
//           fileItems={messageFileItems}
//           isEditing={editingMessage?.id === chatMessage.message.id}
//           isLast={index === array.length - 1}
//           onStartEdit={setEditingMessage}
//           onCancelEdit={() => setEditingMessage(undefined)}
//           onSubmitEdit={handleSendEdit}
//         />
//       )
//     })
// }






import { useChatHandler } from "@/components/chat/chat-hooks/use-chat-handler"
import { ChatbotUIContext } from "@/context/context"
import { Tables } from "@/supabase/types"
import { FC, useContext, useState, useRef, useEffect } from "react"
import { Message } from "../messages/message"

interface ChatMessagesProps {}

export const ChatMessages: FC<ChatMessagesProps> = ({}) => {
  const { chatMessages, chatFileItems } = useContext(ChatbotUIContext)
  const { handleSendEdit } = useChatHandler()
  const [editingMessage, setEditingMessage] = useState<Tables<"messages">>()
  
  // 1. 创建一个 ref 指向滚动容器
  const containerRef = useRef<HTMLDivElement>(null)

  // 2. 每次 chatMessages 变化时，滚到底部
  useEffect(() => {
    const dom = containerRef.current
    if (dom) {
      dom.scrollTo({ top: dom.scrollHeight, behavior: "smooth" })
    }
  }, [chatMessages])

  // 先排序
  const sorted = [...chatMessages].sort(
    (a, b) => a.message.sequence_number - b.message.sequence_number
  )

  return (
    // 3. 给外层 div 加上 overflow-auto，并且要有高度限制
    <div
      ref={containerRef}
      className="w-full h-screen overflow-auto"
      style={{ maxHeight: "100vh" }}
    >
      {sorted.map((chatMessage, index, array) => {
        const messageFileItems = chatFileItems.filter(
          (chatFileItem, _, self) =>
            chatMessage.fileItems.includes(chatFileItem.id) &&
            self.findIndex(item => item.id === chatFileItem.id) === _
        )

        return (
          <Message
            key={chatMessage.message.sequence_number}
            message={chatMessage.message}
            fileItems={messageFileItems}
            isEditing={editingMessage?.id === chatMessage.message.id}
            isLast={index === array.length - 1}
            onStartEdit={setEditingMessage}
            onCancelEdit={() => setEditingMessage(undefined)}
            onSubmitEdit={handleSendEdit}
          />
        )
      })}
    </div>
  )
}
