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

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

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;

        showFloatingText();

        shake(document.getElementById("boss"))
        dmg();
        const bgm = document.getElementById("sfx");
        bgm.play()
    } else {
        selectedBtn.classList.add("Incorrect");
        wrongCount ++;
        shake(document.getElementById("hrt"))
        updateHearts();
        const bgm = document.getElementById("sfxhrt");
        bgm.play()

        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();
    answerBorder.remove();
    document.getElementById("h1").remove();
    document.getElementById("h2").remove();
    document.getElementById("h3").remove();
    setTimeout(()=> {
        const bgm = document.getElementById("sfxhrt");
        bgm.play()
        const alerts = document.getElementById("scoreAlert")
        alerts.textContent = `you scored ${score} out of 200 !`;
    }, 600);
    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") {
            setTimeout(() => {
                window.location.href = "../leaderboard.php"; 
            }, 3000); 
        } else {
            setTimeout(() => {
                window.location.href = "../leaderboard.php"; 
            }, 3000);
        }
    })
    .catch(err => {
        console.error("Fetch error:", err);
        alert("Terjadi kesalahan koneksi.");
    });
}
function showFloatingText(){
    const bossContainer = document.querySelector(".boss");
    const point = document.createElement("div");

    point.textContent = "+10";
    point.classList.add("floating-points");

    bossContainer.appendChild(point);

    setTimeout(()=>{
        point.remove();
    }, 800);
}
startQuiz()