<!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 de Frases</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 (idéntica a la del ejemplo anterior)
    const apiKey = 'sk-proj-vfon7m7hdhEFT6NBtEJcT3BlbkFJeMy741lBst04EstF2X1M';

    // Función para obtener las sugerencias de autocompletado
    async function obtenerSugerencias(texto) {
      // Ajusta la prompt según tu necesidad
      const prompt = `Eres un predictor de palabras y tienes que predecir el la palabra a continuacion de un texto dado. Indica las tres opciones masp robables de palabras individuales  que van a  continuación de la ultima palabra del texo siguiente : "${texto}" . Determina el contexto mas probable, y predice las posibles palabras a continuacion.Deben estar ordenadas de más a menos probables. la respuesta no tiene que tener texto o caracteres extra y tiene que tener el siguiente formato: 

Palabra 1

Palabra 2

Palabra 3

corrobora de no repetir palabras, tienen que ser palabras a continuacion del texto, no repitas el texto en cuestion.
`;

      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.6
          })
        });

        const data = await response.json();

        // Si recibimos datos válidos, interpretamos la respuesta
        if (response.ok && data.choices && data.choices.length > 0) {
          // El modelo podría devolver las tres opciones en un solo texto.
          // Suponiendo que vengan separadas por saltos de línea o comas, ajusta el parseo según el formato real.
          const respuesta = data.choices[0].message.content.trim();

          // Aquí vamos a intentar separar por saltos de línea:
          const sugerencias = respuesta.split('\n').filter(item => item.trim() !== '');

          // Si el modelo no trae 3 líneas, nos aseguramos de manejarlo
          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 = '';
      }
    }

    // Escuchamos cada tecla que se presiona en el input
    textoUsuario.addEventListener('input', () => {
      const texto = textoUsuario.value.trim();

      // Llamamos a la función si hay algo de texto que analizar,
      // o limpiamos si el campo está vacío
      if (texto.length > 0) {
        obtenerSugerencias(texto);
      } else {
        opcion1.textContent = '';
        opcion2.textContent = '';
        opcion3.textContent = '';
      }
    });
  </script>
</body>
</html>
