<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>$MSDOSAI</title>
  <style>
    body { background: black; color: white; font-family: "Courier New", monospace; margin: 0; padding: 20px; }
    footer { margin-top: 20px; font-size: 0.8em; color: gray; text-align: center; }
    #msdos-output { overflow-y: auto; max-height: calc(100vh - 100px); padding-bottom: 20px; }
    #msdos-output input { 
      background: black; 
      color: white; 
      border: none; 
      font-family: "Courier New", monospace; 
      font-size: 1em; 
      width: 90%; 
      outline: none; 
    }
  </style>
</head>
<body>
  <div id="msdos-startup"></div>
  <div id="msdos-output"></div>
  <footer>
    <p>Disclaimer: This information is for entertainment purposes only and is not financial advice. Trading a token is at your own risk, and we are not responsible for any losses. The answers from MS-DOS AI are indicational and also for entertainment purposes only.</p>
    <p><a href="https://x.com/MSDOSAI" target="_blank" style="color: lightblue; text-decoration: none;">Follow us on X</a></p>
  </footer>
  <script>
    const startupLines = ["Booting MS-DOS . . .", "Initializing system components . . .", "Loading configuration files . . .", "System ready.", "C:\\>"];
    const lines = ["C:\\>CHKDSK", "Checking file system . . .", "" + Math.floor(Math.random() * 1000) + " files processed.", "", "C:\\>DIR", "Volume in drive C is $MSDOSAI", "Directory of C:\\", "", "SYSTEM      <DIR><br>Contract Address: <span id='CA'>Loading...</span><br>MARKETCAP: <span id='marketcap'>Loading...</span><br>24H VOLUME: <span id='volume'>Loading...</span><br>TOKEN PRICE: <span id='price'>Loading...</span><br>PERCENT CHANGE: <span id='percentchange'>Loading...</span>", "FILE.TXT            1024 bytes", "", "C:\\>_"];

    let conversationHistory = []; // Array to maintain conversation context



    async function fetchCryptoDataFromDexScreener() {
      const dexScreenerApi = 'https://api.dexscreener.com/latest/dex/tokens/#';
      try {
        const response = await fetch(dexScreenerApi, {
          headers: { 'Content-Type': 'application/json' }
        });

        if (!response.ok) throw new Error(`DexScreener API responded with status ${response.status}`);

        const data = await response.json();
        const token = data.pairs[0];

        // Update DOM elements with the fetched data
        document.getElementById('marketcap').textContent = token.fdv
          ? `$${Number(token.fdv).toLocaleString()}`
          : 'N/A';
        document.getElementById('CA').textContent = token.baseToken.address
        ? token.baseToken.address
        : 'N/A';
        document.getElementById('volume').textContent = token.volume.h24
          ? `$${Number(token.volume.h24).toLocaleString()}`
          : 'N/A';
        document.getElementById('price').textContent = token.priceUsd
          ? `$${Number(token.priceUsd).toFixed(4)}`
          : 'N/A';
        document.getElementById('percentchange').textContent = token.priceChange.h24
          ? `${Number(token.priceChange.h24).toFixed(2)}%`
          : 'N/A';
      } catch (error) {
        console.error('Error fetching crypto data from DexScreener:', error);
        document.getElementById('marketcap').textContent = 'Error';
        document.getElementById('CA').textContent = 'Error';
        document.getElementById('volume').textContent = 'Error';
        document.getElementById('price').textContent = 'Error';
        document.getElementById('percentchange').textContent = 'Error';
      }
    }

    function scrollToBottom() {
      const output = document.getElementById('msdos-output');
      output.scrollTop = output.scrollHeight;
    }

    function typeText(lines, outputElementId, callback) {
      const output = document.getElementById(outputElementId); let index = 0;
      (function typeLine() {
        if (index < lines.length) { 
          output.innerHTML += lines[index++] + "<br>"; 
          setTimeout(typeLine, 300); 
          scrollToBottom();
        } else if (callback) callback();
      })();
    }

    function enablePrompt() {
  const output = document.getElementById('msdos-output');

  // Remove any existing input field before adding a new one
  const existingInput = document.getElementById('msdos-input');
  if (existingInput) existingInput.remove();

  const prompt = document.createElement('div');
  prompt.innerHTML = `C:\\> <input id='msdos-input' type='text' autofocus placeholder='Type your prompt here'>`;
  output.appendChild(prompt);

  const inputField = document.getElementById('msdos-input');
  inputField.focus();

  inputField.addEventListener('keypress', async function(event) {
    if (event.key === 'Enter') {
      const userMessage = inputField.value.trim().toLowerCase();
      if (!userMessage) return;

      const userPrompt = `C:\\> ${userMessage}`;
      output.innerHTML += `<br>${userPrompt}<br>`;
      inputField.value = '';
      scrollToBottom();


      // Check if the user is asking for the AI's name
      const lowerCaseMessage = userMessage.toLowerCase();
      if (lowerCaseMessage.includes("your name") || lowerCaseMessage.includes("who are you")) {
        const aiResponse = "My name is MS-DOS. Your friendly AI assistant.";
        output.innerHTML += `<span style='color:  #37eb34;'>${aiResponse}</span><br>`;
        scrollToBottom();
        enablePrompt(); // Re-enable the prompt for the next input
        return;
      }

      

      // Add user message to conversation history
      conversationHistory.push({ role: 'user', content: userMessage });

      // Default AI response handling
      try {
        const response = await fetch("https://openrouter.ai/api/v1/chat/completions", {
          method: "POST",
          headers: {
            "Authorization": "Bearer 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",
            "Content-Type": "application/json"
          },
          body: JSON.stringify({
            model: "anthropic/claude-3.5-haiku",
            messages: conversationHistory
          })
        });

        if (!response.ok) throw new Error(`AI API responded with status ${response.status}`);

        const data = await response.json();
        const aiResponse = data.choices[0].message.content;
 // Add AI response to conversation history
 conversationHistory.push({ role: 'assistant', content: aiResponse });

        output.innerHTML += `<span style='color: #37eb34;'>${aiResponse}</span><br>`;
        scrollToBottom();
      } catch (error) {
        console.error('Error fetching AI response:', error);
        output.innerHTML += `<span style='color: red;'>Error fetching AI response.</span><br>`;
        scrollToBottom();
      }

      enablePrompt(); // Re-enable input for the next command
    }
  });
}



    typeText(startupLines, 'msdos-startup', () => {
      typeText(lines, 'msdos-output', () => {
        fetchCryptoDataFromDexScreener(); // Fetch token data from DexScreener API
        setInterval(fetchCryptoDataFromDexScreener, 5000); // Fetch token data every 5 seconds
        enablePrompt();
      });
    });
  </script>
</body>
</html>
