edit the code below and edit the newsession functionality such that it caters for both scenarios where the user sends a initial message on a null session which creates a new session, and where a session is created by using the "new session" button.

the first scenario requires the initial message to be sent, while the second scenario does not require an initial message. Once done with the changes, provide the full updated script.


here is the code:
import React, { useState, useEffect } from 'react';
import { getDatabase, ref, set, push, update, onValue } from 'firebase/database';

const ChatApp = () => {
    const [input, setInput] = useState('');
    const [messages, setMessages] = useState([]);
    const [sessions, setSessions] = useState([]);
    const [currentSession, setCurrentSession] = useState(null);
    const [isSending, setIsSending] = useState(false);
    const db = getDatabase();

    // Load sessions from Firebase
    useEffect(() => {
        const sessionRef = ref(db, chats/${currentUser.uid}/sessions);
        onValue(sessionRef, (snapshot) => {
            const sessionData = snapshot.val();
            if (sessionData) {
                setSessions(Object.entries(sessionData));
            }
        });
    }, [db]);

    const handleSend = async () => {
        if (input.trim() === '' || isSending) return;

        const userMessage = { sender: 'user', text: input };
        setIsSending(true);

        try {
            // If there's no current session, create a new one
            if (!currentSession) {
                // Create a new session with the user's message
                createNewSession(userMessage);
            } else {
                const updatedMessages = [...messages, userMessage];
                setMessages(updatedMessages); // Update state with the new message

                // Save messages to Firebase
                const sessionRef = ref(db, chats/${currentUser.uid}/sessions/${currentSession}/messages);
                await set(sessionRef, updatedMessages); // Save updated messages
            }

            // Chatbot interaction
            const FUNCTION_URL = 'https://us-central1-mind-gardener.cloudfunctions.net/chatWithHuggingFace';
            const response = await fetch(FUNCTION_URL, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ conversationHistory: messages }),
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error || 'Server error');
            }

            const result = await response.json();
            const botReply = result.reply || 'No response from bot';

            // Save bot reply and update messages
            const botMessage = { sender: 'bot', text: botReply };
            const updatedMessagesWithBotReply = [...updatedMessages, botMessage];
            setMessages(updatedMessagesWithBotReply);

            // Save both user and bot messages to Firebase
            const sessionRef = ref(db, chats/${currentUser.uid}/sessions/${currentSession}/messages);
            await set(sessionRef, updatedMessagesWithBotReply);

        } catch (error) {
            setMessages((prev) => [
                ...prev,
                { sender: 'bot', text: Sorry, there was an error: ${error.message} },
            ]);
        } finally {
            setIsSending(false);
            setInput('');
        }
    };

    const createNewSession = (userMessage) => {
        const newSessionLabel = Session ${sessions.length + 1}; // Labeling new session sequentially
        const newSessionRef = push(ref(db, chats/${currentUser.uid}/sessions));
        const sessionId = newSessionRef.key;

        // Initialize messages as an empty array or include the user message
        const initialMessages = userMessage ? [userMessage] : [];

        // Create the session in the database
        update(newSessionRef, { name: newSessionLabel, messages: initialMessages })
            .then(() => {
                setSessions((prev) => [
                    ...prev,
                    [sessionId, { name: newSessionLabel, messages: initialMessages }],
                ]);
                loadSession(sessionId); // Automatically load the new session
            })
            .catch((error) => {
                console.error('Error creating new session:', error);
            });
    };

    const loadSession = (sessionId) => {
        setCurrentSession(sessionId);
        const sessionRef = ref(db, chats/${currentUser.uid}/sessions/${sessionId}/messages);
        onValue(sessionRef, (snapshot) => {
            const messagesData = snapshot.val();
            if (messagesData) {
                setMessages(messagesData);
            } else {
                setMessages([]); // Clear messages if no data
            }
        });
    };

    const handleNewSession = () => {
        // Create a new session without an initial message
        createNewSession(null); // Pass null or undefined if no initial message is needed
    };

    return (
        <div>
            <div className="chatbox">
                {messages.map((msg, index) => (
                    <div key={index} className={msg.sender === 'bot' ? 'bot-message' : 'user-message'}>
                        {msg.text}
                    </div>
                ))}
            </div>
            <input
                value={input}
                onChange={(e) => setInput(e.target.value)}
                placeholder="Type your message..."
            />
            <button onClick={handleSend}>Send</button>
            <button onClick={handleNewSession}>New Session</button>
        </div>
    );
};

export default ChatApp;