var maxWidth = 350;
var maxHeight = 350;
var selectColor = '#ffffcc';
var cannotSelectColor = '#eccaca';
var unselectColor = '#eee';
var questionID = "";
/* var selectAllBtnFlag = false; */
function setQuestionDetail(id, breadCrumArr) {
	questionID = id;
	//var questIndexArr = [];
	for (var i = 0; i < questions.length; i++) {
		// console.clear();
		//console.log("question: ", questions[i]);
		//console.log("breadcrum: ", breadCrumArr);
		var bool = true;
		for (var j = 0; j < treeStructure.length; j++) {
			//console.log(treeStructure[j]);
			//console.log("IIIIII: ", breadCrumArr.indexOf(questions[i][treeStructure[j]]));
			if (breadCrumArr.indexOf(questions[i][treeStructure[j]]) == -1) {
				bool = false;
				break;
			}
		}
		if (bool) {
			selectedQuestIndexArr.push(i);
		}
	}
	//console.log("setQuestionDetail=="+selectedQuestIndexArr.length)
	setQuestion();
}

function setQuestion() {
	//console.log("setQuestion"+$("#questBase").length)
	if ($("#questBase").length > 0)
		$("#questBase").empty();

	checkBoxBool = true;

	var allStr = '<div  class="heading column"><span>Questions selected in this section:</span></div>';
	allStr += '<div  class="quest-select column"><span class=quest-num>999/999</span></div>';
	allStr += '<div  class="heading-btn column"><button id=select-btn class=btn-prop>Select All</button><button id=addTo-btn class=btn-prop>Add to test</button></div>';

	$("#questBase").append('<div class="col3">' + allStr + '</div>');

	$('#select-btn').on('click', selectAllQuestion);
	$('#addTo-btn').on('click', function () {
		setAddToDetail(questionID);//this function is addToTestDetail.js file
	});
	$('#header #previewTest').on('click', function () {
		setAddToDetail(questionID, true);//this function is addToTestDetail.js file
	});
	loadAllQuestionImages()
}
//********************************************************************************************//
var selectedQuestIndexArr = [];
var selectIndex = -1;
var urlTemp = [];
var tempTitle = ''
// function loadAllQuestionImages()
// {

// 	selectIndex += 1;
// 	//console.log("0000000000: ", selectIndex, selectedQuestIndexArr.length);
// 	//for(var i=0; i<selectedQuestIndexArr.length; i++)
// 	if(selectIndex < selectedQuestIndexArr.length)	
// 	{
// 		//console.log("11111111111111111111111111111");
// 		var index = selectedQuestIndexArr[selectIndex];
// 		var quest = questions[index].question;
// 		console.log("123***",questions[index].question.image);
// 		img = questions[index].question.image;
// 		console.log(img,"smarty");

// 		//if(selectIndex==0)
// 		//console.log('loadAllQuestionImages',tempTitle, quest.title)	
// 		if(tempTitle != quest.title)	
// 			$("#questBase").append('<div class=title-quest>'+quest.title+'</div>');
// 		tempTitle = quest.title;
// 		if(quest.option.length>0 || quest.image.length>0){
// 			var len = $('.option-quest').length;
// 			var questStr1 = '<div class=option-quest id="option-quest'+index+'"><div class="col2"><div class="column"><span class="hang">'+(len+1)+'. </span>'; 
// 			var questStr2 = '</div><div class="column"><input type="checkbox" class=checkBoxes id="checkBoxes'+index+'"'+'/><label class="fright" for="checkBoxes'+index+'"'+'></label></div></div></div>';
// 			var totQuestStr = questStr1;
// 			if(quest.option.length>0){
// 				var len = $('.option-quest').length;
// 				//$("#questBase").append(questStr1+'<span>'+quest.option+'</span>'+questStr2);
// 				totQuestStr = totQuestStr+'<span>'+quest.option+'</span>';
// 				//checkBoxBaseColor(index);
// 				//loadAllQuestionImages();
// 				//setSelectedQuestTxt();
// 			}
// 			console.log(quest.image.length,"fhytgjjjjjjj");

// 			if(quest.image.length>0){
// 				console.log("loadAllQuestionImages1====="+createJsFileName(quest.image));
// 				var script = document.createElement('script');
// 				script.src = createJsFileName(quest.image);
// 				console.log(script.src,"script.src");

// 				urlTemp.push(createJsFileName(quest.image));
// 				script.onload =  function(){

// 					//----------------------------------------------
// 					var imgTemp = new Image();
// 					imgTemp.src = img;				
// 					imgTemp.onload = function(){
// 					  //alert(imgTemp.width +' '+ imgTemp.height );
// 					  var h = imgTemp.height+"px";
// 					  var w = imgTemp.width+"px";
// 					  //var len = $('.option-quest').length;
// 					  console.log(totQuestStr,img,questStr2);

// 					  var img1 = totQuestStr+'<img src='+img+' style="margin-top: 10px;">'+questStr2;
// 					  console.log(img1);

// 					  $("#questBase").append(img1);
// 					  var imageObj = $("#option-quest"+index+" img");
// 					  imageObj.attr({'src': img});
// 					  imageObj.css({'width':w,'height':h});
// 					  //calculateAspectRatioFit(imageObj, maxWidth, maxHeight);

// 					  setSelectedQuestTxt();
// 					  checkBoxBaseColor(index);
// 					  loadAllQuestionImages();
// 					  //imageObj.hide();
// 					};


// 				};
// 				document.head.appendChild(script);
// 			}
// 			else{
// 				totQuestStr = totQuestStr + '</span>'+questStr2;
// 				$("#questBase").append(totQuestStr);
// 				checkBoxBaseColor(index);
// 				loadAllQuestionImages();
// 				setSelectedQuestTxt();
// 			}
// 		}else if(quest.option.length==0 && quest.image.length==0)//ERROR IN config.js file
// 		{
// 			console.log("ERROR IN CONFIG FILE")
// 			loadAllQuestionImages();	
// 		}
// 	}
// 	else{
// 		//console.log("2222222222222222");
// 		$('script').each(function(i){
// 			if(urlTemp.indexOf($(this).attr('src')) > -1)
// 				$(this).remove();
// 		});
// 		selectIndex = -1;
// 		selectedQuestIndexArr.length = 0;
// 		$('.quest-select').find('span').text(0+"/"+$('#questBase').children(".option-quest").length);

// 		$('#select-btn').prop('disabled', true).css("cursor", "default").fadeTo(0,0.6);
// 		setSelectedQuestTxt();
// 		tempTitle = '';
// 		/* $('.option-quest').each(function(){
// 			calculateAspectRatioFit($(this).find('img'), maxWidth, maxHeight);
// 		}); */
// 	}
// }
// function loadAllQuestionImages() {
//   selectIndex += 1;

//   if (selectIndex < selectedQuestIndexArr.length) {
//     const index = selectedQuestIndexArr[selectIndex];
//     const quest = questions[index].question;

//     if (tempTitle !== quest.title) {
//       $("#questBase").append('<div class="title-quest">' + quest.title + '</div>');
//     }

//     tempTitle = quest.title;

//     if (quest.option.length > 0 || quest.image.length > 0) {
//       const len = $('.option-quest').length;
//       let totQuestStr = '<div class="option-quest" id="option-quest' + index + '"><div class="col2"><div class="column"><span class="hang">' + (len + 1) + '.</span>';
//       const questStr2 = '</div><div class="column"><input type="checkbox" class="checkBoxes" id="checkBoxes' + index + '"/><label class="fright" for="checkBoxes' + index + '"></label></div></div></div>';

//       if (quest.option.length > 0) {
//         totQuestStr += '<span>' + quest.option + '</span>';
//       }

//       if (quest.image.length > 0) {
//         const script = document.createElement('script');
//         const imageJsFile = createJsFileName(quest.image);
//         script.src = imageJsFile;
//         urlTemp.push(imageJsFile);

//         script.onload = function () {
//           try {
//             if (typeof img === 'undefined' || !img.startsWith('data:image/')) {
//               console.warn("Invalid or missing image data in JS file:", script.src);
//               loadAllQuestionImages(); // Skip this question
//               return;
//             }

//             const imgTemp = new Image();
//             imgTemp.src = img;

//             imgTemp.onload = function () {
//               const h = imgTemp.height + "px";
//               const w = imgTemp.width + "px";

//               const imgHtml = totQuestStr + '<img src="' + img + '" style="margin-top: 10px; width:' + w + '; height:' + h + ';">' + questStr2;

//               $("#questBase").append(imgHtml);
//               checkBoxBaseColor(index);
//               setSelectedQuestTxt();
//               loadAllQuestionImages(); // Continue to next question
//             };

//             imgTemp.onerror = function () {
//               console.error("Image failed to load:", imgTemp.src);
//               loadAllQuestionImages(); // Continue on error
//             };
//           } catch (e) {
//             console.error("Error loading image from script:", e);
//             loadAllQuestionImages();
//           }
//         };

//         script.onerror = function () {
//           console.error("JS file failed to load:", script.src);
//           loadAllQuestionImages();
//         };

//         document.head.appendChild(script);
//       } else {
//         totQuestStr += '</span>' + questStr2;
//         $("#questBase").append(totQuestStr);
//         checkBoxBaseColor(index);
//         setSelectedQuestTxt();
//         loadAllQuestionImages();
//       }
//     } else {
//       console.warn("No image or option text found for question:", index);
//       loadAllQuestionImages();
//     }
//   } else {
//     // All done — cleanup
//     $('script').each(function () {
//       if (urlTemp.includes($(this).attr('src'))) {
//         $(this).remove();
//       }
//     });

//     selectIndex = -1;
//     selectedQuestIndexArr.length = 0;
//     $('.quest-select').find('span').text('0/' + $('#questBase').children(".option-quest").length);
//     $('#select-btn').prop('disabled', true).css("cursor", "default").fadeTo(0, 0.6);
//     setSelectedQuestTxt();
//     tempTitle = '';
//   }
// }

function loadAllQuestionImages() {
	selectIndex += 1;

	if (selectIndex < selectedQuestIndexArr.length) {
		const index = selectedQuestIndexArr[selectIndex];
		const quest = questions[index].question;

		if (tempTitle !== quest.title) {
			$("#questBase").append('<div class="title-quest">' + quest.title + '</div>');
		}

		tempTitle = quest.title;

		if (quest.option.length > 0 || quest.image.length > 0) {
			const len = $('.option-quest').length;
			let totQuestStr = '<div class="option-quest" id="option-quest' + index + '"><div class="col2"><div class="column"><span class="hang">' + (len + 1) + '.</span>';
			const questStr2 = '</div><div class="column"><input type="checkbox" class="checkBoxes" id="checkBoxes' + index + '"/><label class="fright" for="checkBoxes' + index + '"></label></div></div></div>';

			if (quest.option.length > 0) {
				totQuestStr += '<span>' + quest.option + '</span>';
			}

			if (quest.image.length > 0) {
				const script = document.createElement('script');
				const imageJsFile = createJsFileName(quest.image);
				script.src = imageJsFile;
				urlTemp.push(imageJsFile);

				script.onload = function () {
					try {
						// Ensure global variable "img" exists
						if (typeof img === 'undefined' || img === null || img.length < 50) {
							console.warn("Missing or invalid image data in script:", script.src);
							loadAllQuestionImages();
							return;
						}

						// Prepend data URI if missing
						if (!img.startsWith("data:image/")) {
							img = "data:image/jpeg;base64," + img;
						}

						const imgTemp = new Image();
						imgTemp.src = img;

						imgTemp.onload = function () {
							//   const h = imgTemp.height + "px";
							//   const w = imgTemp.width + "px";
							//   	//   var img1 = totQuestStr+'<img src='+img+' style="margin-top: 10px;">'+questStr2;
							//   const imgHtml = totQuestStr + '<img src="' + img + '" style="margin-top: 10px;>' + questStr2;
							const fixedWidth = 300; // set fixed width in pixels
							const ratio = imgTemp.height / imgTemp.width;
							const calculatedHeight = fixedWidth * ratio;

							const h = calculatedHeight + "px";
							const w = fixedWidth + "px";

							const imgHtml = totQuestStr +
								'<img src="' + img + '" style="margin-top: 10px; width:' + w + '; height:' + h + ';">' +
								questStr2;

							$("#questBase").append(imgHtml);
							checkBoxBaseColor(index);
							setSelectedQuestTxt();
							loadAllQuestionImages();
						};

						imgTemp.onerror = function () {
							console.error("Failed to load image content:", imgTemp.src);
							loadAllQuestionImages();
						};
					} catch (e) {
						console.error("Error while loading image from script:", e);
						loadAllQuestionImages();
					}
				};

				script.onerror = function () {
					console.error("Failed to load JS image file:", script.src);
					loadAllQuestionImages();
				};

				document.head.appendChild(script);
			} else {
				totQuestStr += '</span>' + questStr2;
				$("#questBase").append(totQuestStr);
				checkBoxBaseColor(index);
				setSelectedQuestTxt();
				loadAllQuestionImages();
			}
		} else {
			console.warn("Question has no image or option:", index);
			loadAllQuestionImages();
		}
	} else {
		// All done
		$('script').each(function () {
			if (urlTemp.includes($(this).attr('src'))) {
				$(this).remove();
			}
		});

		selectIndex = -1;
		selectedQuestIndexArr.length = 0;
		$('.quest-select').find('span').text('0/' + $('#questBase').children(".option-quest").length);
		$('#select-btn').prop('disabled', true).css("cursor", "default").fadeTo(0, 0.6);
		setSelectedQuestTxt();
		tempTitle = '';
	}
}

function calculateAspectRatioFit(tag, maxW, maxH) {
	var srcWidth = tag.width();
	var srcHeight = tag.height();
	//console.log('calculateAspectRatioFit0', srcWidth, srcHeight)

	if (maxW < srcWidth || maxH < srcHeight) {
		var ratio = Math.min(maxW / srcWidth, maxH / srcHeight);
		//console.log('calculateAspectRatioFit5', ratio,  srcWidth*ratio,  srcHeight*ratio)
		//tag.css({'width': srcWidth*ratio+'px','height': srcHeight*ratio+'px'});
		//tag.css({'width': ratio*100+'%','height': ratio*100+'%'});
		tag.css({ 'width': '', 'height': '' });
		tag.attr({ 'width': srcWidth * ratio + 'px', 'height': srcHeight * ratio + 'px' });
	}
	//return { width: srcWidth*ratio, height: srcHeight*ratio };
}
function checkBoxBaseColor(index) {
	//check if the question is pre selected 
	if (findQuestion(index) > -1) {
		$('.option-quest #checkBoxes' + index).closest('.option-quest').css("background-color", cannotSelectColor);
		$('.option-quest #checkBoxes' + index).prop("checked", true);
		$('.option-quest #checkBoxes' + index).on('click', false);
	} else {
		$('.option-quest #checkBoxes' + index).on('click', checkBoxChange);
	}
}
//********************************************************************************************//
var checkBoxBool = true;
function checkBoxChange(e) {
	console.log("changes==" + $(this).attr('id'))
	if (this.checked) {
		$(this).closest('.option-quest').css("background-color", selectColor);
		checkBoxBool = true;
		$(this).prop("checked", true);
		//saveQuestion(questionID, $(this).attr('id').split("checkBoxes")[1]);
	}
	else {
		$(this).closest('.option-quest').css("background-color", unselectColor);
		$(this).prop("checked", false);
		checkBoxBool = false;
		//removeQuestion(questionID, $(this).attr('id').split("checkBoxes")[1]);
	}
	setSelectedQuestTxt();
}
function selectAllQuestion() {

	$('#questBase').children(".option-quest").each(function () {
		var index = $(this).find('.checkBoxes').attr("id").split("checkBoxes")[1];
		if (findQuestion(index) == -1) {
			if (!checkBoxBool) {
				$(this).closest('.option-quest').css("background-color", unselectColor);
				$(this).find('.checkBoxes').prop("checked", false);
				$('#select-btn').text('Select All');
			}
			else {
				console.log($(this).find('.checkBoxes').attr("id"))
				$(this).find('.checkBoxes').prop("checked", true);
				$(this).closest('.option-quest').css("background-color", selectColor);
				$('#select-btn').text('Unselect');
			}
		}
	});
	if (!checkBoxBool)
		checkBoxBool = true;
	else
		checkBoxBool = false;
	setSelectedQuestTxt();
}
function setSelectedQuestTxt() {
	$('#addTo-btn').prop('disabled', true).css("cursor", "default").fadeTo(0, 0.6);

	var num = 0;
	$('.option-quest').find('.checkBoxes').each(function () {
		if ($(this).prop("checked")) {
			num += 1;
			if (findQuestion($(this).attr('id').split("checkBoxes")[1]) == -1)
				$('#addTo-btn').prop('disabled', false).css("cursor", "pointer").fadeTo(0, 1);
		} else
			$('#select-btn').prop('disabled', false).css("cursor", "pointer").fadeTo(0, 1);
	});
	$('.quest-select').find('span').text(num + "/" + $('#questBase').children(".option-quest").length)
}