<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Pro AI Voice Chat</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css?timestamp=1735852388822">
  <style>
    body {
      margin: 0;
      padding: 0;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 100vh;
      background: url('https://cdn.dribbble.com/users/1259682/screenshots/16962880/media/6734356060129abb881da81f043846f4.gif') no-repeat center center fixed;
      background-size: cover;
    }
    #title {
      font-size: 24px;
      font-family: Lobster;
      color: #00A674;
      margin-bottom: 100px;
      text-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
    }
    #container {
      width: 200px;
      height: 200px;
      background-color: #100630;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      color: white;
      font-family: Arial, sans-serif;
      text-align: center;
      padding: 10px;
      box-shadow: 0 0 15px rgba(0, 0, 0, 0.0);
      font-size: 18px;
      overflow: hidden;
      position: relative;
    }
    #textContainer {
      max-height: 100%;
      overflow-y: auto;
      width: 90%;
      word-wrap: break-word;
    }
    #textContainer.long-text {
      font-size: 14px; /* Rétrécit le texte */
    }
    #micButton {
      position: absolute;
      bottom: 20px;
      right: 20px;
      background-color: transparent;
      border: 2px solid #fff;
      border-radius: 50%;
      width: 50px;
      height: 50px;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
    }
    #micButton i {
      font-size: 24px;
    }
    .mic-on {
      color: green;
    }
    .mic-off {
      color: red;
    }
    #footer {
      font-size: 12px;
      font-family: Arial, sans-serif;
      color: #d3d3d3;
      margin-top: 100px;
      display: flex;
      align-items: center;
      gap: 5px;
    }
  </style>
</head>
<body>
  <div id="title">JAVAS • Voice Assistant BETA TEST</div>
  <div id="container">
    <div id="textContainer">Waiting for your voice...</div>
  </div>
  <button id="micButton" class="mic-on" onclick="toggleMicrophone()">
    <i class="fa fa-microphone"></i>
  </button>
  <div id="footer">
    <i class="fa fa-copyright"></i>
    <span>2025. JAVAS. All rights reserved.</span>
  </div>

  <script>
    const apiUrl = 'https://pro-ai.glitch.me/api-pro-chat';
    const apiKey = '8cbad7db-49b8-45bf-b534-3c5eb4887d0e';

    const container = document.getElementById('container');
    const textContainer = document.getElementById('textContainer');
    const micButton = document.getElementById('micButton');
    let history = [];
    let userInput = "";
    let timeout;
    let isMicrophoneActive = true;

    // Initialize Speech Recognition
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    const recognition = new SpeechRecognition();
    recognition.continuous = false;
    recognition.interimResults = false;
    recognition.lang = "en-US";

    // Toggle microphone state
    function toggleMicrophone() {
      if (isMicrophoneActive) {
        micButton.classList.remove('mic-on');
        micButton.classList.add('mic-off');
        micButton.innerHTML = '<i class="fa fa-microphone-slash"></i>';
        isMicrophoneActive = false;
        recognition.stop(); // Stop any ongoing recognition
        textContainer.textContent = "Microphone is off.";
      } else {
        micButton.classList.remove('mic-off');
        micButton.classList.add('mic-on');
        micButton.innerHTML = '<i class="fa fa-microphone"></i>';
        isMicrophoneActive = true;
        textContainer.textContent = "Microphone is ready. Speak now!";
        recognition.start(); // Restart recognition
      }
    }

    // Handle speech recognition result
    recognition.onresult = (event) => {
      if (!isMicrophoneActive) return; // Ignore results if microphone is off

      userInput = event.results[0][0].transcript;
      textContainer.textContent = `${userInput}`;
      adjustTextSize();

      // Clear any existing timeout
      clearTimeout(timeout);

      // Set a 3-second timeout before sending the message
      timeout = setTimeout(() => {
        sendMessageToAI(userInput);
      }, 3000);
    };

    recognition.onend = () => {
      if (isMicrophoneActive) recognition.start(); // Continue if microphone is on
    };

    // Send message to AI
    async function sendMessageToAI(message) {
      const payload = {
        input: message,
        system: "You are JAVAS, a helpful assistant.",
        history: JSON.stringify(history),
        role: "user",
        text: message,
      };

      try {
        const response = await fetch(apiUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'api-key': apiKey,
          },
          body: JSON.stringify(payload),
        });

        const data = await response.json();
        const aiResponse = data.response;

        // Update history with both user and AI messages
        history.push({ role: 'user', text: message });
        history.push({ role: 'assistant', text: aiResponse });

        // Show AI response in container
        textContainer.textContent = aiResponse;
        adjustTextSize();

        // Speak AI response using GTTS API
        speakResponse(aiResponse);

      } catch (error) {
        console.error('Error communicating with Pro AI:', error);
        textContainer.textContent = "An error occurred. Please try again.";
      }
    }

    // Speak AI response
    function speakResponse(text) {
      const encodedText = encodeURIComponent(text);
      const audioUrl = `https://gtts-api.miniggiodev.fr/${encodedText}?lang=en`;

      const audio = new Audio(audioUrl);
      audio.play();
    }

    // Adjust text size if it gets too long
    function adjustTextSize() {
      const lines = textContainer.textContent.split('\n').length;
      if (lines >= 3) {
        textContainer.classList.add('long-text');
      } else {
        textContainer.classList.remove('long-text');
      }
    }

    recognition.onerror = (event) => {
      console.error("Speech recognition error:", event.error);
      textContainer.textContent = "Error with voice recognition. Please try again.";
    };

    // Start voice chat when page loads
    startVoiceChat();

    async function startVoiceChat() {
      try {
        await navigator.mediaDevices.getUserMedia({ audio: true });
        if (isMicrophoneActive) recognition.start();
      } catch (error) {
        console.error("Microphone permission denied or unavailable:", error);
        textContainer.textContent = "Microphone access is required to use this feature.";
      }
    }
  </script>
</body>
</html>