The following code is the App.js for a React app of a chatbot interface. Please fix all errors you find:

App.js:
<code>
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import Sidebar from './components/Sidebar';
import Header from './components/Header';
import ChatWindow from './components/ChatWindow';
import CodeSidebar from './components/CodeSidebar';
import { FaSearch } from 'react-icons/fa';
import {
sendMessage as sendMessageAction,
startNewChat,
setCodeSnippet,
} from './redux/chatSlice';

function App() {
const dispatch = useDispatch();
const {
input, // Managed locally
chats,
activeChat,
codeSnippet,
commonQueries,
status,
error,
} = useSelector((state) => state.chat);

const [localInput, setLocalInput] = React.useState('');

// Handle sending a message
const sendMessage = () => {
if (localInput.trim() === '') return;

// Dispatch sendMessage async thunk
dispatch(sendMessageAction({ text: localInput, activeChat }));
setLocalInput('');
};

// Start a new chat
const handleStartNewChat = () => {
dispatch(startNewChat());
};

// Handle code click
const handleCodeClick = (code) => {
dispatch(setCodeSnippet(code));
};

// Optionally, handle error state
useEffect(() => {
if (status === 'failed') {
console.error(error);
}
}, [status, error]);

return (
<div className="flex h-screen">
{/ Sidebar /}
      <Sidebar
        chats={chats}
        activeChat={activeChat}
      />

      {/ Main Content /}
      <div className="flex-1 flex flex-col">
        {/ Header /}
        <Header />

        {/ Search Box and Common Queries (Visible when no active chat) /}
        {activeChat === null && (
          <div className="p-4 bg-gray-100">
            {/ Search Box /}
            <div className="flex mb-4">
              <input
                type="text"
                className="flex-grow border rounded-l px-4 py-2 focus:outline-none"
                placeholder="Enter your query..."
                value={localInput}
                onChange={(e) => setLocalInput(e.target.value)}
                onKeyPress={(e) => {
                  if (e.key === 'Enter') sendMessage();
                }}
              />
              <button
                className="bg-blue-500 text-white px-4 py-2 rounded-r hover:bg-blue-600"
                onClick={sendMessage}
              >
                <FaSearch />
              </button>
            </div>

            {/ Common Queries /}
            <div>
              <h3 className="text-lg font-semibold mb-2">Common Queries:</h3>
              <div className="flex flex-wrap gap-2">
                {commonQueries.map((query, index) => (
                  <button
                    key={index}
                    className="bg-gray-200 text-gray-800 px-3 py-1 rounded hover:bg-gray-300"
                    onClick={() => setLocalInput(query)}
                  >
                    {query}
                  </button>
                ))}
              </div>
            </div>
          </div>
        )}

        {/ Chat Window (Visible when a chat is active) /}
        {activeChat !== null && (
          <ChatWindow
            messages={chats[activeChat]}
            onSend={sendMessage}
            input={localInput}
            setInput={setLocalInput}
            onCodeClick={handleCodeClick}
          />
        )}
      </div>

      {/ Code Sidebar */}
      {codeSnippet && (
        <CodeSidebar onClose={() => dispatch(setCodeSnippet(null))} code={codeSnippet} />
      )}
    </div>
  );
}

export default App;
</code>

index.js:
<code>
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import store from './redux/store'; // Import the store
import { Provider } from 'react-redux'; // Import Provider

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById('root')
);
</code>

ChatWindow.js:
<code>
import React, { useRef, useEffect } from "react";
import { FaCopy } from "react-icons/fa";

function ChatWindow({ messages, onSend, input, setInput, onCodeClick }) {
  const messagesEndRef = useRef(null);

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

  useEffect(scrollToBottom, [messages]);

  return (
    <div className="flex flex-col flex-1">
      <div className="flex-1 overflow-y-auto p-4 bg-gray-50">
        {messages.map((msg, index) => (
          <div
            key={index}
            className={`mb-4 flex ${
              msg.sender === "user" ? "justify-end" : "justify-start"
            }`}
          >
            <div
              className={`px-4 py-2 rounded-lg max-w-xs ${
                msg.sender === "user"
                  ? "bg-blue-500 text-white"
                  : "bg-white text-gray-800 shadow"
              }`}
              onClick={() => {
                if (msg.isCode && onCodeClick) onCodeClick(msg.code);
              }}
            >
              {msg.isCode ? (
                <pre className="whitespace-pre-wrap cursor-pointer">
                  {msg.code.length > 100
                    ? `${msg.code.substring(0, 100)}...`
                    : msg.code}
                  {msg.code.length > 100 && (
                    <span className="text-blue-300"> Click to expand</span>
                  )}
                </pre>
              ) : (
                msg.text
              )}
            </div>
          </div>
        ))}
        <div ref={messagesEndRef} />
      </div>
      <div className="flex p-4 bg-white border-t">
        <input
          type="text"
          className="flex-grow border rounded-l px-4 py-2 focus:outline-none"
          placeholder="Type your message..."
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyPress={(e) => {
            if (e.key === "Enter") onSend();
          }}
        />
        <button
          className="bg-blue-500 text-white px-4 py-2 rounded-r hover:bg-blue-600"
          onClick={onSend}
        >
          Send
        </button>
      </div>
    </div>
  );
}

export default ChatWindow;
</code>

CodeSidebar.js:
<code>
import React from "react";
import { FaTimes } from "react-icons/fa";

function CodeSidebar({ code, onClose }) {
  return (
    <div className="fixed top-0 right-0 w-1/3 h-full bg-gray-100 shadow-lg p-4 overflow-y-auto">
      <div className="flex justify-between items-center mb-4">
        <h2 className="text-xl font-semibold">Code Snippet</h2>
        <button onClick={onClose}>
          <FaTimes size={20} />
        </button>
      </div>
      <pre className="bg-white p-4 rounded shadow overflow-auto">
        <code>{code}</code>
      </pre>
    </div>
  );
}

export default CodeSidebar;
</code>

Header.js:
<code>
import React from "react";
import { FaRobot } from "react-icons/fa";

function Header() {
  const getGreeting = () => {
    const hour = new Date().getHours();
    if (hour < 12) return "Good Morning";
    if (hour < 18) return "Good Afternoon";
    return "Good Evening";
  };

  return (
    <div className="flex items-center justify-between p-4 bg-white shadow-md">
      <div className="flex items-center">
        <FaRobot size={30} className="text-blue-500 mr-2" />
        <h1 className="text-2xl font-bold">{getGreeting()}</h1>
      </div>
    </div>
  );
}

export default Header;
</code>

Sidebar.js:
<code>
import React from 'react';
import { FaPlus, FaHistory } from 'react-icons/fa';
import { useDispatch } from 'react-redux';
import { setActiveChat, startNewChat } from '../redux/chatSlice';

function Sidebar({ chats, activeChat }) {
  const dispatch = useDispatch();

  const handleNewChat = () => {
    dispatch(startNewChat());
  };

  const handleSetActiveChat = (index) => {
    dispatch(setActiveChat(index));
  };

  return (
    <div className="w-64 bg-white shadow-md h-screen flex flex-col">
      <div className="flex items-center justify-between p-4 border-b">
        <h2 className="text-xl font-semibold">Chats</h2>
        <button
          onClick={handleNewChat}
          className="text-blue-500 hover:text-blue-700"
          title="New Chat"
        >
          <FaPlus size={20} />
        </button>
      </div>
      <div className="flex-1 overflow-y-auto">
        {chats.length === 0 ? (
          <p className="p-4 text-gray-500">No chats yet. Start a new chat!</p>
        ) : (
          chats.map((chat, index) => (
            <div
              key={index}
              onClick={() => handleSetActiveChat(index)}
              className={`p-4 cursor-pointer hover:bg-gray-100 ${ activeChat === index ? 'bg-gray-200' : '' } flex items-center justify-between`}
            >
              <span>Chat {index + 1}</span>
              <FaHistory size={14} className="text-gray-500" />
            </div>
          ))
        )}
      </div>
    </div>
  );
}

export default Sidebar;
</code>

chatSlice.js:
<code>
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

// Async thunk for sending messages
export const sendMessage = createAsyncThunk(
  'chat/sendMessage',
  async ({ text, activeChat }, { rejectWithValue }) => {
    try {
      const response = await axios.post('http://localhost:8000/api/chat', { text });
      console.log('Response from backend:', response.data.response); // Debug log
      return { response: response.data.response, activeChat };
    } catch (error) {
      console.error('Error in sendMessage thunk:', error);
      return rejectWithValue('Error sending message');
    }
  }
);

const chatSlice = createSlice({
  name: 'chat',
  initialState: {
    chats: [],
    activeChat: null,
    codeSnippet: null,
    commonQueries: [
      "What's the weather today?",
      'Tell me a joke',
      'Show me a React example',
    ],
    status: 'idle', // 'idle' | 'loading' | 'succeeded' | 'failed'
    error: null,
  },
  reducers: {
    startNewChat: (state) => {
      state.activeChat = null;
      state.codeSnippet = null;
      // Optional: Reset input if it's part of Redux state
    },
    setActiveChat: (state, action) => {
      state.activeChat = action.payload;
      state.codeSnippet = null;
    },
    setCodeSnippet: (state, action) => {
      state.codeSnippet = action.payload;
    },
    // If you plan to manage input globally, you can add a reducer here
    // setInput: (state, action) => {
    //   state.input = action.payload;
    // },
  },
  extraReducers: (builder) => {
    builder
      .addCase(sendMessage.pending, (state) => {
        state.status = 'loading';
      })
      .addCase(sendMessage.fulfilled, (state, action) => {
        const { response, activeChat } = action.payload;
        let chatIndex = activeChat;

        if (activeChat === null) {
          // Starting a new chat
          state.chats.push([]);
          chatIndex = state.chats.length - 1;
          state.activeChat = chatIndex;
        }

        // Extract code if present using RegExp
        // Ensure 'response' is a string before calling 'match'
        let codeMatch = null;
        if (typeof response === 'string') {

        }

        console.log('Code Match:', codeMatch); // Debug log

        let botMessage = { sender: 'bot', text: response };

        if (codeMatch && codeMatch[1]) {
          const code = codeMatch[1];
          botMessage = { sender: 'bot', text: response, isCode: true, code };
        }

        // Initialize chat array if undefined (precaution)
        if (!state.chats[chatIndex]) {
          state.chats[chatIndex] = [];
        }

        // Add bot message to the chat
        state.chats[chatIndex].push(botMessage);
        state.status = 'succeeded';
      })
      .addCase(sendMessage.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.payload;
        if (state.activeChat !== null) {
          // Ensure the active chat exists
          if (!state.chats[state.activeChat]) {
            state.chats[state.activeChat] = [];
          }
          state.chats[state.activeChat].push({
            sender: 'bot',
            text: 'Sorry, something went wrong.',
          });
        }
      });
  },
});

export const { startNewChat, setActiveChat, setCodeSnippet } = chatSlice.actions;

export default chatSlice.reducer;
</code>

store.js:
<code>
import { configureStore } from '@reduxjs/toolkit';
import chatReducer from './chatSlice';

const store = configureStore({
  reducer: {
    chat: chatReducer,
  },
});

export default store;
</code>