let questions = [];
let correctAnswers = 0;

async function startTest() {
    const userName = document.getElementById("participant_name").value.trim();
    const activityType = document.getElementById("activity_type").value;

    if (!userName || !activityType) {
        alert("Por favor, completa todos los campos.");
        return;
    }

    const response = await fetch("fetch_questions_retencion.php");
    questions = await response.json();

    document.getElementById("setup-section").style.display = "none";
    document.getElementById("test-section").style.display = "block";

    loadTestContent();
}

function loadTestContent() {
    const content = questions.map((q, index) => `
        <div>
            <p>${q.text}</p>
            ${q.options.map((option, i) => `
                <label>
                    <input type="radio" name="question${index}" value="${option}"> ${option}
                </label>
            `).join("")}
        </div>
    `).join("");

    document.getElementById("questions-display").innerHTML = content;
    document.getElementById("submit-answers").style.display = "block";
}

async function submitAnswers() {
    const answers = [...document.querySelectorAll("input[type='radio']:checked")];
    if (answers.length !== questions.length) {
        alert("Responde todas las preguntas antes de enviar.");
        return;
    }

    correctAnswers = answers.filter((answer, index) => answer.value === questions[index].answer).length;

    const userName = document.getElementById("participant_name").value;
    const activityType = document.getElementById("activity_type").value;

    const response = await fetch("save_results_retencion.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
            userName,
            activityType,
            correctAnswers,
            totalQuestions: questions.length
        })
    });

    const result = await response.json();
    if (result.success) {
        showResults(result.recommendation);
    } else {
        alert("Error al guardar los resultados.");
    }
}

function showResults(recommendation) {
    document.getElementById("test-section").style.display = "none";
    document.getElementById("result-section").style.display = "block";

    document.getElementById("user-name-result").innerText = document.getElementById("participant_name").value;
    document.getElementById("activity-type-result").innerText = document.getElementById("activity_type").value;
    document.getElementById("correct-answers-result").innerText = `${correctAnswers}/${questions.length}`;
    document.getElementById("recommendation-result").innerText = recommendation;
}
