<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>OpenRouter Chat</title>
  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <!-- Highlight.js for code syntax highlighting -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github-dark.min.css" rel="stylesheet">
  <style>
    /* ChatGPT-like UI */
    body {
      background-color: #343541;
      color: #FFFFFF;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      margin: 0;
    }

    .chat-container {
      width: 100%;
      max-width: 800px;
      height: 90vh;
      background-color: #40414F;
      border-radius: 8px;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    }

    .chat-messages {
      flex: 1;
      overflow-y: auto;
      padding: 16px;
      display: flex;
      flex-direction: column;
      gap: 12px;
    }

    .message {
      max-width: 70%;
      display: flex;
      align-items: flex-start;
      gap: 8px;
    }

    .user {
      align-self: flex-end;
    }

    .user .bubble {
      background-color: #343541;
      border-radius: 8px 8px 0 8px;
    }

    .assistant {
      align-self: flex-start;
    }

    .assistant .bubble {
      background-color: #565869;
      border-radius: 8px 8px 8px 0;
    }

    .bubble {
      padding: 12px 16px;
      font-size: 14px;
      line-height: 1.5;
      color: #FFFFFF;
    }

    .chat-input {
      display: flex;
      flex-direction: column;
      gap: 8px;
      padding: 16px;
      background-color: #40414F;
      border-top: 1px solid #565869;
    }

    input {
      background-color: #565869;
      border: none;
      color: #FFFFFF;
      padding: 8px 12px;
      border-radius: 4px;
      font-size: 14px;
    }

    input::placeholder {
      color: #A0A0A0;
    }

    .buttons {
      display: flex;
      gap: 8px;
    }

    .buttons button {
      background-color: #565869;
      color: #FFFFFF;
      border: none;
      padding: 8px 16px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      transition: background-color 0.2s;
    }

    .buttons button:hover {
      background-color: #64748B;
    }

    .image-preview {
      max-width: 100%;
      height: auto;
      border-radius: 8px;
    }

    .clear-chat-btn {
      background-color: #565869;
      color: #FFFFFF;
      border: none;
      padding: 8px 16px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      margin-bottom: 16px;
      transition: background-color 0.2s;
    }

    .clear-chat-btn:hover {
      background-color: #64748B;
    }
  </style>
</head>
<body>

<div class="chat-container">
  <div class="chat-messages" id="chat-messages"></div>
  <div class="chat-input">
    <!-- Clear chat button -->
    <button class="clear-chat-btn" id="clear-chat">Clear Chat</button>
    <!-- Text Input -->
    <input type="text" id="text-input" placeholder="Enter text message..." />
    <!-- URL Input -->
    <input type="text" id="url-input" placeholder="Enter URL..." />
    <!-- Image Upload -->
    <input type="file" id="image-upload" accept="image/*" />
    <!-- Buttons -->
    <div class="buttons">
      <button id="send-text">Send Text</button>
      <button id="send-url">Send URL</button>
      <button id="send-image">Send Image</button>
    </div>
  </div>
</div>

<!-- Highlight.js for syntax highlighting -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
<!-- Marked.js for markdown rendering -->
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
  // Replace with your actual OpenRouter API key
  const apiKey = "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";
  const apiUrl = "https://openrouter.ai/api/v1/chat/completions";

  // Chat history to maintain context
  let chatHistory = [];

  // Function to append a message to the chat interface
  function appendMessage(role, content, type = "text") {
    const chatMessages = document.getElementById('chat-messages');
    const messageElement = document.createElement('div');
    messageElement.className = `message ${role}`;

    if (type === "image") {
      messageElement.innerHTML = `
        <div class="bubble">
          <img src="${content}" alt="Image" class="image-preview">
        </div>
      `;
    } else if (type === "url") {
      messageElement.innerHTML = `
        <div class="bubble">
          <a href="${content}" target="_blank">${content}</a>
        </div>
      `;
    } else {
      // Sanitize and render markdown content
      const markdownContent = marked.parse(content);
      messageElement.innerHTML = `
        <div class="bubble">
          ${markdownContent}
        </div>
      `;
      // Highlight code blocks
      hljs.highlightAll();
    }

    chatMessages.appendChild(messageElement);
    chatMessages.scrollTop = chatMessages.scrollHeight;
  }

  // Function to handle sending text messages
  document.getElementById('send-text').addEventListener('click', async () => {
    const input = document.getElementById('text-input');
    const message = input.value.trim();
    if (!message) return;

    // Clear input
    input.value = '';

    // Append user message
    appendMessage('user', message, "text");

    // Prepare payload
    const payload = {
      model: "google/gemini-2.0-flash-exp:free",
      messages: [
        ...chatHistory,
        {
          role: "user",
          content: [
            { type: "text", text: message }
          ]
        }
      ]
    };

    // Send API request
    await sendApiRequest(payload);
  });

  // Function to handle sending URLs
  document.getElementById('send-url').addEventListener('click', async () => {
    const input = document.getElementById('url-input');
    const url = input.value.trim();
    if (!url) return;

    // Clear input
    input.value = '';

    // Append user message
    appendMessage('user', url, "url");

    // Prepare payload
    const payload = {
      model: "google/gemini-2.0-flash-exp:free",
      messages: [
        ...chatHistory,
        {
          role: "user",
          content: [
            { type: "text", text: `Here is a URL: ${url}` }
          ]
        }
      ]
    };

    // Send API request
    await sendApiRequest(payload);
  });

  // Function to handle sending images
  document.getElementById('send-image').addEventListener('click', async () => {
    const input = document.getElementById('image-upload');
    const file = input.files[0];
    if (!file) return;

    // Read the file as a data URL
    const reader = new FileReader();
    reader.onload = async (event) => {
      const dataURL = event.target.result;

      // Append user message
      appendMessage('user', dataURL, "image");

      // Prepare payload
      const payload = {
        model: "google/gemini-2.0-flash-exp:free",
        messages: [
          ...chatHistory,
          {
            role: "user",
            content: [
              { type: "text", text: "What's in this image?" },
              { type: "image_url", image_url: { url: dataURL } }
            ]
          }
        ]
      };

      // Send API request
      await sendApiRequest(payload);
    };
    reader.readAsDataURL(file);
  });

  // Function to send API request
  async function sendApiRequest(payload) {
    try {
      const response = await fetch(apiUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${apiKey}`,
          "HTTP-Referer": "https://your-site.com", // Replace with your site URL
          "X-Title": "Your Site Name", // Replace with your site name
        },
        body: JSON.stringify(payload)
      });

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

      const data = await response.json();
      console.log("API Response:", data); // Debugging

      // Ensure the response contains choices
      if (!data.choices || !data.choices[0]) {
        throw new Error("Invalid API response: No choices found");
      }

      const assistantResponse = data.choices[0].message.content || "No content returned.";
      chatHistory.push({ role: 'assistant', content: assistantResponse });

      // Append assistant message
      appendMessage('assistant', assistantResponse);

    } catch (error) {
      console.error("API Error:", error); // Debugging
      appendMessage('assistant', `Error: ${error.message}`);
    }
  }

  // Function to clear chat history
  document.getElementById('clear-chat').addEventListener('click', () => {
    if (confirm("Are you sure you want to clear the chat?")) {
      chatHistory = [];
      document.getElementById('chat-messages').innerHTML = '';
    }
  });
</script>

</body>
</html>