import { useRef, useEffect } from 'preact/hooks';
import { useChat } from '../hooks/useChat';
import ChatHeader from './ChatHeader';
import MessageList from './MessageList';
import TypingIndicator from './TypingIndicator';
import ChatInput from './ChatInput';

export default function ChatPanel({ isOpen, onClose }) {
    const { messages, isTyping, initialize, sendMessage } = useChat();
    const initializedRef = useRef(false);

    useEffect(() => {
        if (isOpen && !initializedRef.current) {
            initializedRef.current = true;
            initialize();
        }
    }, [isOpen]);

    return (
        <div class={`chat-panel${isOpen ? ' open' : ''}`}>
            <ChatHeader onClose={onClose} />
            <MessageList messages={messages} />
            <TypingIndicator active={isTyping} />
            <ChatInput onSend={sendMessage} disabled={isTyping} />
        </div>
    );
}
