<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Autocompletado de Frases con LLM</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      color: #333;
      background: #f0f0f0;
    }
    .container {
      width: 90%;
      max-width: 800px;
      margin: 20px auto;
      background: #fff;
      padding: 20px;
      box-sizing: border-box;
      border-radius: 8px;
    }
    h1 {
      text-align: center;
      color: #333;
      margin-bottom: 15px;
    }
    .input-label {
      display: block;
      margin: 10px 0 5px;
      font-weight: bold;
    }
    #textoUsuario {
      width: 100%;
      padding: 10px;
      font-size: 16px;
      margin-bottom: 20px;
      box-sizing: border-box;
    }
    .suggestions {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }
    .suggestion-box {
      width: 100%;
      min-height: 40px;
      background-color: #f7f7f7;
      border: 1px solid #ccc;
      border-radius: 4px;
      padding: 8px;
      font-size: 16px;
      box-sizing: border-box;
      color: #333;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>Autocompletado  Contextual</h1>
    
    <label class="input-label" for="textoUsuario">Empieza a escribir:</label>
    <input 
      type="text" 
      id="textoUsuario" 
      placeholder="Escribe aquí..." 
      autocomplete="off"
    />

    <div class="suggestions">
      <div id="opcion1" class="suggestion-box"></div>
      <div id="opcion2" class="suggestion-box"></div>
      <div id="opcion3" class="suggestion-box"></div>
    </div>
  </div>

  <script>
    const textoUsuario = document.getElementById('textoUsuario');
    const opcion1 = document.getElementById('opcion1');
    const opcion2 = document.getElementById('opcion2');
    const opcion3 = document.getElementById('opcion3');

    // Reemplaza con tu propia API Key de OpenAI (la misma que el ejemplo anterior)
    const apiKey = 'sk-proj-vfon7m7hdhEFT6NBtEJcT3BlbkFJeMy741lBst04EstF2X1M';

    // Función para obtener las sugerencias de autocompletado (frases completas)
    async function obtenerSugerencias(texto) {
      // Prompt para solicitar frases completas
      const prompt = `
      Dado el texto que el usuario ha escrito: "${texto}", 
      necesito que me adivines la frase commpleta. Propone tres frases completas  coherentes que tengan alta probabilidad de tener el mismo significado semantico del texto del usuario. 
      Deben estar ordenadas de más a menos probables, separadas por un salto de línea,
      y no incluyas texto adicional ni repitas el input del usuario.
      `;

      try {
        const response = await fetch('https://api.openai.com/v1/chat/completions', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${apiKey}`
          },
          body: JSON.stringify({
            model: 'gpt-4o-mini',
            messages: [{ role: 'user', content: prompt }],
            temperature: 0.7
          })
        });

        const data = await response.json();

        // Si recibimos datos válidos, interpretamos la respuesta
        if (response.ok && data.choices && data.choices.length > 0) {
          const respuesta = data.choices[0].message.content.trim();

          // Dividimos la respuesta en líneas
          const sugerencias = respuesta.split('\n').filter(item => item.trim() !== '');

          // Asignar cada línea a un recuadro
          opcion1.textContent = sugerencias[0] ? sugerencias[0] : '';
          opcion2.textContent = sugerencias[1] ? sugerencias[1] : '';
          opcion3.textContent = sugerencias[2] ? sugerencias[2] : '';
        } else {
          opcion1.textContent = 'No se recibieron sugerencias.';
          opcion2.textContent = '';
          opcion3.textContent = '';
        }
      } catch (error) {
        console.error('Error:', error);
        opcion1.textContent = 'Ocurrió un error al obtener las sugerencias.';
        opcion2.textContent = '';
        opcion3.textContent = '';
      }
    }

    // Cada vez que el usuario teclea algo, se invoca la función para obtener nuevas frases sugeridas
    textoUsuario.addEventListener('input', () => {
      const texto = textoUsuario.value.trim();

      // Llamamos a la función si hay algo de texto
      if (texto.length > 0) {
        obtenerSugerencias(texto);
      } else {
        opcion1.textContent = '';
        opcion2.textContent = '';
        opcion3.textContent = '';
      }
    });
  </script>
</body>
</html>
