import React, { useState, useEffect, useRef } from "react";
import "../style/index.css";
import "../style/guidedTest.css";
import OptionContainer from "../../chapter/OptionContainer";
import QuestionBodyTestSeries from "../../chapter/QuestionBodyTestSeries";
import ChapterStepper from "../../chapter/ChapterStepper";
import GuidedTestStepper from "../../chapter/GuidedTestStepper";
import { useLocation, useNavigate } from "react-router-dom";
import submitTest from "../api/submitTest";
import ComprehensionBox from "../ComprehensionBox";
import BackDrop from "../../ui/backdrop/BackDrop";
import { LanguagesSlugs } from "../LanguageData";
import "../style/testHeader.css";
import ChatVoiceComponent from "../../chapterPractice/ChatVoiceComponent";
import { processSubject } from "./processSubject";
import Preloader from "../../ui/loading/Preloader";
import oneshotUpdateAndGetRecord from "../api/oneshotupdateAndGetall";
import OpttionContainerOneshot from "../../chapter/OptionContainerOneShot";
import TextToSpeech from "../ellevenlabsVoice/VoiceLabs";
// import getAllChapters from './api/getAllChapters';
// import BackDrop from '../ui/backdrop/BackDrop';
const throttle = (func, limit) => {
let lastFunc;
let lastRan;
return function () {
const context = this;
const args = arguments;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function () {
if (Date.now() - lastRan >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
};
const AnimatedScore = ({ value }) => {
const [prevValue, setPrevValue] = useState(value);
const [isAnimating, setIsAnimating] = useState(false);
useEffect(() => {
console.log("AnimatedScore received new value:", value);
if (value !== prevValue) {
console.log("AnimatedScore animating from", prevValue, "to", value);
setIsAnimating(true);
const timer = setTimeout(() => {
setPrevValue(value);
setIsAnimating(false);
}, 500);
return () => clearTimeout(timer);
}
}, [value]);
const formattedScore = (num) => (num * 100).toFixed(2);
const currentScore = formattedScore(value);
const previousScore = formattedScore(prevValue);
return (
<div style={{ display: "block", margin: 0 }}>
Score →
<span
style={{
position: "relative",
display: "inline-block",
minWidth: "4em",
height: "1.2em",
overflow: "hidden",
}}
>
<span
style={{
position: "absolute",
left: 0,
transform: isAnimating ? "translateY(-100%)" : "translateY(0)",
opacity: isAnimating ? 0 : 1,
transition: "all 500ms ease-out",
}}
>
{isAnimating ? previousScore : currentScore}%
<span
style={{
position: "absolute",
left: 0,
transform: isAnimating ? "translateY(0)" : "translateY(100%)",
opacity: isAnimating ? 1 : 0,
transition: "all 500ms ease-out",
}}
>
{currentScore}%
<span style={{ visibility: "hidden" }}>{currentScore}%
);
};
// Add Hindi translations for encouragement messages
const encouragementMessages = {
wrongAnswer: {
English: [
"Don't worry! Every mistake is a step towards learning.",
"Keep going! Mistakes are part of the learning journey.",
"It's okay to make mistakes! That's how we learn.",
],
Hindi: [
"चिंता न करें! हर गलती सीखने की दिशा में एक कदम है।",
"जारी रखें! गलतियाँ सीखने की यात्रा का हिस्सा हैं।",
"गलतियाँ करना ठीक है! इसी तरह हम सीखते हैं।",
],
},
milestone: {
English: {
5: "You've completed 5 questions! Keep going!",
10: "Great! 10 questions done!",
20: "Awesome! 20 questions completed!",
40: "🔥 40 questions! You're unstoppable!",
50: "Half century! Keep pushing!",
70: "70 questions solved! Amazing!",
90: "90 done! Almost there!",
100: "🎯 100 questions! Excellent effort!",
},
Hindi: {
5: "आपने 5 प्रश्न पूरे कर लिए हैं! जारी रखें!",
10: "शानदार! 10 प्रश्न पूरे!",
20: "कमाल है! 20 प्रश्न पूरे!",
40: "🔥 40 प्रश्न! आप अद्भुत हैं!",
50: "अर्धशतक पूरा! ऐसे ही चलते रहें!",
70: "70 प्रश्न हल हो चुके हैं! शानदार!",
90: "90 हो गए! अब थोड़ा ही बचा है!",
100: "🎯 100 प्रश्न! अद्भुत प्रयास!",
},
},
score: {
English: {
10: "🎉 Great! Your score crossed 10%.",
20: "👏 Well done! 20% achieved.",
40: "🔥 40% score reached!",
60: "Awesome! You hit 60%.",
80: "💯 80%! You're crushing it!",
},
Hindi: {
10: "🎉 बढ़िया! आपका स्कोर 10% पार कर गया है।",
20: "👏 शाबाश! 20% प्राप्त हुआ।",
40: "🔥 40% स्कोर पूरा किया!",
60: "शानदार! आपने 60% हासिल किया।",
80: "💯 80%! आप धूम मचा रहे हैं!",
},
},
completion: {
English: "🎉 Congratulations on completing this test!",
Hindi: "🎉 इस परीक्षा को पूरा करने पर बधाई हो!",
},
};
// Update EncouragementMessage component
const EncouragementMessage = ({ message, type, language }) => {
const [isVisible, setIsVisible] = useState(true);
useEffect(() => {
setIsVisible(true);
const timer = setTimeout(() => {
setIsVisible(false);
}, 5000); // Increased display time to 5 seconds for longer messages
return () => clearTimeout(timer);
}, [message, type]);
if (!isVisible) return null;
// Get the appropriate heading based on message type
const getHeading = () => {
switch (type) {
case 'wrongAnswer':
return '💪 Keep Going!';
case 'achievement':
return '🏆 Achievement Unlocked!';
default:
return '🌟 Great Job!';
}
};
return (
<div
className="encouragement-message"
style={{
position: 'fixed',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
backgroundColor: 'var(--bg-primary-clr)',
padding: '20px 40px',
borderRadius: '10px',
boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
zIndex: 1000,
textAlign: 'center',
border: '2px solid var(--accent-primary-clr)',
animation: 'fadeInOut 5s ease-in-out forwards', // Increased animation time
maxWidth: '80%', // Added max width
width: 'auto', // Allow width to adjust to content
minWidth: '300px', // Minimum width
}}
>
<h3 style={{ margin: '0 0 10px 0', color: 'var(--accent-primary-clr)' }}>
{getHeading()}
<p style={{
margin: 0,
fontSize: '16px',
color: 'var(--text-primary-clr)',
whiteSpace: 'pre-wrap', // Allow text to wrap
wordBreak: 'break-word', // Break long words if needed
lineHeight: '1.5' // Improve readability
}}>
{message}
<button
onClick={() => setIsVisible(false)}
style={{
marginTop: '12px',
padding: '6px 16px',
backgroundColor: 'var(--accent-primary-clr)',
color: 'white',
border: 'none',
borderRadius: '6px',
cursor: 'pointer',
fontSize: '14px'
}}
{language?.id === 'hi' ? 'बंद करें' : 'Close'}
);
};
// Update showEncouragement function
function PracticePage() {
const location = useLocation();
const navigate = useNavigate();
// const [testCategory, setTestCategory] = useState("")
// const [allChapter, setAllChapter] = useState([])
// const [ChapterDropdown, setChapterDropdown] = useState(false)
// const [chapterSelected, setChapterSelected] = useState({})
// const [subTopicSelected, setsubTopicSelected] = useState("All")
// const [examTypeMode, setExamTypeMode] = useState("Both MCQs and Integer Type")
// const [examTypeDropDown, setExamTypeDropDown] = useState(false)
// const [subTopicSelectecdDropDown, setSubTopicSelectecdDropDown] = useState(false)
const [language, setLanguagesSlugs] = useState(
localStorage.getItem("language")
? LanguagesSlugs.filter(
(obj) => obj.id === localStorage.getItem("language")
)[0]
: LanguagesSlugs[0]
);
const [openLanguage, setOpenLanguage] = useState(false);
const { skipInitialLoader } = location.state || {};
const [loading, setLoading] = useState(!skipInitialLoader);
// console.log(location?.state)
let ChapterID = location?.state?.ChapterID;
let UserID = location?.state?.UserID;
// let TestID = location?.state?.TestID;
let ChapterName = location?.state?.ChapterName?.replaceAll(",", ", ");
let TestTitle = location?.state?.TestTitle;
let questionMain = location?.state?.Questions;
let scores = location?.state?.score;
// Store the original question data with all language variants
const [originalQuestions, setOriginalQuestions] = useState(questionMain);
const [question, setQuestionMain] = useState(questionMain);
const [currentQuestion, setCurrentQuestion] = useState(question?.length);
// const [currentQuestion, setCurrentQuestion] = useState(1);
const [totalPages, setTotalPages] = useState(question?.length);
const [score, setScore] = useState(scores);
// console.log(question)
const [questionSubmitted, setQuestionSubmitted] = useState(false);
const [speakerVoiceActivatedOnce, setSpeakerVoiceActivatedOnce] =
useState(false);
const [encouragementMessage, setEncouragementMessage] = useState("");
const [encouragementType, setEncouragementType] = useState("");
const [milestonesShown, setMilestonesShown] = useState({
questions: [],
scores: [],
concepts: [],
});
const [currentTestTitle, setCurrentTestTitle] = useState(TestTitle);
// New useEffect to update currentTestTitle state when TestTitle changes
useEffect(() => {
if (TestTitle) {
setCurrentTestTitle(TestTitle);
}
}, [TestTitle]);
// New useEffect to show message when currentTestTitle changes
useEffect(() => {
if (currentTestTitle) {
showEncouragement(🎉 Congratulations on completing ${currentTestTitle}!);
}
}, [currentTestTitle]);
// Encouragement Message Function
const showEncouragement = (message, type = 'encouragement', langState) => {
// If no message or type is provided, don't show anything
if (!message || !type) {
setEncouragementMessage("");
setEncouragementType("");
return;
}
const lang = langState?.id === 'hi' ? 'Hindi' : 'English';
let translatedMessage;
// Only handle specific message types
switch (type) {
case 'wrongAnswer':
const messages = encouragementMessages[type][lang];
translatedMessage = messages[Math.floor(Math.random() * messages.length)];
break;
case 'score':
if (typeof message === "number") {
translatedMessage = encouragementMessages.score?.[lang]?.[message] || 🌟 Your score just crossed ${message}%!;
}
break;
case 'milestone':
if (typeof message === "number") {
translatedMessage = encouragementMessages.milestone?.[lang]?.[message] || 🎉 You've completed ${message} questions!;
}
break;
case 'completion':
translatedMessage = encouragementMessages.completion?.[lang] || message;
break;
default:
// For any other type, don't show a message
setEncouragementMessage("");
setEncouragementType("");
return;
}
// Only set the message if we have a translated message
if (translatedMessage) {
setEncouragementMessage(translatedMessage);
setEncouragementType(type);
} else {
setEncouragementMessage("");
setEncouragementType("");
}
};
const updateQuestionData = (data, langDefiner) => {
// Create a copy of the data to avoid mutating the original object
const updatedData = { ...data };
// Iterate over the keys of the object
Object.keys(data).forEach((key) => {
const langSpecificKey = `${key}${langDefiner}`;
// console.log(langDefiner)
// Check if the language-specific key exists and is not null
if (
data[langSpecificKey] !== undefined &&
data[langSpecificKey] !== null
) {
updatedData[key] = data[langSpecificKey];
}
});
return updatedData;
};
const questionstr = {
optionChosen: "",
optionBeforeSubmit: "",
};
// console.log(question)
const [questionTestStatus, setQuestionTestStatus] = useState(() =>
question.map((val) => {
return {
...questionstr,
QuestionID: val.QuestionID,
QuestionType: val.QuestionType,
};
})
);
// console.log(language);
// useEffect(() => {
// let selectedOption =
// question[currentQuestion - 1].OptionA ===
// question[currentQuestion - 1].optionBeforeSubmit
// ? "a"
// : question[currentQuestion - 1].OptionB ===
// question[currentQuestion - 1].optionBeforeSubmit
// ? "b"
// : question[currentQuestion - 1].OptionC ===
// question[currentQuestion - 1].optionBeforeSubmit
// ? "c"
// : question[currentQuestion - 1].OptionD ===
// question[currentQuestion - 1].optionBeforeSubmit
// ? "d"
// : question[currentQuestion - 1].OptionE ===
// question[currentQuestion - 1].optionBeforeSubmit
// ? "e"
// : question[currentQuestion - 1].OptionF ===
// question[currentQuestion - 1].optionBeforeSubmit
// ? "f"
// : ""; // Return null if no match is found
// console.log(selectedOption);
// oneshotUpdateAndGetRecord(
// UserID,
// ChapterID,
// question?.length != currentQuestion
// ? "&QuestionID=" + question[currentQuestion - 1]
// : ""
// )
// .then((res) => {
// let adata = res.data;
// let nextQuestion = res.data.nextQuestion;
// if (!nextQuestion && question?.length === currentQuestion) {
// alert("You reached a peak level now pleas wait for more questions");
// }
// let AllQueston = question;
// AllQueston[currentQuestion - 1] = nextQuestion[0];
// console.log(AllQueston[currentQuestion - 1]);
// })
// .catch((err) => console.log(err));
// // }, [currentQuestion]);
// }, [question]);
// console.log(questionTestStatus[currentQuestion - 1]?.optionChosen);
console.log(UserID);
// Add a ref for the TextToSpeech component
const textToSpeechRef = useRef(null);
// functio to show the Encouragement message
// Function to check and show achievements
const checkAchievements = (currentScore, questionsCompleted) => {
const lang = language?.id === 'hi' ? 'Hindi' : 'English';
// Score-based achievements
if (currentScore >= 0.8 && !milestonesShown.scores.includes('high_score')) {
const message = encouragementMessages.score[lang][80] || "🎉 High score!";
showEncouragement(message, 'score', language);
setMilestonesShown(prev => ({
...prev,
scores: [...prev.scores, 'high_score']
}));
}
// Question completion achievements
const milestones = {
5: encouragementMessages.milestone[lang][5],
10: encouragementMessages.milestone[lang][10]
};
if (milestones[questionsCompleted] && !milestonesShown.questions.includes(first_${questionsCompleted})) {
showEncouragement(milestones[questionsCompleted], 'milestone', language);
setMilestonesShown(prev => ({
...prev,
questions: [...prev.questions, first_${questionsCompleted}]
}));
}
// Concept completion achievement
if (currentTestTitle && !milestonesShown.concepts.includes(currentTestTitle)) {
const message = encouragementMessages.completion[lang] || 🎉 Completed ${currentTestTitle};
showEncouragement(message, 'completion', language);
setMilestonesShown(prev => ({
...prev,
concepts: [...prev.concepts, currentTestTitle]
}));
}
};
const handleClickNextButton = () => {
// Pause any ongoing speech before proceeding
if (speakerVoiceActivatedOnce && question?.length === currentQuestion - 1) {
setSpeakerVoiceActivatedOnce(false);
}
if (textToSpeechRef.current) {
textToSpeechRef.current.pauseSpeech();
}
console.log("=== API Call Debug ===");
const currentQuestionData = question[currentQuestion - 1];
const currentQuestionStatus = questionTestStatus[currentQuestion - 1];
// Set submitted to true when user clicks next
setQuestionSubmitted(true);
// Check if the answer is wrong and show appropriate message
console.log("Current Question Data:", {
QuestionID: currentQuestionData?.QuestionID,
CorrectOption: currentQuestionData?.CorrectOption,
UserAnswer: currentQuestionStatus?.optionChosen,
});
// Ensure we have valid data before making the API call
if (!currentQuestionData?.QuestionID) {
console.error("Missing QuestionID");
return;
}
// Get the user's answer and correct answer
const userAnswer = currentQuestionStatus?.optionChosen || "";
const correctAnswer = currentQuestionData?.CorrectOption || "";
// Encode parameters properly
const params = new URLSearchParams({
QuestionID: currentQuestionData.QuestionID,
user_answer: userAnswer.toLowerCase(),
correct_answer: correctAnswer.toUpperCase(),
});
// Build API parameters with proper encoding
const apiParams = `&${params.toString()}`;
console.log("API Call Parameters:", {
UserID: UserID?.UserID,
ChapterID: ChapterID,
apiParams: apiParams,
fullURL: `${UserID?.UserID}/${ChapterID}/${apiParams}`,
});
// Make API call
oneshotUpdateAndGetRecord(UserID?.UserID, ChapterID, apiParams)
.then((res) => {
console.log("=== API Response Success ===");
console.log("Response Data:", res.data);
// Add detailed logging for score
console.log("Current score state:", score);
console.log("Score from API:", res.data.score);
console.log("Score type:", typeof res.data.score);
if (!res.data) {
console.error("No data received from API");
return;
}
const { nextQuestion, score: newScore } = res.data;
// Always update score if provided
if (typeof newScore === "number") {
console.log("Updating score from", score, "to", newScore);
setScore(newScore);
const questionsCompleted = currentQuestion;
const roundedScore = parseFloat((newScore * 100).toFixed(1));
// ✅ 1. Question Milestones
const questionMilestones = [5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
if (
questionMilestones.includes(questionsCompleted) &&
!milestonesShown.questions.includes(questionsCompleted)
) {
showEncouragement(questionsCompleted, 'milestone',language); // 🔄 Pass milestone value
setMilestonesShown((prev) => ({
...prev,
questions: [...prev.questions, questionsCompleted],
}));
}
// ✅ 2. Score Milestones
const scoreMilestones = [10, 20, 40, 60, 80];
const crossedMilestone = scoreMilestones.find(
(milestone) =>
roundedScore >= milestone && !milestonesShown.scores.includes(milestone)
);
if (crossedMilestone) {
showEncouragement(crossedMilestone, 'score',language); // 🔄 Pass score milestone value
setMilestonesShown((prev) => ({
...prev,
scores: [...prev.scores, crossedMilestone],
}));
}
}
else if (newScore !== undefined) {
// Try to convert the score to a number if it's not already
const parsedScore = parseFloat(newScore);
if (!isNaN(parsedScore)) {
console.log(
"Updating score from",
score,
"to",
parsedScore,
"(after conversion)"
);
setScore(parsedScore);
} else {
console.error("Invalid score format received:", newScore);
}
} else {
console.warn("No score received in API response");
}
// If we have a next question and we're at the last question, add it
if (nextQuestion?.length > 0 && currentQuestion === question.length) {
console.log("Adding new question:", nextQuestion[0]);
// First, update the originalQuestions state with the new questions
const updatedOriginalQuestions = [...originalQuestions, ...nextQuestion];
setOriginalQuestions(updatedOriginalQuestions);
// Then apply translations based on current language
const translatedNextQuestions = nextQuestion.map(questionItem =>
updateQuestionData(questionItem, language.Definer)
);
console.log("Translated new question:", translatedNextQuestions[0]);
const updatedQuestions = [...question, ...translatedNextQuestions];
setQuestionMain(updatedQuestions);
setTotalPages(updatedQuestions.length);
const updatedStatus = [
...questionTestStatus,
{
optionChosen: "",
optionBeforeSubmit: "",
QuestionID: nextQuestion[0].QuestionID,
QuestionType: nextQuestion[0].QuestionType,
},
];
setQuestionTestStatus(updatedStatus);
}
// Allow navigation to next question if available
if (currentQuestion < question.length) {
setCurrentQuestion((prev) => prev + 1);
}
else {
// All questions completed
if (!milestonesShown.questions.includes("complete")) {
// For final question
showEncouragement("🏁 You've completed all the questions! Amazing effort!");
setMilestonesShown((prev) => ({
...prev,
questions: [...prev.questions, "complete"],
}));
}
}
})
.catch((err) => {
console.error("=== API Error Debug ===");
console.error("Error Details:", {
message: err.message,
userAnswer: userAnswer,
correctAnswer: correctAnswer,
questionId: currentQuestionData.QuestionID,
fullURL: `${UserID?.UserID}/${ChapterID}/${apiParams}`,
});
// Still allow navigation on error if there are more questions
if (currentQuestion < question.length) {
setCurrentQuestion((prev) => prev + 1);
}
});
// After updating score and current question
checkAchievements(score, currentQuestion);
// Handle answer feedback
const isCorrect = questionTestStatus[currentQuestion - 1]?.optionChosen === question[currentQuestion - 1]?.CorrectOption;
// Clear any existing message first
setEncouragementMessage("");
setEncouragementType("");
// Only show message for wrong answers
if (!isCorrect) {
showEncouragement("wrongAnswer", 'wrongAnswer', language);
}
};
console.log(questionMain);
useEffect(() => {
console.log("=== Language Switch Debug ===");
console.log("Language changed to:", language?.Name);
console.log("Original Questions length:", originalQuestions?.length);
console.log("Question Test Status length:", questionTestStatus?.length);
if (originalQuestions?.length) {
// We'll handle the question translation in the other useEffect
// This effect will focus solely on updating questionTestStatus based on the new language
// Get the current translated questions from the other useEffect
const updatedDataArray = originalQuestions.map((questionI) =>
updateQuestionData(questionI, language.Definer)
);
// Update the questionTestStatus to preserve user choices while updating text
const updatedStatus = updatedDataArray.map((translatedQuestion, idx) => {
// If we have existing test status for this question, preserve the user choices
if (idx < questionTestStatus.length) {
return {
...questionTestStatus[idx],
// Update the optionBeforeSubmit with the newly translated text
optionBeforeSubmit:
translatedQuestion.UserAnswer &&
translatedQuestion[`Option${translatedQuestion.UserAnswer.toUpperCase()}`]
? translatedQuestion[`Option${translatedQuestion.UserAnswer.toUpperCase()}`]
: ""
};
} else {
// For new questions without existing test status
return {
QuestionID: translatedQuestion.QuestionID,
QuestionType: translatedQuestion.QuestionType,
optionBeforeSubmit:
translatedQuestion.UserAnswer &&
translatedQuestion[`Option${translatedQuestion.UserAnswer.toUpperCase()}`]
? translatedQuestion[`Option${translatedQuestion.UserAnswer.toUpperCase()}`]
: "",
optionChosen: translatedQuestion.UserAnswer ? translatedQuestion.UserAnswer : "",
};
}
});
console.log("Updated status after translation:", updatedStatus?.length);
setQuestionTestStatus(updatedStatus);
}
}, [
language?.id,
language?.Definer
// Remove dependency on originalQuestions as it's handled in the other useEffect
// Remove dependency on questionTestStatus.length to avoid infinite loops
]);
console.log(questionTestStatus);
useEffect(() => {
if (location.state?.Questions?.length) {
setOriginalQuestions(location.state.Questions);
}
}, [location.state?.Questions]);
useEffect(() => {
if (
location.state?.questionTestStatus &&
location.state?.currentQuestion >= 0
) {
setQuestionTestStatus(location.state?.questionTestStatus);
setCurrentQuestion(location.state?.currentQuestion);
}
}, [location?.state]);
useEffect(() => {
const handleKeyPress = (event) => {
// Disable F5 key
if (event.keyCode === 116) {
event.preventDefault();
}
// Disable browser reload (Ctrl+R or Command+R)
if ((event.ctrlKey || event.metaKey) && event.keyCode === 82) {
event.preventDefault();
}
};
const handleBeforeUnload = (event) => {
// Display a confirmation dialog
event.preventDefault();
const confirmationMessage = "Are you sure you want to leave?";
event.returnValue = confirmationMessage; // Standard-compliant browsers
return confirmationMessage; // For legacy browsers
};
// Attach the event listeners when the component mounts
window.addEventListener("keydown", handleKeyPress);
window.addEventListener("beforeunload", handleBeforeUnload);
// Detach the event listeners when the component unmounts
return () => {
window.removeEventListener("keydown", handleKeyPress);
window.removeEventListener("beforeunload", handleBeforeUnload);
};
}, []);
const [containerWidth, setContainerWidth] = useState(
window?.innerWidth < 600.02 ? 350 : 400
);
let comprehensionDataReflector = question?.length
? question[currentQuestion - 1]?.Instructions
: null;
const handleMouseDown = (event) => {
let startX = event.pageX; // Capture the initial X position
const handleDrag = throttle((event) => {
const deltaX = event.pageX - startX; // Calculate the change in X position
setContainerWidth((prevWidth) => {
let newWidth = prevWidth + deltaX;
if (newWidth < 200) {
newWidth = 200;
} else if (newWidth > 800) {
newWidth = 800;
}
startX = event.pageX; // Update the start X position for the next drag movement
return newWidth;
});
}, 16); // Throttle to roughly 60fps (16ms)
const handleMouseUp = () => {
document.removeEventListener("mousemove", handleDrag);
document.removeEventListener("mouseup", handleMouseUp);
};
document.addEventListener("mousemove", handleDrag);
document.addEventListener("mouseup", handleMouseUp);
};
const handleSubmitTest = () => {
navigate("/oneshot");
};
// console.log(comprehensionDataReflector);
useEffect(() => {
if (!skipInitialLoader) {
// Only show loader if not skipping
const timer = setTimeout(() => {
setLoading(false);
}, 1500);
return () => clearTimeout(timer);
}
}, [skipInitialLoader]);
// pagination controls
const goToPage = (page) => {
if (page >= 1 && page <= totalPages) {
// Pause any ongoing speech before changing the question
if (textToSpeechRef.current) {
textToSpeechRef.current.pauseSpeech();
}
setCurrentQuestion(page);
}
};
const getPaginationRange = () => {
const pages = [];
let showPiece = window?.innerWidth > 600.02 ? 2 : 1;
let startPage = Math.max(1, currentQuestion - showPiece);
let endPage = Math.min(totalPages, currentQuestion + showPiece);
// Add previous ellipsis
if (startPage > 1) {
// pages.push("<<");
// pages.push("<");
}
// Add page numbers
for (let i = startPage; i <= endPage; i++) {
pages.push(i);
}
// Add next ellipsis
if (endPage < totalPages) {
// pages.push(">");
// pages.push(">>");
}
return pages;
};
// Reset questionSubmitted when moving to next question
useEffect(() => {
setQuestionSubmitted(false);
}, [currentQuestion]);
useEffect(() => {
if (
// question[currentQuestion - 1]?.QuestionID?.toLowerCase().includes(
// "theory"
// ) &&
question?.length === currentQuestion &&
!speakerVoiceActivatedOnce
) {
setSpeakerVoiceActivatedOnce(true);
} else {
// if (speakerVoiceActivatedOnce &&(question?.length === currentQuestion)) setSpeakerVoiceActivatedOnce(false);
}
}, [question?.length]);
// Add a useEffect to update translated questions whenever originalQuestions changes
useEffect(() => {
console.log("=== Original Questions Update Debug ===");
console.log("Original Questions changed, length:", originalQuestions?.length);
if (originalQuestions?.length && language) {
// Apply current language translations
const updatedDataArray = originalQuestions.map((questionI) =>
updateQuestionData(questionI, language.Definer)
);
console.log("Setting translated questions, length:", updatedDataArray?.length);
setQuestionMain(updatedDataArray);
}
}, [originalQuestions, language?.Definer]); // Only depend on originalQuestions and language.Definer
// useEffect to initialize originalQuestions when component loads
useEffect(() => {
if (location.state?.Questions?.length) {
setOriginalQuestions(location.state.Questions);
}
}, [location.state?.Questions]);
// // Add test buttons for development
// const TestButtons = () => {
// if (process.env.NODE_ENV !== "development") return null;
// return (
// <div style={{
// position: 'fixed',
// bottom: '2rem',
// right: '2rem', // Changed from left to right
// zIndex: 999,
// display: 'flex',
// flexDirection: 'column',
// gap: '0.5rem',
// backgroundColor: 'var(--bg-primary-clr)',
// padding: '1rem',
// borderRadius: '8px',
// boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
// }}>
// <h4 style={{ margin: '0 0 0.5rem 0', color: 'var(--text-primary-clr)' }}>Test Messages
// <button
// onClick={() => showEncouragement("wrongAnswer", 'wrongAnswer',language)}
// style={{
// padding: '0.5rem 1rem',
// backgroundColor: 'var(--accent-primary-clr)',
// color: 'white',
// border: 'none',
// borderRadius: '4px',
// cursor: 'pointer'
// }}
// >
// Test Wrong Answer
//
// <button
// onClick={() => showEncouragement("correctAnswer", 'correctAnswer',language)}
// style={{
// padding: '0.5rem 1rem',
// backgroundColor: 'var(--accent-primary-clr)',
// color: 'white',
// border: 'none',
// borderRadius: '4px',
// cursor: 'pointer'
// }}
// >
// Test Correct Answer
//
// <button
// onClick={() => showEncouragement(5,"milestone", 'milestone',language)}
// style={{
// padding: '0.5rem 1rem',
// backgroundColor: 'var(--accent-primary-clr)',
// color: 'white',
// border: 'none',
// borderRadius: '4px',
// cursor: 'pointer'
// }}
// >
// Test Question Milestone
//
// <button
// onClick={() => showEncouragement(11,"highScore", 'highScore',language)}
// style={{
// padding: '0.5rem 1rem',
// backgroundColor: 'var(--accent-primary-clr)',
// color: 'white',
// border: 'none',
// borderRadius: '4px',
// cursor: 'pointer'
// }}
// >
// Test Score Achievement
//
// <button
// onClick={() => showEncouragement("completion", 'completion',language)}
// style={{
// padding: '0.5rem 1rem',
// backgroundColor: 'var(--accent-primary-clr)',
// color: 'white',
// border: 'none',
// borderRadius: '4px',
// cursor: 'pointer'
// }}
// >
// Test Completion
//
//
// );
// };
if (loading) return ;
console.log("Checking the score at the moment");
console.log(
question[currentQuestion - 1]?.QuestionID?.toLowerCase().includes("theory")
);
return (
{encouragementMessage && (
)}
{/* */}
<div
className="TestButtosContainer testContentViewPort3"
style={{ maxWidth: "100%" }}
>
{TestTitle ? (
<>Title : {TestTitle}</>
) : (
<>Chapter: {ChapterName}</>
)}
{question?.find((obj, idx) => obj.Question_hi != null) ? (
<div
style={{ marginLeft: "0.5rem" }}
// onClick={()=>setOpenLanguage(prev=>!prev)}
>
<div
className="app-btn-1-reverse"
style={{ width: "fit-content", padding: "0.5rem 0.5rem" }}
onClick={() => setOpenLanguage(true)}
>
<TranslateSvg /> {language?.Name}
</div>
{openLanguage ? (
<>
<div
className="dropdownLanguageGuided"
style={{ right: null }}
>
{LanguagesSlugs?.filter(
(obj) => obj.id !== language?.id
)?.map((obj) => (
<div
className="ObjectTileLanguage"
onClick={() => [
setLanguagesSlugs(obj),
localStorage.setItem("language", obj?.id),
setOpenLanguage(false),
]}
>
{obj.Svg}
{obj.Name}
</div>
))}
</div>
<BackDrop
blur
closeHandler={() => setOpenLanguage(false)}
/>
</>
) : null}
</div>
) : null}
</div>
<div
style={{
display: "flex",
alignItems: "center",
gap: "0.4em",
flexDirection: "row-reverse",
flexWrap: "wrap",
}}
>
<button className="app-btn-1" onClick={() => handleSubmitTest()}>
{"Exit practice ->"}
</button>
<div>
{
question?.length === currentQuestion &&
speakerVoiceActivatedOnce && (
<TextToSpeech
ref={textToSpeechRef}
text={
language?.id === "hi"
? (question[currentQuestion - 1]?.QuestionTTS_hi || question[currentQuestion - 1]?.Question_hi)
: (question[currentQuestion - 1]?.QuestionTTS || question[currentQuestion - 1]?.Question)
}
/>
)
}
</div>
</div>
</div>
<div
style={{
display: "inline-block",
alignItems: "center",
marginLeft: "0",
fontFamily: "inherit",
fontSize: "inherit",
lineHeight: "inherit",
}}
>
<button
onClick={() => {
if (textToSpeechRef.current) {
textToSpeechRef.current.pauseSpeech();
}
goToPage(1);
}}
disabled={currentQuestion <= 1}
style={{
background: "none",
border: "none",
color: "inherit",
fontSize: "inherit",
cursor: "pointer",
padding: "0 0.4rem",
opacity: currentQuestion <= 1 ? 0.5 : 1,
}}
>
{"<<"}
</button>
<button
onClick={() => {
if (textToSpeechRef.current) {
textToSpeechRef.current.pauseSpeech();
}
goToPage(currentQuestion - 1);
}}
disabled={currentQuestion <= 1}
style={{
background: "none",
border: "none",
color: "inherit",
fontSize: "inherit",
cursor: "pointer",
padding: "0 0.4rem",
opacity: currentQuestion <= 1 ? 0.5 : 1,
}}
>
{"<"}
</button>
{getPaginationRange().map((page) => (
<span
key={page}
onClick={() => goToPage(page)}
style={{
cursor: "pointer",
padding: "0 0.4rem",
fontWeight: currentQuestion === page ? "bold" : "normal",
color: "inherit",
}}
>
{page}
</span>
))}
<button
onClick={() => {
if (textToSpeechRef.current) {
textToSpeechRef.current.pauseSpeech();
}
goToPage(currentQuestion + 1);
}}
disabled={currentQuestion >= totalPages}
style={{
background: "none",
border: "none",
color: "inherit",
fontSize: "inherit",
cursor: "pointer",
padding: "0 0.4rem",
opacity: currentQuestion >= totalPages ? 0.5 : 1,
}}
>
{">"}
</button>
<button
onClick={() => {
if (textToSpeechRef.current) {
textToSpeechRef.current.pauseSpeech();
}
goToPage(totalPages);
}}
disabled={currentQuestion >= totalPages}
style={{
background: "none",
border: "none",
color: "inherit",
fontSize: "inherit",
cursor: "pointer",
padding: "0 0.4rem",
opacity: currentQuestion >= totalPages ? 0.5 : 1,
}}
>
{">>"}
</button>
</div>
<div
className="TestStartingContainer CompressionBoxCont"
style={{
marginInline: "1%",
marginTop: "0em",
gridTemplateColumns: comprehensionDataReflector ? "" : "1fr",
maxWidth: comprehensionDataReflector ? "" : "calc(90% - 1rem)",
width: comprehensionDataReflector ? "" : "calc(90% - 2rem)",
}}
>
{comprehensionDataReflector ? (
<>
<div className="comprehensionHead">Instructions</div>
<div
className="draggableLine"
onMouseDown={handleMouseDown}
></div>
<div className="comprehensionHead QuestionBig">Question</div>
<ComprehensionBox
containerWidth={containerWidth}
data={comprehensionDataReflector}
render={
question?.length
? question[currentQuestion - 1]?.RenderFormat
: null
}
/>
<div className="comprehensionHead QuestionSmall">Question</div>
<div
className="draggableLine"
onMouseDown={handleMouseDown}
></div>
</>
) : null}
<div
className="TestButtosContainer testContentViewPort"
style={{
maxWidth:
window.innerWidth > 600.02 && comprehensionDataReflector
? `calc(90% - ${containerWidth}px - 1em)`
: "90vw",
// width: `calc(100% - ${containerWidth}px)`,
minWidth:
// window.innerWidth > 600.02 &&
comprehensionDataReflector
? `calc(${90}vw - ${containerWidth}px - 1em)`
: "90vw",
}}
>
{question.map(
(object, idx) =>
currentQuestion === idx + 1 && (
<OpttionContainerOneshot
question={object}
setCurrentQuestion={setCurrentQuestion}
currentQuestion={currentQuestion - 1}
questionTestStatus={questionTestStatus}
setQuestionTestStatus={setQuestionTestStatus}
handleClickNextButton={handleClickNextButton}
/>
)
)}
</div>
{/* <div style={{ height: "4em" }}></div> */}
</div>
{/* Only show ChatVoiceComponent when question is submitted */}
{questionSubmitted && (
<ChatVoiceComponent
question={JSON.stringify({
currentQuestion: question[currentQuestion - 1],
userAnswer: questionTestStatus[currentQuestion - 1]?.optionChosen,
correctAnswer: question[currentQuestion - 1]?.CorrectOption,
explanation:
question[currentQuestion - 1]?.Solution ||
question[currentQuestion - 1]?.Explanation,
})}
/>
)}
</div>
</div>
);
}
export default PracticePage;
export const TranslateSvg = () => {
return (
);
};