document.addEventListener('DOMContentLoaded', () => {
	let feedback_success = document.querySelector('.feedback.success');
	let feedback_error = document.querySelector('.feedback.error');
	const checkAnswersButton = document.getElementById('checkAnswersButton');
	let image1 = document.getElementById('randomImage1');
	let image2 = document.getElementById('randomImage2');

	// Function to count red grid items
	function countRedGridItems() {
	  let redCount = 0;
	  gridItems.forEach(function(item) {
	      if (item.classList.contains('clicked')) {
	          redCount++;
	      }
	  });
	  return redCount;
	}

	//pool of image paths
	 const imagePool = [
	    { path: "resources/hand1.jpg", value: 1 },
	    { path: "resources/hand2.jpg", value: 2 },
	    { path: "resources/hand3.jpg", value: 3 },
	    { path: "resources/hand4.jpg", value: 4 },
	    { path: "resources/hand5.jpg", value: 5 }
	];

	//assign images to the img tags
	let imgElement = document.getElementById("randomImage1");
	// Get a random index within the range of imagePaths array
	let randomIndex = Math.floor(Math.random() * imagePool.length);
	imgElement.src = imagePool[randomIndex].path;
	let randomValue = imagePool[randomIndex].value;
	image1.setAttribute('aria-label', randomValue + "δάχτυλα");

	//assign images to the img tags (2)
	let imgElement2 = document.getElementById("randomImage2");
	// Get a random index within the range of imagePaths array
	let randomIndex2 = Math.floor(Math.random() * imagePool.length);
	imgElement2.src = imagePool[randomIndex2].path;
	let randomValue2 = imagePool[randomIndex2].value;
	image2.setAttribute('aria-label', randomValue2 + "δάχτυλα");

	//change grid color by clicking
    let gridItems = document.querySelectorAll('.grid-item');
    gridItems.forEach(function(item) {
      item.addEventListener('click', function() {
      	this.classList.toggle('clicked');
      	let currentLabel = this.getAttribute('aria-label');
      	if (this.classList.contains('clicked')) {
      		if (!currentLabel.includes("επιλεγμένο")) {
      			this.setAttribute('aria-label', currentLabel + " επιλεγμένο");	
      		}
      	} else {
      		let newLabel = currentLabel.replace("επιλεγμένο", "");
      		this.setAttribute('aria-label', newLabel);
      	}
      	
      });
  	});

  	checkAnswersButton.addEventListener('click', () => {
		let redCount = countRedGridItems();
		if (redCount === (randomValue + randomValue2)) {
		    feedback_success.style.display = 'block';
			feedback_error.style.display = 'none';
			//to reload the page and start a new game
			setTimeout(() => {
				// reload the page
				location.reload();
			}, 2000);
		} else {
		    feedback_success.style.display = 'none';
			feedback_error.style.display = 'block';
		}
	});
});

window.onload = function() {
    document.getElementById('container_wrapper').focus();
};