<!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');

    const apiKey = "AIzaSyBdVN5g_KM7EG9tm_whPNKyNxxFV6FSbBQ"; // Reemplaza con tu API Key

    async function obtenerSugerencias(texto) {
        const prompt = `Eres un predictor de palabras en espanol y tienes que predecir el la palabra a continuacion de un texto dado. Indica las tres opciones mas probables 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://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp:generateContent?key=${apiKey}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                  contents: [{
                    parts: [{ text: prompt }]
                  }]
                })
            });

            const data = await response.json();

            if (response.ok && data.candidates && data.candidates.length > 0 && data.candidates[0].content.parts) {
              const response_text = data.candidates[0].content.parts[0].text.trim();
              const sugerencias = response_text.split('\n').filter(item => item.trim() !== '');

              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 = '';
        }
    }

    textoUsuario.addEventListener('input', () => {
        const texto = textoUsuario.value;
      
        if(texto.length> 0 && texto.endsWith(' ')){
              const palabras = texto.trim().split(' ');
              const ultimaPalabra = palabras[palabras.length - 1];

             if(ultimaPalabra){
                  obtenerSugerencias(ultimaPalabra);
              }
             
        }
       else if(texto.trim() === ''){
            opcion1.textContent = '';
            opcion2.textContent = '';
            opcion3.textContent = '';
       }
    });
</script>
</body>
</html>
