<!DOCTYPE html>
<html>
<head>
  <title>Google</title>
  <style>
    body {
      font-family: sans-serif;
    }

    #chat-container {
      display: flex;
      flex-direction: column;
      width: 500px;
      margin: 20px auto;
      border: 1px solid #ccc;
      padding: 10px;
      height: 400px;
      overflow-y: auto;
      background-color: #fafafa;
    }

    .message {
      padding: 10px;
      margin-bottom: 10px;
      border-radius: 5px;
    }

    .user-message {
      background-color: #e0f7fa;
      text-align: right;
      white-space: pre-wrap; 
    }

    .bot-message {
      background-color: #f1f8e9;
      white-space: pre-wrap; 
    }

    #input-area {
      display: flex;
      margin: 10px auto;
      width: 500px;
    }

    #input-box {
      flex-grow: 1;
      padding: 10px;
      border: 1px solid #ccc;
      border-radius: 5px;
      resize: none;
      font-size: 14px;
    }

    #send-button {
      padding: 10px 20px;
      margin-left: 10px;
      background-color: #007bff;
      color: #fff;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 14px;
    }

    #send-button:hover {
      background-color: #0056b3;
    }

    /* Styles for typing indicator */
    #typing-indicator {
      display: none; /* Initially hidden */
      margin: 5px auto;
      font-style: italic;
      color: #999;
      width: 500px;
      text-align: left;
    }

    /* Styles for the toggle containers */
    .toggle-container {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 10px;
    }

    .toggle-container label {
      margin-right: 10px;
    }

    /* Toggle switch styles */
    .switch {
      position: relative;
      display: inline-block;
      width: 60px;
      height: 34px;
      margin-left: 10px;
    }

    .switch input {
      opacity: 0;
      width: 0;
      height: 0;
    }

    .slider {
      position: absolute;
      cursor: pointer;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: #ccc;
      transition: .4s;
      border-radius: 34px;
    }

    .slider:before {
      position: absolute;
      content: "";
      height: 26px;
      width: 26px;
      left: 4px;
      bottom: 4px;
      background-color: white;
      transition: .4s;
      border-radius: 50%;
    }

    input:checked + .slider {
      background-color: #2196F3;
    }

    input:checked + .slider:before {
      transform: translateX(26px);
    }

    /* Responsive adjustments */
    @media (max-width: 550px) {
      #chat-container, #input-area, #typing-indicator {
        width: 90%;
      }
    }
  </style>
</head>

<body>
  <!-- Toggle Button for Super Smart Mode -->
  <div class="toggle-container">
    <label for="superSmartToggle">Super Smart Mode (buggy)</label>
    <label class="switch">
      <input type="checkbox" id="superSmartToggle">
      <span class="slider"></span>
    </label>
  </div>

  <!-- Toggle Button for Fast/Smart Model Switching -->
  <div class="toggle-container">
    <label for="modelToggle">Fast Mode</label>
    <label class="switch">
      <input type="checkbox" id="modelToggle">
      <span class="slider"></span>
    </label>
  </div>

  <div id="chat-container"></div>
  <div id="input-area">
    <textarea id="input-box" placeholder="Enter your message..." rows="3"></textarea>
    <button id="send-button">Send</button>
  </div>
  <div id="typing-indicator">Gemini is typing...</div> 

  <script>
    // List of API keys. Replace these with your actual API keys.
    const API_KEYS = [
      'AIzaSyBdc_A8VxExwO6-0LY1--r2-Ym73lMg-h4',
      'AIzaSyBydeCpaNOIPSk794CpTGnfKrxbjCgJLu4',
      'AIzaSyCQ7tBHtctxlNs61Zm2Y__7KYeDLfz5dms',
      'AIzaSyAip_DFfKNC35MFIorEoNK4y6czP9P65-c'
    ];

    const chatContainer = document.getElementById('chat-container');
    const inputBox = document.getElementById('input-box');
    const sendButton = document.getElementById('send-button');
    const typingIndicator = document.getElementById('typing-indicator');
    const superSmartToggle = document.getElementById('superSmartToggle');
    const modelToggle = document.getElementById('modelToggle');

    // Initialize messageHistory based on toggles' initial state
    let messageHistory = "";

    // Current model variable
    let currentModel = 'gemini-1.5-pro-exp-0827'; // Default model

    // Event listener for the Super Smart Mode toggle switch
    superSmartToggle.addEventListener('change', () => {
      if (superSmartToggle.checked) {
        messageHistory = "Tt" + messageHistory;
      } else {
        // If disabling, remove "The assistant" from the history
        messageHistory = messageHistory.replace("Tt", "");
      }
    });

    // Event listener for the Fast/Smart Model toggle switch
    modelToggle.addEventListener('change', () => {
      if (modelToggle.checked) {
        currentModel = 'gemini-1.5-flash';
      } else {
        currentModel = 'gemini-1.5-pro-exp-0827';
      }
      console.log(`Model switched to: ${currentModel}`);
    });

    sendButton.addEventListener('click', sendMessage);
    inputBox.addEventListener('keydown', (event) => {
      if (event.key === 'Enter' && !event.shiftKey) {
        event.preventDefault();
        sendMessage();
      }
    });

    /**
     * Attempts to fetch a response using the provided API key.
     * @param {string} apiKey - The API key to use for the request.
     * @param {string} prompt - The user message to send.
     * @param {string} model - The model to use for generating the response.
     * @returns {Promise<Object>} - The response data from the API.
     */
    async function fetchWithKey(apiKey, prompt, model) {
      const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          contents: [
            {
              role: "user",
              parts: [
                { text: prompt } // Include history in the prompt
              ]
            }
          ],
          "generationConfig": {
            "temperature": 0.5,
            "topK": 64,
            "topP": 0.95,
            "maxOutputTokens": 8192,
            "responseMimeType": "text/plain"
          }
        })
      });

      if (!response.ok) {
        // Extract error message from response
        const errorData = await response.json();
        throw new Error(errorData.error?.message || 'Unknown API error');
      }

      const data = await response.json();
      return data;
    }

    /**
     * Sends the user's message and handles the bot's response using multiple API keys.
     */
    async function sendMessage() {
      const userMessageText = inputBox.value.trim();
      if (userMessageText === '') return;

      // Display user's message
      const userMessage = document.createElement('div');
      userMessage.classList.add('message', 'user-message');
      userMessage.textContent = userMessageText;
      chatContainer.appendChild(userMessage);
      chatContainer.scrollTop = chatContainer.scrollHeight;      
      
      inputBox.value = '';
      typingIndicator.style.display = 'block';

      let botMessageText = '';
      let success = false;

      // Prepare the prompt based on the current messageHistory and Super smart mode
      const currentMessageHistory = messageHistory + `User: ${userMessageText}\n`;

      for (const apiKey of API_KEYS) {  // Simplified loop
        try {
          const data = await fetchWithKey(apiKey, currentMessageHistory, currentModel); // Add user message here

          const fullResponse = data?.candidates[0]?.content?.parts[0]?.text; // Optional chaining

          if (!fullResponse) {
            throw new Error("Invalid response format: Missing content."); // Better error handling
          }

          if (superSmartToggle.checked) {
            // Parse response between <final_answer> and </final_answer>
            const finalAnswerStartIndex = fullResponse.indexOf("<final_answer>");
            const finalAnswerEndIndex = fullResponse.indexOf("</final_answer>");

            if (finalAnswerStartIndex !== -1 && finalAnswerEndIndex !== -1) {
              botMessageText = fullResponse.substring(finalAnswerStartIndex + "<final_answer>".length, finalAnswerEndIndex).trim();
            } else {
              botMessageText = "Error: Could not extract final answer. Invalid response format.";
              console.error("Final answer tags not found in response:", fullResponse);
            }
          } else {
            // When Super smart mode is off, use the entire response
            botMessageText = fullResponse.trim();
          }

          if (botMessageText) {
            // Update history *after* successful response
            messageHistory += `Gemini (${currentModel}): ${botMessageText}\n`;
          }

          success = true;
          break; 
        } catch (error) {
          console.error(`Error with API key:`, error.message);
        }
      }

      const botMessage = document.createElement('div'); // Create element *outside* the loop
      botMessage.classList.add('message', 'bot-message');
      botMessage.textContent = success ? botMessageText : "I'm sorry, I'm currently unable to process your request. Please try again later."; // Display error or bot message
      chatContainer.appendChild(botMessage);
      chatContainer.scrollTop = chatContainer.scrollHeight;

      typingIndicator.style.display = 'none';
    }
  </script>
</body>
</html>