<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>FakeGPT</title>
  <!-- Bootstrap 5 CDN -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    /* Unified theme colors */
    :root {
      --clr-primary: #B1F0F7;  /* Primary color */
      --clr-surface: #FADA7A;  /* Surface color */
      --clr-surface-tonal: #ffe69b;  /* Surface tonal color */
      --clr-text-dark: #333;  /* Text color (dark for contrast) */
      --clr-text-light: #000000;  /* Light text color */
    }

    body {
      font-family: Arial, sans-serif;
      padding: 0;
      margin: 0;
      background-color: var(--clr-surface);
      color: var(--clr-text-dark);
      display: flex;
      flex-direction: column;
      min-height: 100vh;
      overflow-y: none;
    }

    /* Ensure that the page takes full height */
    .container {
      display: contents;
      flex-direction: column;
      flex-grow: 1;
      overflow: hidden;
    }

  /* Make conversation container scrollable but hide scrollbar */
  .conversation-container {
    margin-top: 0px;
    background-color: var(--clr-surface-tonal);
    padding: 15px;
    border-radius: 10px;
    border: 1px solid #ccc;
    min-height: 200px;
    max-height: calc(100vh - 200px); /* Adjust to fit in one page on mobile */
    overflow-y: auto;
    flex-grow: 1;
    /* Hide scrollbars */
    scrollbar-width: thin;
    scrollbar-color: transparent transparent;
  }

  .conversation-container::-webkit-scrollbar {
    display: none; /* Hide scrollbar for Webkit-based browsers */
  }


    .conversation-container::-webkit-scrollbar-thumb {
      background: transparent;
    }

    /* Sticky div for user input that sticks to the bottom of the whole page */
    #userInputWrapper {
      position: sticky;
      bottom: 0;
      background-color: var(--clr-surface);
      z-index: 10;
      width: 100wh;
      padding: 5px;
      box-sizing: border-box;
    }

    #userInput {
      width: 100%;
      min-height: 60px;
      max-height: 300px;
      resize: both;
      background-color: var(--clr-surface-tonal);
      color: var(--clr-text-dark);
    }

    #sendBtn {
      background-color: var(--clr-primary);
      color: var(--clr-text-dark);
      border: none;
      border-radius: 5px;
      padding: 10px;
      font-size: 14px;
      cursor: pointer;
      width: 100%;
    }

    #sendBtn:hover {
      background-color: var(--clr-surface-tonal);
    }

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

    .message.user {
      background-color: #ffd34d;
    }

    .message.assistant {
      background-color: var(--clr-primary);
      position: relative;
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
    }
    .message.system {
      background-color: var(--clr-primary);
      position: relative;
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
    }

    .copy-btn {
      position: absolute;
      top: 5px;
      right: 5px;
      background-color: var(--clr-primary);
      color: var(--clr-text-dark);
      border: none;
      border-radius: 5px;
      padding: 5px 10px;
      font-size: 12px;
      cursor: pointer;
      z-index: 10;
    }

    .copy-btn:hover {
      background-color: var(--clr-surface-tonal);
    }

    .message pre {
      white-space: pre-wrap;
      word-wrap: break-word;
    }

    .navbar {
      position: sticky;
      top: 0;
      z-index: 1;
      background-color: #3464b5;
    }

    /* Style for code block */
    pre code {
      background-color: #f8f9fa;  /* Light background for code */
      border-radius: 5px;
      padding: 10px;
      font-size: 14px;
      line-height: 1.5;
      display: block;
      white-space: pre-wrap;
      word-wrap: break-word;
      color: #333;
      border: 1px solid #ddd;
      overflow-x: auto;
      margin-bottom: 10px;  /* Space below the code block */
    }

    pre code:hover {
      background-color: #e8f0fe;  /* Slightly darker background on hover */
    }
  </style>
</head>
<body>

  <!-- Navigation Bar -->
  <nav class="navbar navbar-expand-lg">
    <div class="container-fluid">
      <a class="navbar-brand" href="#" style="color:wheat;"><i class="fa-sharp-duotone fa-solid fa-cat"></i> FAKEGPT</a>
    </div>
  </nav>

  <div class="container">
    <!-- Display the conversation -->
    <div id="conversation" class="conversation-container"></div>
    
    <!-- Div for User Input (Textarea and Send Button) -->
    <div id="userInputWrapper">
      <!-- Textarea for user input -->
      <textarea id="userInput" class="form-control" placeholder="Type your message here..." rows="3"></textarea>

      <!-- Send Button -->
      <button id="sendBtn" class="btn btn-primary w-100 mb-3">Send</button>
    </div>
  </div>

  <!-- Modal for Custom Alerts -->
  <div class="modal fade" id="customAlertModal" tabindex="-1" aria-labelledby="customAlertModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="customAlertModalLabel">Alert</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body" id="modalMessage">
          <!-- Message will be dynamically inserted here -->
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>

  <!-- Bootstrap 5 JS and Popper (for Bootstrap components like tooltips or popovers) -->
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js"></script>

  <script>
    // Your JavaScript code here (same as provided)
    // Get references to the HTML elements
    const userInput = document.getElementById("userInput");
    const sendBtn = document.getElementById("sendBtn");
    const conversationDiv = document.getElementById("conversation");
    const modalMessage = document.getElementById("modalMessage");
    const customAlertModal = new bootstrap.Modal(document.getElementById('customAlertModal'));

    // Initialize message history array
    let messageHistory = [
      {
        "role": "system",
        "content": "Made by Yuhan Sanchez<br>FakeGPT at your service! ^_^"
      }
    ];

    // Function to display messages in the conversation
    function displayConversation() {
      conversationDiv.innerHTML = '';  // Clear current conversation

      // Loop through message history and display each message
      messageHistory.forEach((msg, index) => {
        const messageDiv = document.createElement('div');
        messageDiv.classList.add('message', msg.role);
        
        // Handle assistant's response with proper formatting
        if (msg.role === "assistant") {
          const formattedMessage = formatResponse(msg.content);
          messageDiv.innerHTML = `<div>${formattedMessage}</div>`;
          
          // Create and append the copy button for assistant's response (only for code blocks)
          const codeBlocks = messageDiv.querySelectorAll('pre code');
          codeBlocks.forEach(codeBlock => {
            const copyButton = document.createElement('button');
            copyButton.classList.add('copy-btn');
            copyButton.textContent = 'Copy';
            copyButton.addEventListener('click', () => copyToClipboard(codeBlock));
            messageDiv.appendChild(copyButton);
          });
        } else {
          messageDiv.textContent = msg.content;
        }
        
        conversationDiv.appendChild(messageDiv);
      });
    }

    // Function to format assistant's response (e.g., handling code or line breaks)
    function formatResponse(response) {
      // Replace line breaks with <br> for proper formatting
      response = response.replace(/\n/g, '<br>');

      // Format bold text (e.g., **bold** to <strong>bold</strong>)
      response = response.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');

      // Format italic text (e.g., _italic_ to <em>italic</em>)
      response = response.replace(/_(.*?)_/g, '<em>$1</em>');

      // Detect and format code blocks (e.g., ```code``` to <pre><code>code</code></pre>)
      response = response.replace(/```(.*?)```/gs, '<pre><code class="code-block">$1</code></pre>');

      return response;
    }


    // Function to copy the content inside code blocks
    function copyToClipboard(codeElement) {
      // Copy only the text content inside the <code> element
      const codeText = codeElement.textContent || codeElement.innerText;

      navigator.clipboard.writeText(codeText).then(() => {
        showAlert('Code copied to clipboard!');
      }).catch(err => {
        console.error('Error copying text: ', err);
      });
    }

    // Function to send the POST request and handle the response
    async function sendMessage() {
      const userMessage = userInput.value.trim();
      
      if (!userMessage) {
        showAlert('Please enter a message!');
        return;
      }

      // Add user message to message history
      messageHistory.push({
        "role": "user",
        "content": userMessage
      });

      // Display updated conversation
      displayConversation();

      // Prepare the message payload
      const message = {
        messages: messageHistory
      };

      try {
        // Send the message to the API and await response
        const response = await fetch('https://gpt-api-bay.vercel.app/chat', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(message)
        });

        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }

        // Parse the API response
        const data = await response.json();

        // Add assistant's reply to message history
        messageHistory.push({
          "role": "assistant",
          "content": data.response
        });

        // Display the updated conversation with the assistant's reply
        displayConversation();

      } catch (error) {
        console.error('Error sending message:', error);
        showAlert('Something went wrong. Please try again.');
      }

      // Clear input field after sending
      userInput.value = '';
      userInput.focus();  // Keep focus on input field
    }

    // Function to show custom alert in modal
    function showAlert(message) {
      modalMessage.textContent = message;
      customAlertModal.show();
    }

    // Add event listener to the button
    sendBtn.addEventListener("click", sendMessage);

    // Optionally, send on Enter key press
    userInput.addEventListener("keypress", function(event) {
      if (event.key === "Enter") {
        sendMessage();
      }
    });

    // Initialize with a greeting message
    displayConversation();
  </script>
</body>
</html>
