const score = (answers) => {
	let total = 0;
	let scores = [];
	for (let i = 0; i < answers.length; i++) {
		const questionNumber = answers[i].name;
		if (answers[i].checked) {
			total += Number(answers[i].value);
			scores.push({
				questionNumber: questionNumber,
				points: answers[i].value,
			});
		}
	}
	return { totalPoints: total, scores: scores };
};

const dishOutConsequences = (consequences, points) => {
	for (let i = consequences.length - 1; i >= 0; i--) {
		if (points >= Number(consequences[i].dataset.pointsThreshold)) {
			consequences[i].showModal();
			return;
		}
	}
};

const populateDetails = (detailsElement, scores, total) => {
	detailsElement.innerHTML = `Total Score: ${total} points<br />`;
	for (let i = 0; i < scores.length; i++) {
		detailsElement.innerHTML += `<br />Question ${scores[i].questionNumber >= 10 ? scores[i].questionNumber : "0" + scores[i].questionNumber}: ${scores[i].points} points`;
	}
};

const handleQuizSubmit = () => {
	const answers = document.getElementsByClassName("answer");
	const consequences = document.getElementsByClassName("consequence");
	const details = document.getElementsByClassName("scoreDetails");
	const totalPoints = score(answers).totalPoints;
	const scoreDetails = score(answers).scores;
	for (let i = 0; i < details.length; i++) {
		populateDetails(details[i], scoreDetails, totalPoints);
	}
	dishOutConsequences(consequences, totalPoints);
};
