import { questions } from "./soal.js";

const questionElement = document.getElementById("question")
const answerBtn = document.getElementById("btn-answer")

let currentQuestionIndex = 0;
let score = 0;

let wrongCount = 0;
let maxWrong = 3;

function shuffle(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}

function startQuiz(){
    currentQuestionIndex = 0;
    score = 0;
    shuffle(questions);
    showQuestion();
}


function showQuestion(){
    resetState();
    let currentQuestion = questions[currentQuestionIndex]
    let questionNumber = currentQuestionIndex + 1
    questionElement.innerHTML = questionNumber + ". " + currentQuestion.question;
    currentQuestion.answers.forEach(answer => {
        const button = document.createElement("button");
        button.innerHTML = answer.text;
        button.classList.add("btn");
        answerBtn.appendChild(button);
        button.dataset.correct = answer.correct;
        button.addEventListener("click", selectAnswer)
    });
}

function resetState(){
    while(answerBtn.firstChild){
        answerBtn.removeChild(answerBtn.firstChild)
    }
}

function updateHearts(){
    const hearts = [
        document.getElementById("h1"),
        document.getElementById("h2"),
        document.getElementById("h3")
    ];

    hearts.forEach((h, i) => {
        if(i < wrongCount){
            h.src = "/assets/Design/HeartEmpty.png"; 
        } else {
            h.src = "/assets/Design/Heartfull.png";  
        }
    });

}

function dmg(){
    const dmg = document.getElementById("dmg");

    dmg.style.display = "block";

    setTimeout(() => {
        dmg.style.display = "none";
    }, 450);
}

function shake(el){
    el.classList.remove("animate-shake");
    void el.offsetWidth;                 
    el.classList.add("animate-shake");

    el.addEventListener("animationend", () => {
        el.classList.remove("animate-shake");
    }, { once: true });
}


function selectAnswer(e){
    const selectedBtn = e.target;
    const isCorrect = selectedBtn.dataset.correct === "true";
    if(isCorrect){
        selectedBtn.classList.add("correct");
        score += 10;
        shake(document.getElementById("boss"))
        dmg();
    } else {
        selectedBtn.classList.add("Incorrect");
        wrongCount ++;
        shake(document.getElementById("hrt"))
        updateHearts();

        if(wrongCount >= maxWrong){
            setTimeout(()=>{
                showScore();
            }, 500);
            return;
        }
    }

    Array.from(answerBtn.children).forEach(button => {
        if(button.dataset.correct === "true") button.classList.add("correct");
        button.disabled = true;
    },
    setTimeout(nextQuestion, 500)
    );
}

function showScore(){
    resetState();
    const show = questionElement.innerHTML = `you scored ${score} out of ${questions.length}!`;
    postScore(score);
}

function handleNextBtn(){
    currentQuestionIndex++;
    if(currentQuestionIndex < questions.length){
        showQuestion();
    } else {
        showScore();
    }
}

function nextQuestion(){
    if(currentQuestionIndex < questions.length){
        handleNextBtn()
    } else {
        showScore()
    }
}

function postScore(score){
    fetch('/score.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ score:   score })
    })
    .then(r => r.json())
    .then(data => {
        console.log("Server response:", data);
        
        if(data.success || data.message === "Score accumulated") {
            window.location.href = "../leaderboard.php"; 
        } else {
            window.location.href = "../leaderboard.php"; 
        }
    })
    .catch(err => {
        console.error("Fetch error:", err);
        alert("Terjadi kesalahan koneksi.");
    });
}
startQuiz()