import { useContext, useEffect, useRef } from "preact/hooks";
import { StateContext } from "../contexts/state";
import { Message } from "./message/message";
import { MessageTools } from "../tools/messages";
import { DOMTools } from "../tools/dom";

export const Chat = () => {
    const { messages } = useContext(StateContext);
    const chatRef = useRef<HTMLDivElement>(null);

    const lastMessage = messages.at(-1);
    const lastMessageSwipe = MessageTools.getSwipe(lastMessage);
    const lastMessageContent = lastMessageSwipe?.content;
    const lastUserId = messages.findLastIndex(m => m.role === 'user');
    const lastAssistantId = messages.findLastIndex(m => m.role === 'assistant');

    useEffect(() => {
        DOMTools.scrollDown(chatRef.current);
    }, [messages.length, lastMessageContent]);

    return (
        <div class="chat" ref={chatRef}>
            {messages.map((m, i) => (
                <Message
                    message={m}
                    key={i} index={i}
                    isLastUser={i === lastUserId} isLastAssistant={i === lastAssistantId}
                />
            ))}
        </div>
    );
}
