User: Analyse this code:&nbsp;
```javascript
// src/components/ChatInterface.js

import React, {
  useState,
  useContext,
  useRef,
  useEffect,
  useCallback,
} from "react";
import { ChatContext } from "../context/ChatContext";
import Message from "./Message";
import CodeModal from "./CodeModal";
import InlineCodeEditor from "./InlineCodeEditor";
import { escapeHtml } from "../utils/escapeHtml";
import { unescapeHtml } from "../utils/unescapeHtml"; // Import unescapeHtml
import { encodeToBase64, decodeFromBase64 } from "../utils/base64"; 

/**
 * Component representing the chat interface where users can send messages and receive responses.
 *
 * @returns {JSX.Element} The ChatInterface component.
 */
function ChatInterface() {
  const {
    chats,
    currentChatId,
    addMessage,
    updateChat,
    selectedModelId,
    models,
  } = useContext(ChatContext);

  const currentChat = chats.find((chat) =&gt; chat.id === currentChatId);
  const [message, setMessage] = useState("");
  const [isTyping, setIsTyping] = useState(false);
  const messagesEndRef = useRef(null);
  const [isCodeModalOpen, setIsCodeModalOpen] = useState(false);
  const [currentEditingCode, setCurrentEditingCode] = useState(null);
  const [isSystemPromptOpen, setIsSystemPromptOpen] = useState(false);
  // Removed unused state: codeAttachments

  /**
   * Adds a code attachment within the message by embedding it as a <code> tag.
   *
   * @param {object} params - Parameters for the code attachment.
   * @param {string} params.codeContent - The actual code content.
   * @param {string} [params.fileName='untitled'] - The name of the code file.
   * @param {string} [params.notes=''] - Optional notes or comments.
   */
  const addCodeAttachment = ({
    codeContent,
    fileName = "untitled",
    notes = "",
  }) =&gt; {
    const escapedFileName = escapeHtml(fileName);
    const escapedNotes = escapeHtml(notes);
    // Encode codeContent to Base64 to prevent tag conflicts
    const encodedCodeContent = encodeToBase64(codeContent);
    const codeTag = `<ai-code filename="${escapedFileName}" notes="${escapedNotes}">${encodedCodeContent}</ai-code>`;
    setMessage((prev) =&gt; prev + codeTag);
  };


  /**
   * Opens the code modal for attaching or editing code segments.
   *
   * @param {object} [codeSegment=null] - The code segment to edit, if any.
   */
  const handleAttachCode = useCallback((codeSegment = null) =&gt; {
    setCurrentEditingCode(codeSegment);
    setIsCodeModalOpen(true);
  }, []);

  /**
   * Handles saving of code attachments, either adding new or updating existing ones.
   *
   * @param {object} updatedCode - The updated code data.
   * @param {string} updatedCode.codeContent - The updated code content.
   * @param {string} updatedCode.fileName - The updated file name.
   * @param {string} updatedCode.notes - The updated notes.
   */
  const handleCodeSave = useCallback(
    (updatedCode) =&gt; {
      if (currentEditingCode) {
        // Update existing code
        const escapedFileName = escapeHtml(updatedCode.fileName || "untitled");
        const escapedNotes = escapeHtml(updatedCode.notes || "");

        // Use a more robust selector if possible to prevent regex issues
        const regex = new RegExp(
          `<code\\s+filename="${escapehtml( currenteditingcode.filename="" )}"\\s+notes="${escapeHtml(
            currentEditingCode.notes
          )}">([\\s\\S]*?)&lt;\\/code&gt;`
        );

        const updatedMessage = message.replace(
          regex,
          `<code filename="${escapedFileName}" notes="${escapedNotes}">${updatedCode.codeContent}</code>`
        );
        setMessage(updatedMessage);
      } else {
        // Add new code
        addCodeAttachment(updatedCode);
      }
      setIsCodeModalOpen(false);
      setCurrentEditingCode(null);
    },
    [currentEditingCode, message, escapeHtml, addCodeAttachment]
  );

  /**
   * Sends the user's message to the backend and handles the response.
   */
  const handleSend = useCallback(async () =&gt; {
    if (!message.trim() || !currentChatId || !selectedModelId) return;
  
    // Retrieve the system prompt from the current chat
    const systemPrompt = currentChat.systemPrompt || "";
  
    // Combine the system prompt with the user message
    const fullMessage = systemPrompt ? `${systemPrompt}\n${message}` : message;
  
    // Parse the message to extract ai-code tags and decode codeContent
    const parser = new DOMParser();
    const doc = parser.parseFromString(fullMessage, "text/html");
    const aiCodeElements = doc.querySelectorAll("ai-code");
  
    aiCodeElements.forEach((element) =&gt; {
      const encodedCodeContent = element.textContent;
      const codeContent = decodeFromBase64(encodedCodeContent);
      const fileName = element.getAttribute("fileName") || "Untitled";
      const notes = element.getAttribute("notes") || "";
      // Replace <ai-code> with Markdown code block
      const codeBlock = `\n\`\`\`javascript\n${codeContent}\n\`\`\`\n`;
      element.outerHTML = codeBlock;
    });
  
    const processedMessage = doc.body.innerHTML;
  
    const userMessage = { sender: "user", text: processedMessage };
    addMessage(currentChatId, userMessage);
    setMessage("");
    scrollToBottom();
  
    // Set typing indicator
    setIsTyping(true);
  
    try {
      const response = await fetch(
        `${process.env.REACT_APP_BACKEND_URL}/api/chat`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            text: processedMessage, // Send the processed message with code blocks
            model_id: selectedModelId,
          }),
        }
      );
  
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(
          errorData.detail || "Failed to get response from the server."
        );
      }
  
      const data = await response.json();
      const responseText = data.response;
      const responseModelId = data.model_id;
  
      const botMessage = {
        sender: "bot",
        text: responseText,
        model_id: responseModelId,
      };
      addMessage(currentChatId, botMessage);
      scrollToBottom();
    } catch (error) {
      console.error("Error:", error);
      const errorMessage = {
        sender: "bot",
        text: "Sorry, something went wrong. Please try again.",
      };
      addMessage(currentChatId, errorMessage);
      scrollToBottom();
    } finally {
      // Remove typing indicator
      setIsTyping(false);
    }
  }, [message, currentChatId, selectedModelId, addMessage, currentChat, decodeFromBase64]);

  /**
   * Handles the keydown event in the message input area.
   * Sends the message on Enter key without Shift.
   *
   * @param {object} e - The event object.
   */
  const handleKeyDown = useCallback(
    (e) =&gt; {
      if (e.key === "Enter" &amp;&amp; !e.shiftKey) {
        e.preventDefault();
        handleSend();
      }
    },
    [handleSend]
  );

  const handleEditorKeyDown = useCallback((e) =&gt; {
    if (e.key === 'Enter' &amp;&amp; !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  }, [handleSend]);

  /**
   * Scrolls the chat to the bottom.
   */
  const scrollToBottom = useCallback(() =&gt; {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, []);

  /**
   * Updates the system prompt in the current chat.
   *
   * @param {object} e - The event object.
   */
  const handleSystemPromptChange = useCallback(
    (e) =&gt; {
      const newPrompt = e.target.value;
      updateChat(currentChatId, { systemPrompt: newPrompt });
    },
    [updateChat, currentChatId]
  );

  /**
   * Toggles the visibility of the system prompt textarea.
   */
  const toggleSystemPrompt = useCallback(() =&gt; {
    setIsSystemPromptOpen((prev) =&gt; !prev);
  }, []);

  // Remove unused useState: codeAttachments

  if (!currentChat) {
    return (
      <div classname="flex-1 p-4 text-gray-700 dark:text-gray-300">
        No active chat. Please start a new chat.
      </div>
    );
  }

  return (
    <div classname="flex flex-col h-screen">
      <div classname="flex-1 p-32 pt-8 pb-8 overflow-y-auto bg-[#eeeeee] dark:bg-[#161618]">
        {/* Removed Model Selector Dropdown */}

        {/* Chat Messages */}
        {currentChat.messages.map((msg, index) =&gt; (
          <message key="{index}" chatid="{currentChatId}" messageindex="{index}" sender="{msg.sender}" text="{msg.text}" model_id="{msg.model_id}" pass="">
        ))}
        {isTyping &amp;&amp; (
          <div classname="mb-4 flex justify-start">
            <div classname="max-w-xs md:max-w-md lg:max-w-lg p-3 rounded-lg bg-gray-200 dark:bg-gray-800 text-gray-800 dark:text-gray-200 flex items-center">
              <div classname="flex space-x-1 mr-2">
                <div classname="w-2 h-2 bg-gray-600 rounded-full animate-bounce-custom animation-delay-0"></div>
                <div classname="w-2 h-2 bg-gray-600 rounded-full animate-bounce-custom animation-delay-200"></div>
                <div classname="w-2 h-2 bg-gray-600 rounded-full animate-bounce-custom animation-delay-400"></div>
              </div>
              <span classname="text-sm">Echo is typing...</span>
            </div>
          </div>
        )}
        <div ref="{messagesEndRef}">
      </div>
      <div id="message_area" classname="p-4 border-t dark:border-gray-700 bg-white dark:bg-[#161618]">
        <button onclick="{toggleSystemPrompt}" classname="mb-2 text-sm text-blue-500 hover:underline focus:outline-none">
          {isSystemPromptOpen ? "Hide System Prompt" : "Show System Prompt"}
        </button>
        {isSystemPromptOpen &amp;&amp; (
          <textarea classname="w-full p-2 border rounded-lg resize-none dark:bg-gray-800 dark:text-gray-200 mb-2" rows="3" placeholder="Enter system prompt..." value="{currentChat.systemPrompt}" onchange="{handleSystemPromptChange}">        )}
        &lt;div className="flex flex-row"&gt;
          &lt;div className="flex-grow"&gt;
            &lt;InlineCodeEditor
              value={message}
              onChange={setMessage}
              onAttachCode={handleAttachCode}
              onKeyDown={handleEditorKeyDown} // Pass the keydown handler as a prop
            /&gt;
          &lt;/div&gt;
          &lt;div className="flex flex-col items-end pl-4"&gt;
            &lt;button
              onClick={() =&gt; handleAttachCode(null)} // Passing null for new attachment
              className="bg-blue-500 text-white px-3 py-2 rounded-lg hover:bg-blue-600 flex-grow w-full"
            &gt;
              Attach Code
            &lt;/button&gt;
            &lt;button
              className="bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 flex-grow mt-2 w-full"
              onClick={handleSend}
            &gt;
              Send
            &lt;/button&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      {isCodeModalOpen &amp;&amp; (
        &lt;CodeModal
          onClose={() =&gt; {
            setIsCodeModalOpen(false);
            setCurrentEditingCode(null);
          }}
          onSave={handleCodeSave}
          initialData={currentEditingCode}
        /&gt;
      )}
    &lt;/div&gt;
  );
}

export default ChatInterface;

```
</textarea></div></message></div></div></ai-code></code\\s+filename="${escapehtml(></code>