make the apropriate changes.

here are the script
chatpage.js:
import React, { useState, useEffect, useContext, useRef } from 'react';
import { AuthContext } from '../AuthContext';
import { ref, get, update, push, set, remove } from 'firebase/database';
import { db } from '../firebase';
import { TextField, Button, Paper, Typography, List, ListItem, Divider, IconButton, Avatar, Menu, MenuItem, Badge, Switch } from '@mui/material';
import SendIcon from '@mui/icons-material/Send';
import EditIcon from '@mui/icons-material/Edit';
import SaveIcon from '@mui/icons-material/Save';
import DeleteIcon from '@mui/icons-material/Delete';
import LogoutIcon from '@mui/icons-material/Logout';
import Brightness4Icon from '@mui/icons-material/Brightness4';
import Brightness7Icon from '@mui/icons-material/Brightness7';
import { ThemeProvider, createTheme, CssBaseline } from '@mui/material';
import { styled } from '@mui/system';

const Root = styled('div')(({ theme }) => ({
  height: '100vh',
  display: 'flex',
  flexDirection: 'column',
}));

const Header = styled('div')(({ theme }) => ({
  display: 'flex',
  justifyContent: 'space-between',
  alignItems: 'center',
  padding: theme.spacing(2),
  backgroundColor: theme.palette.primary.main,
  color: theme.palette.primary.contrastText,
}));

const Sidebar = styled('div')(({ theme }) => ({
  width: '250px',
  padding: theme.spacing(2),
  backgroundColor: theme.palette.background.paper,
  borderRight: `1px solid ${theme.palette.divider}`,
  overflowY: 'auto',
}));

const ChatContainer = styled(Paper)(({ theme }) => ({
  padding: theme.spacing(4),
  textAlign: 'left',
  width: '100%',
  height: '100%',
  display: 'flex',
  flexDirection: 'column',
  justifyContent: 'space-between',
  overflowY: 'auto',
}));

const Title = styled(Typography)(({ theme }) => ({
  marginBottom: theme.spacing(2),
}));

const MessageContainer = styled('div')({
  marginTop: 16,
  flexGrow: 1,
  display: 'flex',
  flexDirection: 'column',
  overflowY: 'auto',
});

const Message = styled(Typography)(({ sender, theme }) => ({
  alignSelf: sender === 'user' ? 'flex-end' : 'flex-start',
  backgroundColor: sender === 'user' ? theme.palette.primary.main : theme.palette.grey[200],
  color: sender === 'user' ? theme.palette.primary.contrastText : theme.palette.text.primary,
  padding: theme.spacing(1),
  borderRadius: theme.spacing(1),
  marginBottom: theme.spacing(1),
  maxWidth: '75%',
}));

const InputContainer = styled('div')(({ theme }) => ({
  display: 'flex',
  gap: theme.spacing(1),
  marginTop: theme.spacing(2),
}));



const TextInput = styled(TextField)(({ theme }) => ({
  flexGrow: 1,
}));

const SendButton = styled(Button)(({ theme }) => ({
  flexShrink: 0,
}));

const UserAvatar = styled(Avatar)(({ theme }) => ({
  marginRight: theme.spacing(2),
}));

const UserStatus = styled('div')(({ theme }) => ({
  display: 'flex',
  alignItems: 'center',
}));



function ChatPage() {
  const [sessions, setSessions] = useState([]);
  const [currentSession, setCurrentSession] = useState(null);
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [editingSession, setEditingSession] = useState(null);
  const [sessionName, setSessionName] = useState('');
  const { currentUser, signOut } = useContext(AuthContext);
  const [isSending, setIsSending] = useState(false);
  const [isCreatingSession, setIsCreatingSession] = useState(false);
  const messagesEndRef = useRef(null);
  const [anchorEl, setAnchorEl] = useState(null);
  const [darkMode, setDarkMode] = useState(false); // Light/Dark mode state

  const logUserActivity = async (activity) => {
    if (!currentUser) return;
  
    const logRef = ref(db, `activityLogs/${currentUser.uid}`);
    const newLogRef = push(logRef);
  
    const logEntry = {
      timestamp: new Date().toISOString(),
      activity: activity,
    };
  
    try {
      await set(newLogRef, logEntry);
    } catch (error) {
      console.error("Error logging activity:", error);
    }
  };
  

  const scrollToBottom = () => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  };

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

  useEffect(() => {
    if (currentUser) {
      const sessionsRef = ref(db, `chats/${currentUser.uid}/sessions`);
      get(sessionsRef)
        .then((snapshot) => {
          if (snapshot.exists()) {
            setSessions(Object.entries(snapshot.val()));
          } else {
            setSessions([]);
          }
        })
        .catch((error) => {
          console.error('Error fetching chat sessions:', error);
        });
    }
  }, [currentUser]);

  useEffect(() => {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      setDarkMode(savedTheme === 'dark');
    }
  }, []);

  const loadSession = async (sessionId) => {
    if (!currentUser) return;

    const sessionRef = ref(db, `chats/${currentUser.uid}/sessions/${sessionId}`);
    try {
      const snapshot = await get(sessionRef);
      if (snapshot.exists()) {
        setMessages(snapshot.val().messages || []);
        setSessionName(snapshot.val().name || sessionId);
      } else {
        setMessages([]);
        setSessionName(sessionId);
      }
      setCurrentSession(sessionId);
    } catch (error) {
      console.error('Error fetching session chat history:', error);
    }
  };

  const createNewSession = async (userMessage = null) => {
    if (!currentUser || isCreatingSession) return;

    setIsCreatingSession(true);

    try {
      const newSessionLabel = `Session ${sessions.length + 1}`;
      const newSessionRef = push(ref(db, `chats/${currentUser.uid}/sessions`));
      const sessionId = newSessionRef.key;

      const initialMessages = userMessage && userMessage.text ? [userMessage] : [];

      await set(newSessionRef, { name: newSessionLabel, messages: initialMessages });

      setSessions((prev) => [
        ...prev,
        [sessionId, { name: newSessionLabel, messages: initialMessages }],
      ]);

      setCurrentSession(sessionId);
      setMessages(initialMessages);
      setSessionName(newSessionLabel);

    } catch (error) {
      console.error('Error creating new session:', error);
    } finally {
      setIsCreatingSession(false);
    }
  };

  const saveMessagesToFirebase = async (sessionId, updatedMessages) => {
    const sessionRef = ref(db, `chats/${currentUser.uid}/sessions/${sessionId}/messages`);
    await set(sessionRef, updatedMessages);
  };

  const handleSend = async () => {
    if (input.trim() === '' || isSending || isCreatingSession) return;
  
    const userMessage = { sender: 'user', text: input.trim() };
  
    setIsSending(true);
  
    try {
      let sessionId = currentSession;
  
      if (!sessionId) {
        await createNewSession(userMessage);
        sessionId = currentSession;
      }
  
      let updatedMessages = [...messages, userMessage];
      if (!currentSession) {
        updatedMessages = [userMessage];
      }
      setMessages(updatedMessages);
  
      await saveMessagesToFirebase(sessionId, updatedMessages);
      await logUserActivity(`User ${currentUser.email} sent a message in session ${sessionName}`);
  
      const FUNCTION_URL = 'https://us-central1-mind-gardener.cloudfunctions.net/chatWithOpenAI';
      const response = await fetch(FUNCTION_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ conversationHistory: updatedMessages }),
      });
  
      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';
      const botMessage = { sender: 'bot', text: botReply };
      const updatedMessagesWithBotReply = [...updatedMessages, botMessage];
  
      setMessages(updatedMessagesWithBotReply);
      await saveMessagesToFirebase(sessionId, updatedMessagesWithBotReply);
  
    } catch (error) {
      const errorMessage = { sender: 'bot', text: `Sorry, there was an error: ${error.message}` };
      const updatedMessagesWithError = [...messages, userMessage, errorMessage];
  
      setMessages(updatedMessagesWithError);
      if (currentSession) {
        await saveMessagesToFirebase(currentSession, updatedMessagesWithError);
      }
    } finally {
      setIsSending(false);
      setInput('');
    }
  };
  

  const toggleTheme = () => {
    const newMode = !darkMode;
    setDarkMode(newMode);
    localStorage.setItem('theme', newMode ? 'dark' : 'light');
  };

  const saveSessionName = async (sessionId) => {
    if (!currentUser || !sessionId || !sessionName) return;

    const sessionRef = ref(db, `chats/${currentUser.uid}/sessions/${sessionId}/name`);
    try {
      await update(sessionRef, { name: sessionName });
      setSessions((prevSessions) =>
        prevSessions.map(([id, data]) =>
          id === sessionId ? [id, { ...data, name: sessionName }] : [id, data]
        )
      );
      setEditingSession(null);
    } catch (error) {
      console.error('Error saving session name:', error);
    }
  };

  const deleteSession = async (sessionId) => {
    if (!currentUser || !sessionId) return;

    const sessionRef = ref(db, `chats/${currentUser.uid}/sessions/${sessionId}`);
    try {
      await remove(sessionRef);
      setSessions((prevSessions) => prevSessions.filter(([id]) => id !== sessionId));
      if (sessionId === currentSession) {
        setCurrentSession(null);
        setMessages([]);
      }
    } catch (error) {
      console.error('Error deleting session:', error);
    }
  };

  const lightTheme = createTheme({
    palette: {
      mode: 'light',
      primary: {
        main: '#4caf50', // Green for primary in light mode
      },
    },
  });

  const darkTheme = createTheme({
    palette: {
      mode: 'dark',
      primary: {
        main: '#4caf50', // Green for primary in dark mode
      },
      background: {
        default: '#121212',
        paper: '#1e1e1e',
      },
    },
  });

  return (
    <ThemeProvider theme={darkMode ? darkTheme : lightTheme}>
      <CssBaseline />
      <Root>
        <Header>
          <Title variant="h6">MindGarden Chat</Title>
          <UserStatus>
            <UserAvatar>{currentUser.email[0].toUpperCase()}</UserAvatar>
            <Typography>{currentUser.email}</Typography>
            <Switch
              checked={darkMode}
              onChange={toggleTheme}
              icon={<Brightness7Icon />}
              checkedIcon={<Brightness4Icon />}
            />
            <IconButton onClick={(e) => setAnchorEl(e.currentTarget)}>
              <Badge color="success" variant="dot">
                <LogoutIcon />
              </Badge>
            </IconButton>
            <Menu
              anchorEl={anchorEl}
              open={Boolean(anchorEl)}
              onClose={() => setAnchorEl(null)}
            >
              <MenuItem onClick={signOut}>Sign Out</MenuItem>
            </Menu>
          </UserStatus>
        </Header>
        <div style={{ display: 'flex', height: '100%' }}>
          <Sidebar>
            <Button
              variant="contained"
              onClick={createNewSession}
              fullWidth
              disabled={isCreatingSession}
            >
              {isCreatingSession ? 'Creating...' : 'New Session'}
            </Button>
            <List>
              {sessions.map(([sessionId, sessionData]) => (
                <div key={sessionId}>
                  <ListItem
                    button
                    selected={sessionId === currentSession}
                    onClick={() => loadSession(sessionId)}
                  >
                    {editingSession === sessionId ? (
                      <>
                        <TextField
                          value={sessionName}
                          onChange={(e) => setSessionName(e.target.value)}
                          onBlur={() => saveSessionName(sessionId)}
                          autoFocus
                          size="small"
                        />
                        <IconButton onClick={() => saveSessionName(sessionId)}>
                          <SaveIcon />
                        </IconButton>
                      </>
                    ) : (
                      <>
                        <Typography style={{ flexGrow: 1 }}>
                          {sessionData.name}
                        </Typography>
                        <IconButton onClick={() => setEditingSession(sessionId)}>
                          <EditIcon />
                        </IconButton>
                        <IconButton onClick={() => deleteSession(sessionId)}>
                          <DeleteIcon />
                        </IconButton>
                      </>
                    )}
                  </ListItem>
                  <Divider />
                </div>
              ))}
            </List>
          </Sidebar>
          <ChatContainer>
            <MessageContainer>
              {messages.map((msg, index) => (
                <Message key={index} sender={msg.sender}>
                  {msg.text}
                </Message>
              ))}
              <div ref={messagesEndRef} />
            </MessageContainer>
            <InputContainer>
              <TextInput
                value={input}
                onChange={(e) => setInput(e.target.value)}
                variant="outlined"
                placeholder="Type your message..."
                disabled={isSending || isCreatingSession}
                onKeyPress={(e) => {
                  if (e.key === 'Enter') {
                    handleSend();
                  }
                }}
              />
              <SendButton
                variant="contained"
                color="primary"
                onClick={handleSend}
                endIcon={<SendIcon />}
                disabled={isSending || isCreatingSession}
              >
                {isSending ? 'Sending...' : 'Send'}
              </SendButton>
            </InputContainer>
          </ChatContainer>
        </div>
      </Root>
    </ThemeProvider>
  );
}

export default ChatPage;

AuthContext.js:
import React, { createContext, useState, useEffect, useContext } from 'react';
import { auth } from './firebase'; // Make sure the path is correct
import { onAuthStateChanged, signInWithEmailAndPassword, signOut as firebaseSignOut } from 'firebase/auth';
import { db } from './firebase'; // Import your Firebase database
import { ref, push, set } from 'firebase/database'; // Import necessary functions for Realtime Database

// Create an AuthContext
export const AuthContext = createContext();

// Custom hook to use AuthContext
export const useAuth = () => {
  return useContext(AuthContext);
};

// Function to log user activity
const logUserActivity = async (userEmail, activity) => {
  if (!userEmail) return;

  // Sanitize the user ID by replacing invalid characters
  const sanitizedUserId = userEmail.replace(/\./g, '_').replace('@', '_at_');  

  const logRef = ref(db, `activityLogs/${sanitizedUserId}`);
  const newLogRef = push(logRef);

  const logEntry = {
    timestamp: new Date().toISOString(),
    activity: activity,
  };

  try {
    await set(newLogRef, logEntry);
  } catch (error) {
    console.error("Error logging activity:", error);
  }
};

// AuthProvider component
export function AuthProvider({ children }) {
  const [currentUser, setCurrentUser] = useState(null);

  useEffect(() => {
    // Listen for auth state changes
    const unsubscribe = onAuthStateChanged(auth, async (user) => {
      setCurrentUser(user);

      // Log user activity on sign-in
      if (user) {
        await logUserActivity(user.email, `User ${user.email} logged in.`);
      } else {
        // Log user activity on sign-out
        await logUserActivity(currentUser?.email, `User ${currentUser?.email} logged out.`);
      }
    });

    return unsubscribe; // Cleanup subscription on unmount
  }, [currentUser]); // Update dependency to include currentUser


  const signIn = async (email, password) => {
    try {
      await signInWithEmailAndPassword(auth, email, password);
    } catch (error) {
      console.error("Error signing in:", error);
    }
  };

  const signOut = async () => {
    try {
      await firebaseSignOut(auth); // Sign out the user
      setCurrentUser(null); // Update the current user state
    } catch (error) {
      console.error("Sign out error:", error);
    }
  };

  return (
    <AuthContext.Provider value={{ currentUser, signIn, signOut }}>
      {children}
    </AuthContext.Provider>
  );
}