Transaltor / quiz.html
Aichatbot12321's picture
Upload 27 files
84e1dd3 verified
Raw History Blame Contribute Delete
98.4 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>AI Pro Suite - Smart Quiz</title> <link rel="manifest" href="/manifest.json"> <meta name="theme-color" content="#0f172a"> <!-- BRAND NEW MONOGLYPHIC-STYLE FONTS --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;600;700&family=JetBrains+Mono:wght@500;700;800&display=swap" rel="stylesheet"> <link rel="stylesheet" href="style.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script> <script src="https://cdnjs.cloudflare.com/polyfill/v3/polyfill.min.js?version=4.8.0"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.6.0/dist/confetti.browser.min.js"></script> <script> MathJax = { tex: { inlineMath: [['$', '$'], ['\\(', '\\)']], displayMath: [['$$', '$$'], ['\\[', '\\]']] }, startup: { typeset: false } }; </script> <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script> <style> /* APPLYING THE NEW MONOGLYPHIC-STYLE FONTS GLOBALLY */ body, input, select, textarea, button, .option-btn { font-family: 'Space Grotesk', sans-serif !important; } h1, h2, h3, .cardTitle, .appTitle, .quiz-btn { font-family: 'Space Grotesk', sans-serif !important; font-weight: 700 !important; letter-spacing: -0.5px; } .num, .shortcut-badge, .timer-box { font-family: 'JetBrains Mono', monospace !important; } .quiz-page-container { width: 100% !important; max-width: 600px !important; margin: 70px auto 0 auto !important; display: flex !important; flex-direction: column !important; padding: 30px 20px 150px 20px !important; transition: opacity 0.3s; } .quiz-card { width: 100% !important; flex-shrink: 0 !important; } .quiz-setup, .quiz-active, .quiz-results { display: none !important; animation: fadeIn 0.4s ease; } .quiz-setup.active, .quiz-active.active, .quiz-results.active { display: flex !important; flex-direction: column !important; } @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } } .quiz-btn { background: linear-gradient(135deg, #a855f7, #7e22ce); color: white; padding: 16px; border-radius: 30px; font-size: 19px; width: 100%; border: none; cursor: pointer; box-shadow: 0 10px 30px rgba(168,85,247,0.4); margin-top: 25px; transition: 0.2s; text-align: center; } .quiz-btn:active { transform: scale(0.97); } input[type="number"].standard, select.standard { width: 100%; padding: 15px 20px; background: rgba(15, 23, 42, 0.6); border: 1px solid rgba(255, 255, 255, 0.1); color: #f8fafc; border-radius: 12px; outline: none; font-size: 15px; box-sizing: border-box; appearance: none; font-weight: 600; } input[type="number"].standard:focus, select.standard:focus { border-color: #c084fc; background: rgba(15, 23, 42, 0.9); } .option-btn { background: rgba(255, 255, 255, 0.05); border: 2px solid rgba(255, 255, 255, 0.1); color: #f8fafc; padding: 16px; border-radius: 12px; font-size: 16px; font-weight: 600; text-align: left; cursor: pointer; transition: all 0.2s; margin-bottom: 12px; word-wrap: break-word; } .option-btn:hover { background: rgba(255, 255, 255, 0.1); border-color: #38bdf8; } .option-btn.selected { background: rgba(56, 189, 248, 0.2) !important; border-color: #38bdf8 !important; box-shadow: 0 0 15px rgba(56, 189, 248, 0.3) !important; } .stat-box { background: rgba(0,0,0,0.3); border: 1px solid rgba(255,255,255,0.1); padding: 15px 10px; border-radius: 15px; text-align: center; flex: 1 1 28%; min-width: 80px; } .stat-box .num { font-size: 32px; font-weight: 900; } .result-card { background: rgba(0,0,0,0.2); border: 1px solid rgba(255,255,255,0.05); border-radius: 12px; padding: 20px; margin-bottom: 15px; text-align: left; word-wrap: break-word; } select.standard option { background: #0f172a; color: white; } .subj-btn { background: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.1); color: #f8fafc; padding: 15px; border-radius: 12px; font-size: 16px; text-align: center; font-weight: 600; cursor: pointer; transition: all 0.2s; flex-shrink: 0; } .subj-btn:hover { background: rgba(168, 85, 247, 0.2); border-color: #a855f7; } .subj-scroll-container { display: flex; flex-direction: column; gap: 10px; max-height: 60vh; overflow-y: auto; padding-right: 10px; -webkit-overflow-scrolling: touch; } .subj-scroll-container::-webkit-scrollbar { width: 4px; } .subj-scroll-container::-webkit-scrollbar-thumb { background: rgba(168, 85, 247, 0.5); border-radius: 10px; } /* Timer UI */ .timer-box { background: rgba(239, 68, 68, 0.15); border: 1px solid rgba(239, 68, 68, 0.4); color: #ef4444; padding: 5px 12px; border-radius: 20px; font-weight: 800; font-size: 15px; display: flex; align-items: center; gap: 6px; transition: 0.3s; } .timer-box.hurry { animation: pulseRedText 1s infinite; } @keyframes pulseRedText { 0% { background: rgba(239, 68, 68, 0.15); } 50% { background: rgba(239, 68, 68, 0.4); color: #fff; } 100% { background: rgba(239, 68, 68, 0.15); } } /* Mic Buttons */ .mic-btn-main { background: rgba(239, 68, 68, 0.1); border: 2px solid #ef4444; color: #ef4444; padding: 20px; border-radius: 50%; font-size: 24px; cursor: pointer; transition: 0.3s; width: 80px; height: 80px; display: flex; align-items: center; justify-content: center; margin: 15px auto; box-shadow: 0 0 15px rgba(239,68,68,0.2); } .mic-btn-main.recording { background: #ef4444; color: white; animation: pulseRedText 1s infinite; box-shadow: 0 0 30px rgba(239, 68, 68, 0.6); } /* YOUTUBE APP ANIMATED LOADER */ #global-loader { position: fixed; top: -100px; left: 50%; transform: translateX(-50%); background: linear-gradient(135deg, #ff0844 0%, #ffb199 100%); color: white; padding: 12px 30px; border-radius: 20px; font-weight: 700; font-size: 16px; box-shadow: 0 10px 30px rgba(255,8,68,0.5); z-index: 10000; transition: top 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); display: flex; flex-direction: column; align-items: center; pointer-events: none;} #global-loader.active { top: 30px; } .spinner { width: 22px; height: 22px; border: 3px solid rgba(255,255,255,0.3); border-radius: 50%; border-top-color: white; animation: spin 1s ease-in-out infinite; } @keyframes spin { to { transform: rotate(360deg); } } .indeterminate-loader-bar { width: 100%; min-width: 150px; height: 4px; background: rgba(255,255,255,0.2); border-radius: 2px; overflow: hidden; position: relative; margin-top: 8px; } .indeterminate-loader-progress { position: absolute; top: 0; left: -50%; width: 50%; height: 100%; background: white; border-radius: 2px; animation: loaderSweep 1.2s infinite ease-in-out; box-shadow: 0 0 8px white; } @keyframes loaderSweep { 0% { left: -50%; } 100% { left: 100%; } } /* DANGER TIMER VIGNETTE (< 5s) */ #red-vignette { position: fixed; inset: 0; pointer-events: none; z-index: 9998; box-shadow: inset 0 0 0px rgba(239, 68, 68, 0); transition: box-shadow 0.3s ease; } #red-vignette.active { animation: dangerFlash 0.8s infinite; } @keyframes dangerFlash { 0% { box-shadow: inset 0 0 0px rgba(239, 68, 68, 0); } 50% { box-shadow: inset 0 0 80px rgba(239, 68, 68, 0.7), inset 0 0 20px rgba(239, 68, 68, 0.9); } 100% { box-shadow: inset 0 0 0px rgba(239, 68, 68, 0); } } .shortcut-badge { background: rgba(255,255,255,0.1); color: #94a3b8; font-size: 12px; padding: 2px 6px; border-radius: 4px; margin-right: 8px; font-weight: bold; border: 1px solid rgba(255,255,255,0.1); } /* Focus Mode purely hides nav, keeps original background */ body.zen-focus-active .topbar, body.zen-focus-active .sidebar { display: none !important; } body.zen-focus-active .quiz-page-container { margin-top: 20px !important; } .map-dot { width: 8px; height: 8px; border-radius: 50%; background: rgba(255,255,255,0.1); transition: 0.3s; } .map-dot.current { background: #38bdf8; box-shadow: 0 0 5px #38bdf8; transform: scale(1.3); } .map-dot.answered { background: #22c55e; } .map-dot.skipped { background: #f59e0b; } .score-donut { width: 120px; height: 120px; border-radius: 50%; background: conic-gradient(#22c55e var(--pct), rgba(0,0,0,0.3) 0); display: flex; align-items: center; justify-content: center; margin: 0 auto 20px auto; transition: --pct 1s ease-out; } .donut-inner { width: 90px; height: 90px; background: #0f172a; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 26px; font-weight: 900; color: white; border: 1px solid rgba(255,255,255,0.05); } </style> </head> <body> <div id="red-vignette"></div> <!-- CLASSIC LOADER REVERTED WITH FONT FIX --> <div id="global-loader"> <div style="display: flex; align-items: center; gap: 12px;"> <div class="spinner" id="loaderSpinner"></div> <span id="loaderText">Loading...</span> </div> <div class="indeterminate-loader-bar"><div class="indeterminate-loader-progress"></div></div> </div> <div class="overlay" id="overlay"></div> <div class="topbar"> <div class="menuBtn" onclick="toggleSidebar()">☰</div> <div class="appTitle">AI Pro Suite</div> </div> <div class="sidebar" id="sidebar" style="overflow-y:auto;"> <button class="sidebar-close-btn" onclick="toggleSidebar()">✖ Close Menu</button> <button onclick="window.location.href='index.html'">🏠 Dashboard</button> <button onclick="window.location.href='lens.html'">✨ Lens Studio</button> <button onclick="window.location.href='books.html'">📚 Book Deep Study</button> <button onclick="window.location.href='maths.html'">🧮 Math Solver</button> <button onclick="window.location.href='search.html'">🔎 Deep Search</button> <button onclick="window.location.href='downloader.html'">📥 Video Downloader</button> <button onclick="window.location.href='board.html'">📋 Whiteboard</button> <button onclick="window.location.href='clone.html'">📑 Website Cloner</button> <button onclick="window.location.href='runhtml.html'">🌐 Write HTML</button> <button onclick="window.location.href='youtube.html'">▶️ YouTube Search</button> <button onclick="window.location.href='managequiz.html'">⚙️ Manage Quiz</button> <button onclick="window.location.href='tutor.html'">👨‍🏫 AI Tutor</button> <button onclick="window.location.href='quiz.html'" style="border-left: 4px solid var(--primary); color: var(--primary); background: var(--border-light);">📝 Take a Quiz!</button> <button onclick="window.location.href='book_quiz.html'">📝 Take a Book Quiz!</button> <button onclick="window.location.href='tables.html'">🔢 Maths Table</button> <button onclick="window.location.href='coding.html'">💻 AI Coding</button> <button onclick="window.location.href='chess.html'">♟️ Chess AI</button> <button onclick="window.location.href='translator.html'">🎙️ Text Translator</button> <button onclick="window.location.href='image.html'">🖼️ Image Translator</button> <button onclick="window.location.href='create.html'">🎨 Image Creator</button> <button onclick="window.location.href='qa.html'">📚 Document Q&A</button> <button onclick="window.location.href='history.html'">🕒 History & Downloads</button> <button onclick="window.location.href='storage.html'">📂 Storage</button> <button onclick="window.location.href='hub.html'">🛰️ HF Command Center</button> <button onclick="window.location.href='live.html'">🗣️ Gemini Live</button> </div> <!-- Subject Modal --> <div id="subjectModal" style="display:none; position: fixed; inset: 0; background: rgba(0,0,0,0.85); backdrop-filter: blur(5px); z-index: 100000; align-items: center; justify-content: center; padding: 20px;"> <div class="card" style="width: 100%; max-width: 400px; padding: 25px; display: flex; flex-direction: column; max-height: 85vh;"> <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; flex-shrink: 0;"> <h3 style="color: white; margin: 0; font-size: 20px;">Select Subject</h3> <button id="closeSubjectModalBtn" class="closeBtn" style="position:static; margin: 0; width: 40px; height: 40px;">✕</button> </div> <div class="subj-scroll-container"> <button class="subj-btn main-subj">Science</button> <button class="subj-btn main-subj">Math</button> <button class="subj-btn main-subj">Computer Science</button> <button class="subj-btn main-subj">English Grammar</button> <button class="subj-btn main-subj">Hindi Grammar</button> <button class="subj-btn main-subj">SST</button> <button class="subj-btn main-subj">Geography</button> <button class="subj-btn main-subj">History</button> <button class="subj-btn main-subj">GK</button> </div> </div> </div> <!-- Topic Modal --> <div id="topicModal" style="display:none; position: fixed; inset: 0; background: rgba(0,0,0,0.85); backdrop-filter: blur(5px); z-index: 100001; align-items: center; justify-content: center; padding: 20px;"> <div class="card" style="width: 100%; max-width: 400px; padding: 25px; display: flex; flex-direction: column; max-height: 85vh;"> <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; flex-shrink: 0;"> <h3 style="color: white; margin: 0; font-size: 20px;">Select Topic</h3> <button id="closeTopicModalBtn" class="closeBtn" style="position:static; margin: 0; width: 40px; height: 40px;">✕</button> </div> <div class="subj-scroll-container" id="topicListContainer"></div> </div> </div> <!-- Speak Modal --> <div id="speakModal" style="display:none; position: fixed; inset: 0; background: rgba(0,0,0,0.9); backdrop-filter: blur(5px); z-index: 100002; align-items: center; justify-content: center; padding: 20px;"> <div class="card" style="width: 100%; max-width: 400px; padding: 25px; display: flex; flex-direction: column; align-items: center;"> <h3 style="color: white; margin: 0 0 15px 0; font-size: 20px;">🎙️ Speak or Type Answer</h3> <button id="speakMicBtn" class="mic-btn-main" onmousedown="startRecording()" onmouseup="stopRecording()" ontouchstart="startRecording()" ontouchend="stopRecording()">🎤</button> <div id="speakStatus" style="font-size: 14px; color: #94a3b8; margin-bottom: 15px; font-weight: 600;">Hold mic to speak, or type below...</div> <textarea id="speakTranscript" style="width: 100%; height: 100px; background: rgba(0,0,0,0.3); color: white; border: 1px solid #38bdf8; border-radius: 12px; padding: 10px; margin-bottom: 20px; resize: none; font-size:15px; font-weight:600;" placeholder="Speak using the mic, or manually type your answer here..."></textarea> <div style="display: flex; width: 100%; gap: 10px;"> <button class="btn red" style="flex: 1; padding: 12px; border-radius: 12px;" onclick="clearRecording()">🔄 Clear</button> <button class="btn green" style="flex: 1; padding: 12px; border-radius: 12px;" onclick="saveSpeakAnswer()">✅ Save Answer</button> </div> </div> </div> <!-- Adaptive Info Modal --> <div id="adaptiveInfoModal" style="display:none; position: fixed; inset: 0; background: rgba(0,0,0,0.85); backdrop-filter: blur(5px); z-index: 100000; align-items: center; justify-content: center; padding: 20px;"> <div class="card" style="width: 100%; max-width: 400px; padding: 25px;"> <h3 style="color: #38bdf8; margin: 0 0 15px 0; font-size: 20px;">🧠 Adaptive Engine</h3> <p style="color: #cbd5e1; font-size: 15px; margin-bottom: 15px;"> The AI evaluates your performance in chunks (25% at a time). </p> <ul style="color: #94a3b8; font-size: 14px; margin-bottom: 20px; padding-left: 20px;"> <li>Score <b>≥ 80%</b> ➡️ Next chunk becomes <b>Harder</b>.</li> <li>Score <b>≤ 20%</b> ➡️ Next chunk becomes <b>Easier</b>.</li> <li>Requires at least 5 questions to activate.</li> </ul> <button class="btn blue" style="width:100%; padding: 12px; border-radius: 12px;" onclick="document.getElementById('adaptiveInfoModal').style.display='none'">Got it</button> </div> </div> <div id="pdfModal" style="display:none; position: fixed; inset: 0; background: rgba(0,0,0,0.9); backdrop-filter: blur(5px); z-index: 100003; align-items: center; justify-content: center; padding: 20px;"> <div class="card" style="width: 100%; max-width: 400px; padding: 30px; display: flex; flex-direction: column; align-items: center; text-align: center;"> <div id="pdfModalSpinner" class="spinner" style="border-top-color: #ff0844; margin-bottom: 20px;"></div> <h3 id="pdfModalText" style="color: white; margin: 0 0 20px 0; font-size: 20px;">Creating your PDF...</h3> <button id="pdfManualBtn" class="btn blue" style="display: none; width: 100%; padding: 15px; border-radius: 12px; font-weight: bold;">📥 Download Manually</button> <button id="pdfCloseBtn" class="btn red" style="display: none; width: 100%; padding: 15px; border-radius: 12px; font-weight: bold; margin-top: 10px;" onclick="document.getElementById('pdfModal').style.display='none'">✖ Close</button> </div> </div> <div class="page active quiz-page-container" id="quizPageContainer"> <div id="quizSetup" class="card quiz-card quiz-setup active" style="padding: 30px;"> <h2 class="cardTitle" style="color: #a855f7; font-size: 28px; margin-bottom: 25px; text-align: center;">AI Quiz Generator</h2> <div style="text-align: left; margin-bottom: 18px;"> <label style="color: #cbd5e1; font-size: 15px; font-weight: 600; margin-bottom: 8px; display: block;">Quiz Generation Language</label> <select id="quizLanguage" class="standard" style="background: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.1);"> <option value="Hindi">Hindi (हिंदी)</option> <option value="English">English</option> <option value="Hinglish">Hinglish</option> </select> <div id="langLockMsg" style="font-size: 12px; color: #f59e0b; margin-top: 5px; display: none;">Language locked for this subject.</div> </div> <div style="text-align: left; margin-bottom: 18px;"> <label style="color: #cbd5e1; font-size: 15px; font-weight: 600; margin-bottom: 8px; display: block;">Quiz Format</label> <select id="quizModeSelect" class="standard" style="background: rgba(15, 23, 42, 0.6); border: 1px solid rgba(255, 255, 255, 0.1);"> <option value="mcq">Standard (Multiple Choice)</option> <option value="mokhik">Mokhik / Verbal (Speak your answer)</option> <option value="mixed">Mixed (MCQ + Verbal)</option> </select> </div> <div style="text-align: left; margin-bottom: 18px;"> <label style="color: #cbd5e1; font-size: 15px; font-weight: 600; margin-bottom: 8px; display: block;">Subject <span style="font-size:12px; font-weight:normal; color:#64748b;">(Optional - Leave blank)</span></label> <div id="quizSubjectSelector" style="width: 100%; background: rgba(15, 23, 42, 0.6); border: 1px solid rgba(255, 255, 255, 0.1); color: #94a3b8; padding: 15px 20px; border-radius: 12px; font-size: 16px; cursor: pointer; display: flex; justify-content: space-between; align-items: center; box-sizing: border-box;"> <span id="selectedSubjectText">Select Subject... (Or Leave Blank)</span> <span style="font-size: 12px;">▼</span> </div> </div> <div id="topicContainer" style="display: none; text-align: left; margin-bottom: 18px;"> <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;"> <label style="color: #cbd5e1; font-size: 15px; font-weight: 600; margin: 0;">Specific Topic <span style="font-size:12px; font-weight:normal; color:#64748b;">(Optional)</span></label> <button id="topicLangToggle" style="background: rgba(56, 189, 248, 0.1); border: 1px solid rgba(56, 189, 248, 0.3); color: #38bdf8; border-radius: 15px; padding: 5px 12px; font-size: 13px; font-weight: 600; cursor: pointer; display: flex; align-items: center; gap: 5px; transition: 0.2s;"> <span style="font-size: 15px;">🌐</span> English </button> </div> <div id="quizTopicSelector" style="width: 100%; background: rgba(15, 23, 42, 0.6); border: 1px solid rgba(255, 255, 255, 0.1); color: #94a3b8; padding: 15px 20px; border-radius: 12px; font-size: 16px; cursor: pointer; display: flex; justify-content: space-between; align-items: center; box-sizing: border-box;"> <span id="selectedTopicText">Select Topic... (Or Leave Blank)</span> <span style="font-size: 12px;">▼</span> </div> </div> <div style="display: flex; gap: 15px; margin-bottom: 10px;"> <div style="flex: 1; text-align: left;"> <label style="color: #cbd5e1; font-size: 15px; font-weight: 600; margin-bottom: 8px; display: block;">Class / Grade</label> <select id="quizClass" class="standard" style="background: rgba(15, 23, 42, 0.6); border: 1px solid rgba(255, 255, 255, 0.1);"> <option value="" disabled selected>Select Class...</option> <option value="1">Class 1</option><option value="2">Class 2</option><option value="3">Class 3</option> <option value="4">Class 4</option><option value="5">Class 5</option><option value="6">Class 6</option> <option value="7">Class 7</option><option value="8">Class 8</option><option value="9">Class 9</option> <option value="10">Class 10</option><option value="11">Class 11</option><option value="12">Class 12</option> </select> </div> <div style="flex: 1; text-align: left;"> <label style="color: #cbd5e1; font-size: 15px; font-weight: 600; margin-bottom: 8px; display: block;">Questions</label> <input type="number" id="quizCount" class="standard" min="1" max="25" value="5"> </div> </div> <div style="text-align: left; margin-bottom: 18px; margin-top: 10px; background: rgba(0,0,0,0.2); padding: 15px; border-radius: 12px; border: 1px solid rgba(255,255,255,0.05);"> <label style="color: #cbd5e1; font-size: 15px; font-weight: 600; margin-bottom: 8px; display: block;">AI Engine Priority</label> <select id="modelPriority" class="standard" style="background: rgba(15, 23, 42, 0.8); border: 1px solid rgba(255, 255, 255, 0.1); margin-bottom: 15px;" disabled> <option value="API 1" selected>🚀 Forced Direct API 1</option> </select> <label style="display: flex; align-items: center; gap: 10px; color: #f8fafc; font-size: 15px; cursor: pointer; font-weight: 600; margin-bottom: 10px;"> <input type="checkbox" id="enableTimer" checked style="width: 18px; height: 18px; accent-color: #22c55e; cursor: pointer;"> ⏱️ Enable Question Timer </label> <label style="display: flex; align-items: center; gap: 10px; color: #f8fafc; font-size: 15px; cursor: pointer; font-weight: 600; margin-bottom: 10px;"> <input type="checkbox" id="divideMode" style="width: 18px; height: 18px; accent-color: #a855f7; cursor: pointer;"> Divide Questions to Model (Simultaneous) </label> <label id="adaptiveLabel" style="display: flex; align-items: center; gap: 10px; color: #f8fafc; font-size: 15px; cursor: pointer; font-weight: 600; margin-bottom: 5px;"> <input type="checkbox" id="adaptiveDiff" checked style="width: 18px; height: 18px; accent-color: #38bdf8; cursor: pointer;"> 🧠 Adaptive Difficulty Engine <span class="info-icon" onclick="document.getElementById('adaptiveInfoModal').style.display='flex';" style="display:inline-flex; justify-content:center; align-items:center; width:18px; height:18px; border-radius:50%; background:rgba(255,255,255,0.1); font-size:12px; margin-left:5px; border:1px solid rgba(255,255,255,0.2);">i</span> </label> <div id="adaptiveLockMsg" style="font-size: 12px; color: #f59e0b; margin-top: 5px; margin-left: 28px; display: none;">Requires at least 5 questions to enable.</div> </div> <button id="startQuizBtn" class="quiz-btn">🚀 Generate & Start Quiz!</button> </div> <div id="quizActive" class="card quiz-card quiz-active" style="padding: 30px; position:relative;"> <div id="adaptiveLoader" style="display:none; position:absolute; inset:0; background:rgba(15,23,42,0.9); z-index:50; flex-direction:column; align-items:center; justify-content:center; border-radius:12px;"> <div class="spinner" style="border-top-color:#38bdf8; width:30px; height:30px; margin-bottom:10px;"></div> <h3 style="color:white; margin:0;">Engine Adjusting...</h3> </div> <div style="width: 100%; height: 6px; background: rgba(255,255,255,0.1); border-radius: 3px; margin-bottom: 10px; overflow: hidden;"> <div id="quizProgressBar" style="height: 100%; width: 0%; background: #38bdf8; transition: width 0.3s ease;"></div> </div> <!-- FEATURE: Mini-Map --> <div id="miniMap" style="display:flex; gap:6px; margin-bottom:15px; justify-content:center; flex-wrap:wrap;"></div> <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 15px;"> <div style="display: flex; align-items: center; gap: 10px;"> <div id="quizProgress" style="font-weight: 700; color: #38bdf8; font-size: 18px;">Question 1 of 5</div> <div id="timerContainer" class="timer-box">⏱️ <span id="timerText">60s</span></div> </div> <div style="display: flex; gap: 5px; align-items: center;"> <!-- NEW FEATURES: TTS & Focus Buttons --> <button id="ttsBtn" onclick="speakQuestion()" style="background:rgba(255,255,255,0.1); border:none; color:white; padding:6px 10px; border-radius:8px; font-size:13px; font-weight:bold; cursor:pointer;">🔊 Read</button> <button id="focusBtn" onclick="toggleFocusMode()" style="background:rgba(255,255,255,0.1); border:none; color:white; padding:6px 10px; border-radius:8px; font-size:13px; font-weight:bold; cursor:pointer;">🎯 Focus</button> <div id="difficultyBadge" style="font-size: 12px; font-weight: bold; background: rgba(255,255,255,0.1); padding: 5px 10px; border-radius: 8px; color: #cbd5e1; text-transform: uppercase;">Standard</div> </div> </div> <div id="verbalModeBadge" style="display:none; font-size:12px; font-weight:900; background:#ef4444; color:white; padding:6px 12px; border-radius:8px; margin-bottom:10px; width:fit-content; text-transform:uppercase;">🗣️ Mokhik Question</div> <div id="questionText" style="font-size: 22px; font-weight: 600; line-height: 1.5; color: white; margin-bottom: 25px; word-wrap: break-word; white-space: normal;">Loading Question...</div> <div id="optionsContainer" style="display: flex; flex-direction: column;"></div> <div id="verbalActionContainer" style="display:none; text-align:center; padding: 15px; background: rgba(255,255,255,0.05); border-radius: 12px; border: 1px dashed rgba(255,255,255,0.2);"> <div id="verbalRecordedPreview" style="font-size: 15px; color: #22c55e; margin-bottom: 15px; font-weight: 600; min-height: 20px;">No answer recorded yet.</div> <button onclick="openSpeakGui()" class="btn" style="background: #38bdf8; color: white; padding: 14px 25px; border-radius: 20px; font-size: 16px; font-weight: 700; width: 100%;">🗣️ Open Speaker / Typist GUI</button> </div> <div style="display: flex; gap: 15px; margin-top: 25px;"> <button id="skipBtn" class="btn red" style="flex: 0.5; padding: 16px; border-radius: 14px; font-weight: 700; font-size:18px;">Skip ⏭️</button> <button id="nextBtn" class="btn blue" style="flex: 1; padding: 16px; border-radius: 14px; font-weight: 700; font-size:18px;">Next ➡️</button> </div> </div> <div id="quizResults" class="card quiz-card quiz-results" style="background: transparent; border: none; padding: 0;"> <div id="pdfExportArea" class="card" style="padding: 30px; width: 100%; box-sizing: border-box; background-color: #0f172a; color: white;"> <div style="text-align: center; margin-bottom: 20px;"> <h2 style="color: #22c55e; font-size: 34px; margin-bottom: 5px;">Quiz Completed!</h2> <div id="resultSubtext" style="color: #94a3b8; font-weight: 600; margin-bottom: 15px; font-size: 16px;"></div> <!-- FEATURE: Donut Chart --> <div class="score-donut" id="scoreDonut" style="--pct: 0%;"> <div class="donut-inner" id="donutText">0%</div> </div> <div id="performanceMessage" style="font-size: 18px; font-weight: 700; padding: 12px; border-radius: 10px; background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1);"></div> </div> <div style="display: flex; gap: 10px; margin-bottom: 30px; flex-wrap: wrap; justify-content: center;"> <div class="stat-box"><div class="num" id="statCorrect" style="color: #22c55e;">0</div><div style="font-size:13px; color:#94a3b8; margin-top:5px; text-transform:uppercase; font-weight:700;">Correct</div></div> <div class="stat-box"><div class="num" id="statWrong" style="color: #ef4444;">0</div><div style="font-size:13px; color:#94a3b8; margin-top:5px; text-transform:uppercase; font-weight:700;">Incorrect/Skipped</div></div> <div class="stat-box"><div class="num" id="statTotal" style="color: #38bdf8;">0</div><div style="font-size:13px; color:#94a3b8; margin-top:5px; text-transform:uppercase; font-weight:700;">Total</div></div> </div> <h3 style="color: white; margin-bottom: 15px; font-size: 22px; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 10px;">Detailed Review</h3> <div id="reviewContainer"></div> </div> <div style="display: flex; gap: 15px; margin-top: 20px; flex-wrap: wrap; width: 100%;"> <button onclick="downloadPDF()" class="btn red" style="flex: 1; padding: 16px; border-radius: 15px; min-width: 150px; font-weight:700; font-size:16px;">📄 Save PDF</button> <button onclick="exportQuizJSON()" class="btn blue" style="flex: 1; padding: 16px; border-radius: 15px; min-width: 150px; font-weight:700; font-size:16px;">💾 Export JSON</button> <button onclick="location.reload()" class="btn" style="flex: 1; padding: 16px; border-radius: 15px; background: #475569; color: white; min-width: 150px; font-weight:700; font-size:16px;">🔄 New Quiz</button> </div> </div> </div> <script src="ui-controls.js" defer></script> <script src="main.js" defer></script> <script> const vibe = (pattern) => { if(navigator.vibrate) try{ navigator.vibrate(pattern); }catch(e){} }; function toggleSidebar() { const sidebar = document.getElementById("sidebar"); const overlay = document.getElementById("overlay"); const active = !sidebar.classList.contains("active"); sidebar.classList.toggle("active", active); overlay.classList.toggle("active", active); } if(document.getElementById("overlay")) document.getElementById("overlay").onclick = toggleSidebar; function showToast(msg) { let t = document.createElement('div'); t.innerText = msg; t.style.cssText = "position:fixed; bottom:20px; left:50%; transform:translateX(-50%); background:linear-gradient(135deg, #ef4444, #b91c1c); color:white; padding:14px 28px; border-radius:30px; box-shadow:0 10px 25px rgba(0,0,0,0.5); z-index:100000; font-weight:600; font-size: 15px; text-align:center; animation:fadeToast 3s forwards; pointer-events: none;"; document.body.appendChild(t); setTimeout(() => t.remove(), 4000); } // 🚨 BUG FIX: SAFELY UPDATING THE LOADER TEXT function showGlobalLoader(text) { const loaderTextEl = document.getElementById('loaderText'); if (loaderTextEl) { loaderTextEl.innerText = text; } const globalLoaderEl = document.getElementById('global-loader'); if (globalLoaderEl) { globalLoaderEl.classList.add('active'); } } function hideGlobalLoader() { const globalLoaderEl = document.getElementById('global-loader'); if (globalLoaderEl) { globalLoaderEl.classList.remove('active'); } } // 🚀 NEW 63 TOPICS ADDED! const topicData = { "Math": [ { en: "Number System", hi: "संख्या पद्धति" }, { en: "Algebra", hi: "बीजगणित" }, { en: "Geometry", hi: "ज्यामिति" }, { en: "Trigonometry", hi: "त्रिकोणमिति" }, { en: "Mensuration", hi: "क्षेत्रमिति" }, { en: "Statistics", hi: "सांख्यिकी" }, { en: "Probability", hi: "प्रायिकता" }, { en: "Fractions & Decimals", hi: "भिन्न और दशमलव" }, { en: "Linear Equations", hi: "रैखिक समीकरण" }, { en: "Quadratic Equations", hi: "द्विघात समीकरण" }, { en: "Polynomials", hi: "बहुपद" }, { en: "Coordinate Geometry", hi: "निर्देशांक ज्यामिति" }, { en: "Surface Area and Volume", hi: "पृष्ठीय क्षेत्रफल और आयतन" }, { en: "Set Theory", hi: "समुच्चय सिद्धांत" }, { en: "Logarithms", hi: "लघुगणक" }, { en: "Matrices & Determinants", hi: "आव्यूह और सारणिक" }, { en: "Vectors", hi: "सदिश" }, { en: "Calculus Basics", hi: "कैलकुलस के मूल तत्व" }, { en: "Permutations & Combinations", hi: "क्रमचय और संचय" }, { en: "Sequence & Series", hi: "अनुक्रम और श्रेणी" } ], "Science": [ { en: "Physics (General)", hi: "भौतिक विज्ञान (सामान्य)" }, { en: "Chemistry (General)", hi: "रसायन विज्ञान (सामान्य)" }, { en: "Biology (General)", hi: "जीव विज्ञान (सामान्य)" }, { en: "Motion", hi: "गति" }, { en: "Force & Laws of Motion", hi: "बल और गति के नियम" }, { en: "Gravitation", hi: "गुरुत्वाकर्षण" }, { en: "Work and Energy", hi: "कार्य और ऊर्जा" }, { en: "Sound", hi: "ध्वनि" }, { en: "Structure of the Atom", hi: "परमाणु की संरचना" }, { en: "Matter in Our Surroundings", hi: "हमारे आस-पास के पदार्थ" }, { en: "Tissues", hi: "ऊतक" }, { en: "Diversity in Living Organisms", hi: "जीवों में विविधता" }, { en: "Natural Resources", hi: "प्राकृतिक संपदा" }, { en: "Light - Reflection & Refraction", hi: "प्रकाश - परावर्तन तथा अपवर्तन" }, { en: "Electricity", hi: "विद्युत" }, { en: "Magnetic Effects of Electric Current", hi: "विद्युत धारा के चुंबकीय प्रभाव" }, { en: "Chemical Bonding", hi: "रासायनिक आबंधन" }, { en: "Periodic Table", hi: "आवर्त सारणी" }, { en: "Electromagnetism", hi: "विद्युत चुंबकत्व" }, { en: "Optics", hi: "प्रकाशिकी" }, { en: "Thermodynamics", hi: "ऊष्मागतिकी" }, { en: "Cell Biology", hi: "कोशिका जीव विज्ञान" }, { en: "Human Anatomy", hi: "मानव शरीर रचना" } ], "SST": [ { en: "The French Revolution", hi: "फ्रांसीसी क्रांति" }, { en: "Socialism in Europe and the Russian Revolution", hi: "यूरोप में समाजवाद एवं रूसी क्रांति" }, { en: "Nazism and the Rise of Hitler", hi: "नात्सीवाद और हिटलर का उदय" }, { en: "Forest Society and Colonialism", hi: "वन्य समाज एवं उपनिवेशवाद" }, { en: "Pastoralists in the Modern World", hi: "आधुनिक विश्व में चरवाहे" }, { en: "India - Size and Location", hi: "भारत - आकार और स्थिति" }, { en: "Physical Features of India", hi: "भारत का भौतिक स्वरूप" }, { en: "Drainage", hi: "अपवाह" }, { en: "Climate", hi: "जलवायु" }, { en: "Natural Vegetation and Wildlife", hi: "प्राकृतिक वनस्पति तथा वन्य प्राणी" }, { en: "Population", hi: "जनसंख्या" }, { en: "What is Democracy? Why Democracy?", hi: "लोकतंत्र সুবিধা? लोकतंत्र क्यों?" }, { en: "Constitutional Design", hi: "संविधान निर्माण" }, { en: "Electoral Politics", hi: "चुनावी राजनीति" }, { en: "Working of Institutions", hi: "संस्थाओं का कामकाज" }, { en: "Democratic Rights", hi: "लोकतांत्रिक अधिकार" }, { en: "The Story of Village Palampur", hi: "पालमपुर गाँव की कहानी" }, { en: "People as Resource", hi: "संसाधन के रूप में लोग" }, { en: "Poverty as a Challenge", hi: "निर्धनता: एक चुनौती" }, { en: "Food Security in India", hi: "भारत में खाद्य सुरक्षा" }, { en: "Nationalism in India", hi: "भारत में राष्ट्रवाद" }, { en: "The Making of a Global World", hi: "भूमंडलीकृत विश्व का बनना" }, { en: "The Age of Industrialization", hi: "औद्योगीकरण की युग" }, { en: "Print Culture and the Modern World", hi: "मुद्रण संस्कृति और आधुनिक दुनिया" }, { en: "Resources and Development", hi: "संसाधन और विकास" }, { en: "Water Resources", hi: "जल संसाधन" }, { en: "Agriculture", hi: "कृषि" }, { en: "Power Sharing", hi: "सत्ता की साझेदारी" }, { en: "Federalism", hi: "संघवाद" }, { en: "Gender, Religion and Caste", hi: "जाति, धर्म और लैंगिक मसले" }, { en: "Political Parties", hi: "राजनीतिक दल" }, { en: "Outcomes of Democracy", hi: "लोकतंत्र के परिणाम" }, { en: "Sectors of the Indian Economy", hi: "भारतीय अर्थव्यवस्था के क्षेत्रक" }, { en: "The Cold War", hi: "शीत युद्ध" }, { en: "World War I", hi: "प्रथम विश्व युद्ध" }, { en: "Indian Constitution", hi: "भारतीय संविधान" }, { en: "Earthquakes and Volcanoes", hi: "भूकंप और ज्वालामुखी" }, { en: "Global Warming", hi: "ग्लोबल वार्मिंग" }, { en: "International Trade", hi: "अंतर्राष्ट्रीय व्यापार" }, { en: "Human Rights", hi: "मानव अधिकार" } ], "English Grammar": [ { en: "Tenses", hi: "Tenses" }, { en: "Nouns & Pronouns", hi: "Nouns & Pronouns" }, { en: "Active & Passive Voice", hi: "Active & Passive Voice" }, { en: "Direct & Indirect Speech", hi: "Direct & Indirect Speech" }, { en: "Prepositions", hi: "Prepositions" }, { en: "Conjunctions", hi: "Conjunctions" }, { en: "Articles", hi: "Articles" }, { en: "Subject-Verb Agreement", hi: "Subject-Verb Agreement" }, { en: "Modals", hi: "Modals" }, { en: "Idioms & Phrases", hi: "Idioms & Phrases" }, { en: "Sentence Rearrangement", hi: "Sentence Rearrangement" }, { en: "Phrasal Verbs", hi: "Phrasal Verbs" }, { en: "Question Tags", hi: "Question Tags" }, { en: "Conditionals", hi: "Conditionals" }, { en: "Gerunds & Infinitives", hi: "Gerunds & Infinitives" }, { en: "Clauses", hi: "Clauses" }, { en: "Reported Speech", hi: "Reported Speech" }, { en: "Punctuation", hi: "Punctuation" } ], "Hindi Grammar": [ { en: "संज्ञा और सर्वनाम", hi: "संज्ञा और सर्वनाम" }, { en: "मुहावरे और लोकोक्तियाँ", hi: "मुहावरे और लोकोक्तियाँ" }, { en: "संधि और समास", hi: "संधि और समास" }, { en: "विलोम और पर्यायवाची", hi: "विलोम और पर्यायवाची" }, { en: "रस (Ras)", hi: "रस" }, { en: "अलंकार (Alankar)", hi: "अलंकार" }, { en: "प्रत्यय और उपसर्ग", hi: "प्रत्यय और उपसर्ग" }, { en: "वाक्य भेद", hi: "वाक्य भेद" }, { en: "पत्र लेखन (Format)", hi: "पत्र लेखन (प्रारूप)" }, { en: "अनुच्छेद लेखन", hi: "अनुच्छेद लेखन" }, { en: "वाच्य (Voice)", hi: "वाच्य" }, { en: "पद परिचय", hi: "पद परिचय" }, { en: "वाक्य शुद्धि", hi: "वाक्य शुद्धि" }, { en: "शब्द विचार", hi: "शब्द विचार" }, { en: "छंद", hi: "छंद" }, { en: "अनेकार्थी शब्द", hi: "अनेकार्थी शब्द" }, { en: "श्रुतिसमभिन्नार्थक शब्द", hi: "श्रुतिसमभिन्नार्थक शब्द" } ], "Computer Science": [ { en: "Computer Networks", hi: "कंप्यूटर नेटवर्किंग" }, { en: "Database Management (DBMS)", hi: "डेटाबेस मैनेजमेंट" }, { en: "HTML & CSS Basics", hi: "HTML और CSS मूल बातें" }, { en: "Python Programming", hi: "पायथन प्रोग्रामिंग" }, { en: "Data Structures", hi: "डेटा संरचना (Data Structures)" }, { en: "Cyber Security", hi: "साइबर सुरक्षा" }, { en: "Operating Systems", hi: "ऑपरेटिंग सिस्टम" }, { en: "Binary Mathematics", hi: "बाइनरी गणित" }, { en: "Artificial Intelligence", hi: "कृत्रिम बुद्धिमत्ता" }, { en: "Machine Learning", hi: "मशीन लर्निंग" }, { en: "Cloud Computing", hi: "क्लाउड कंप्यूटिंग" }, { en: "Number Systems (Hex/Octal)", hi: "संख्या प्रणाली" }, { en: "Boolean Algebra", hi: "बूलियन बीजगणित" }, { en: "Web Development", hi: "वेब विकास" }, { en: "SQL Queries", hi: "SQL क्वेरी" } ], "Geography": [ { en: "World Geography", hi: "विश्व का भूगोल" }, { en: "Physical Geography", hi: "भौतिक भूगोल" }, { en: "Human Geography", hi: "मानव भूगोल" }, { en: "Maps and Topography", hi: "मानचित्र और स्थलाकृति" }, { en: "Environment and Ecology", hi: "पर्यावरण और पारिस्थितिकी" }, { en: "Oceanography", hi: "समुद्र विज्ञान" }, { en: "Climatology", hi: "जलवायु विज्ञान" }, { en: "Soil Types", hi: "मिट्टी के प्रकार" }, { en: "Mineral Resources", hi: "खनिज संसाधन" }, { en: "Transport and Communication", hi: "परिवहन और संचार" }, { en: "Map Projections", hi: "मानचित्र प्रक्षेप" }, { en: "Demographics", hi: "जनसांख्यिकी" } ], "History": [ { en: "Ancient History", hi: "प्राचीन इतिहास" }, { en: "Medieval History", hi: "मध्यकालीन इतिहास" }, { en: "Modern World History", hi: "आधुनिक विश्व इतिहास" }, { en: "Industrial Revolution", hi: "औद्योगिक क्रांति" }, { en: "The Renaissance", hi: "पुनर्जागरण" }, { en: "The Reformation", hi: "सुधार" }, { en: "Ancient Egypt", hi: "प्राचीन मिस्र" }, { en: "Indus Valley Civilization", hi: "सिंधु घाटी सभ्यता" }, { en: "The Roman Empire", hi: "रोमन साम्राज्य" }, { en: "Independence Movements", hi: "स्वतंत्रता आंदोलन" }, { en: "Post-Colonial Era", hi: "उत्तर-औपनिवेशिक युग" } ], "GK": [ { en: "Current Affairs", hi: "सामयिकी (करंट अफेयर्स)" }, { en: "Sports & Games", hi: "खेल-कूद" }, { en: "Famous Inventions", hi: "प्रसिद्ध आविष्कार" }, { en: "Capitals & Currencies", hi: "राजधानियां और मुद्राएं" }, { en: "Space Exploration", hi: "अंतरिक्ष अन्वेषण" }, { en: "Nobel Prize Winners", hi: "नोबेल पुरस्कार विजेता" }, { en: "World Mythology", hi: "विश्व पौराणिक कथाएं" }, { en: "Global Organizations (UN, WHO)", hi: "वैश्विक संगठन (UN, WHO)" }, { en: "Famous Authors & Books", hi: "प्रसिद्ध लेखक और पुस्तकें" }, { en: "Indian Politics", hi: "भारतीय राजनीति" }, { en: "World History", hi: "विश्व इतिहास" }, { en: "Major Inventions", hi: "प्रमुख आविष्कार" }, { en: "Geography Records", hi: "भूगोल रिकॉर्ड" }, { en: "National Parks of India", hi: "भारत के राष्ट्रीय उद्यान" }, { en: "Nobel Laureates (Recent)", hi: "नोबेल पुरस्कार विजेता (नवीनतम)" }, { en: "Sports Terminology", hi: "खेल शब्दावली" } ] }; let chosenSubject = ""; let chosenTopic = ""; let topicLang = "en"; let timerInterval; let timeLeft = 60; let isAdaptive = false; let totalQuizCount = 5; let chunkSizes = []; let currentChunkIndex = 0; let questionsFetchedSoFar = 0; let engineDifficulty = 'Standard'; let globalSetupConfig = {}; document.getElementById('quizCount').addEventListener('input', (e) => { const val = parseInt(e.target.value) || 0; const adaptChk = document.getElementById('adaptiveDiff'); const lockMsg = document.getElementById('adaptiveLockMsg'); if (val < 5) { adaptChk.checked = false; adaptChk.disabled = true; lockMsg.style.display = 'block'; document.getElementById('adaptiveLabel').style.opacity = '0.5'; } else { adaptChk.disabled = false; adaptChk.checked = true; lockMsg.style.display = 'none'; document.getElementById('adaptiveLabel').style.opacity = '1'; } }); document.getElementById('quizLanguage').addEventListener('change', (e) => { topicLang = (e.target.value === 'Hindi') ? 'hi' : 'en'; document.getElementById('topicLangToggle').innerHTML = `<span style="font-size: 15px;">🌐</span> ${topicLang === 'en' ? 'English' : 'हिंदी'}`; if(chosenSubject) renderTopics(); }); const subjModal = document.getElementById('subjectModal'); document.getElementById('quizSubjectSelector').addEventListener('click', () => { subjModal.style.display = 'flex'; }); document.getElementById('closeSubjectModalBtn').addEventListener('click', () => { subjModal.style.display = 'none'; }); document.querySelectorAll('.main-subj').forEach(btn => { btn.addEventListener('click', (e) => { chosenSubject = e.target.innerText; const textEl = document.getElementById('selectedSubjectText'); textEl.innerText = chosenSubject; subjModal.style.display = 'none'; const langSelect = document.getElementById('quizLanguage'); const langLockMsg = document.getElementById('langLockMsg'); if (chosenSubject === "English Grammar") { langSelect.value = "English"; langSelect.style.pointerEvents = "none"; langSelect.style.opacity = "0.5"; langLockMsg.style.display = "block"; } else if (chosenSubject === "Hindi Grammar") { langSelect.value = "Hindi"; langSelect.style.pointerEvents = "none"; langSelect.style.opacity = "0.5"; langLockMsg.style.display = "block"; } else { langSelect.style.pointerEvents = "auto"; langSelect.style.opacity = "1"; langLockMsg.style.display = "none"; } topicLang = (langSelect.value === 'Hindi') ? 'hi' : 'en'; document.getElementById('topicLangToggle').innerHTML = `<span style="font-size: 15px;">🌐</span> ${topicLang === 'en' ? 'English' : 'हिंदी'}`; if (topicData[chosenSubject]) { document.getElementById('topicContainer').style.display = 'block'; chosenTopic = ""; document.getElementById('selectedTopicText').innerText = "Select Topic... (Or Leave Blank)"; renderTopics(); } else { document.getElementById('topicContainer').style.display = 'none'; chosenTopic = ""; } }); }); const topicModal = document.getElementById('topicModal'); document.getElementById('topicLangToggle').addEventListener('click', () => { topicLang = topicLang === 'en' ? 'hi' : 'en'; document.getElementById('topicLangToggle').innerHTML = `<span style="font-size: 15px;">🌐</span> ${topicLang === 'en' ? 'English' : 'हिंदी'}`; renderTopics(); if (chosenTopic && topicData[chosenSubject]) { const found = topicData[chosenSubject].find(t => t.en === chosenTopic || t.hi === chosenTopic); if(found) { chosenTopic = found[topicLang]; document.getElementById('selectedTopicText').innerText = chosenTopic; } } }); document.getElementById('quizTopicSelector').addEventListener('click', () => { if(topicData[chosenSubject]) topicModal.style.display = 'flex'; }); document.getElementById('closeTopicModalBtn').addEventListener('click', () => { topicModal.style.display = 'none'; }); function renderTopics() { const container = document.getElementById('topicListContainer'); container.innerHTML = ''; if(!topicData[chosenSubject]) return; topicData[chosenSubject].forEach(t => { const btn = document.createElement('button'); btn.className = 'subj-btn'; btn.innerText = t[topicLang]; btn.onclick = () => { chosenTopic = t[topicLang]; document.getElementById('selectedTopicText').innerText = chosenTopic; topicModal.style.display = 'none'; }; container.appendChild(btn); }); } let quizData = []; let currentQuestionIndex = 0; let userAnswers = []; let mediaRecorder; let audioChunks = []; let currentAudioUrl = null; let currentTranscript = ""; let isRecordingActive = false; let recognition = null; let streamReference = null; if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) { const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; recognition = new SpeechRecognition(); recognition.continuous = true; recognition.interimResults = true; } const setupEl = document.getElementById('quizSetup'), activeEl = document.getElementById('quizActive'), resultsEl = document.getElementById('quizResults'); const startBtn = document.getElementById('startQuizBtn'); const nextBtn = document.getElementById('nextBtn'); // 🛑 JSON REPAIR LOOP async function fixBrokenJson(brokenString, providerOverride) { console.warn("Attempting AI Self-Correction loop for invalid JSON..."); const prompt = `This JSON output is invalid. Fix the syntax errors and return ONLY the valid JSON array without any markdown formatting or conversational text.\n\nBroken JSON:\n${brokenString}`; const response = await fetch('/api/gemini-text', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ systemPrompt: "Return ONLY valid JSON array.", userPrompt: prompt, providerOverride: providerOverride, webSearchActive: false, useSearch: false }) }); const data = await response.json(); if(!data.text) throw new Error("Correction API returned empty text"); let rawText = data.text.replace(/```(?:json)?\n?/gi, '').replace(/```\n?/gi, '').trim(); const s = rawText.indexOf('['); const e = rawText.lastIndexOf(']'); if(s === -1 || e === -1) throw new Error("Correction failed to format array"); return JSON.parse(rawText.substring(s, e + 1)); } // 🛑 FETCH LOGIC FORCED TO API 1 ONLY async function fetchQuizChunk(chunkCount, grade, finalTopicStr, language, providerOverride, quizMode, difficulty) { let modeRule = ""; if (quizMode === "mokhik" || quizMode === "mixed") { modeRule = `8. NO "WHICH OF THE FOLLOWING" (CRITICAL): Because some questions will be answered VERBALLY without seeing options, YOU MUST NOT ask questions that require seeing a list. Ask direct, self-contained questions.`; } const prompt = `Create a quiz with exactly ${chunkCount} multiple choice questions for a Class ${grade} student on the subject/topic: "${finalTopicStr}". CRITICAL RULES: 1. DIFFICULTY SCALING: Target difficulty is ${difficulty.toUpperCase()}. 2. LANGUAGE: The ENTIRE quiz MUST be strictly in ${language.toUpperCase()}. 3. NO HINTS IN OPTIONS (CRITICAL): The 4 items in the "options" array MUST be identical in format. 4. ALL NUMBERS MUST be standard English Arabic numerals (0-9). 5. Use LaTeX for ALL math equations. Wrap inline math in $...$ and display math in $$...$$. 6. JSON ESCAPING (CRITICAL): Double-escape ALL LaTeX backslashes. Write \\\\frac instead of \\frac. 7. Return ONLY a valid JSON array. NO markdown code blocks. ${modeRule} Format exactly like this: [ { "question": "What is $\\\\frac{1}{2} + \\\\frac{1}{4}$?", "options": ["$\\\\frac{3}{4}$", "1", "0", "$\\\\frac{1}{8}$"], "correctOption": "$\\\\frac{3}{4}$", "explanation": "Because $\\\\frac{2}{4} + \\\\frac{1}{4} = \\\\frac{3}{4}$." } ]`; const response = await fetch('/api/gemini-text', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ systemPrompt: "You are a strict data-only API. Output nothing except the requested JSON array.", userPrompt: prompt, providerOverride: 'API 1', // 🚨 FORCE API 1 ALWAYS webSearchActive: false, // 🚨 STOPS TAVILY SEARCH useSearch: false // 🚨 EXTRA SAFETY }) }); const data = await response.json(); // 🚨 BETTER ERROR HANDLING TO CATCH CRASHES PROPERLY if (!response.ok) { let errMsg = "API Request Failed."; try { errMsg = data.error || data.message || errMsg; } catch(e){} throw new Error(errMsg); } if (!data.text) throw new Error("API returned an empty response text."); let rawText = data.text.replace(/```(?:json)?\n?/gi, '').replace(/```\n?/gi, '').trim(); let startIdx = rawText.indexOf('['); let endIdx = rawText.lastIndexOf(']'); if (startIdx === -1 || endIdx === -1) throw new Error("AI did not return the correct array format."); let cleanJsonString = rawText.substring(startIdx, endIdx + 1); let parsedArray; try { parsedArray = JSON.parse(cleanJsonString); } catch (err) { parsedArray = await fixBrokenJson(cleanJsonString, 'API 1'); } return parsedArray.map(item => ({ question: item.question || item.q || "Question text missing", options: item.options || item.choices || ["A", "B", "C", "D"], correctOption: item.correctOption || item.correct_option || item.answer || item.correctAnswer || item.correct || "", explanation: item.explanation || item.reason || item.reasoning || item.desc || "No explanation provided." })); } function calculateChunks(total) { let sizes = []; let rem = total; for(let i=4; i>1; i--) { let s = Math.floor(rem / i); sizes.push(s); rem -= s; } sizes.push(rem); return sizes; } startBtn.addEventListener('click', async () => { const grade = document.getElementById('quizClass').value; const language = document.getElementById('quizLanguage').value; const quizMode = document.getElementById('quizModeSelect').value; let count = parseInt(document.getElementById('quizCount').value); const isDivideMode = document.getElementById('divideMode').checked; if(!grade) { showToast("⚠️ Please select a Class/Grade."); return; } if(isNaN(count) || count < 1) count = 5; if(count > 25) count = 25; const fDock = document.getElementById('fontSizeDock'); if (fDock) fDock.style.display = 'none'; // Hide button while working startBtn.style.display = 'none'; let finalTopicStr = ""; let displayTitleStr = ""; if (!chosenSubject) { finalTopicStr = "Mixed topics across multiple random academic subjects"; displayTitleStr = "Mixed Subjects"; document.getElementById('quizTag').innerText = `Mixed Subjects • Class ${grade}`; } else if (!chosenTopic) { finalTopicStr = `A random mix of all topics within the subject: ${chosenSubject}`; displayTitleStr = `${chosenSubject} (Mixed Topics)`; document.getElementById('quizTag').innerText = `${chosenSubject} (Mixed) • Class ${grade}`; } else { finalTopicStr = `${chosenSubject} - ${chosenTopic}`; displayTitleStr = `${chosenSubject} - ${chosenTopic}`; document.getElementById('quizTag').innerText = `${finalTopicStr} • Class ${grade}`; } globalSetupConfig = { grade, language, quizMode, finalTopicStr, modelPriorityStr: 'API 1' }; isAdaptive = document.getElementById('adaptiveDiff').checked; totalQuizCount = count; if (isAdaptive && count >= 5) { chunkSizes = calculateChunks(count); showGlobalLoader("Booting Adaptive Engine..."); } else { isAdaptive = false; chunkSizes = [count]; showGlobalLoader("Building your smart quiz..."); } currentChunkIndex = 0; questionsFetchedSoFar = 0; engineDifficulty = 'Standard'; quizData = []; userAnswers = []; currentQuestionIndex = 0; try { let allFetchedQuestions = []; if (!isAdaptive && isDivideMode) { showGlobalLoader("Dividing workload (API 1 Only)..."); // 🚨 BUG FIXED let chunk1 = Math.ceil(count / 3); let chunk2 = Math.ceil((count - chunk1) / 2); let chunk3 = count - chunk1 - chunk2; const promises = []; // 🚨 ABSOLUTELY NO LOAD BALANCING. EVERY LOAD TO API 1. if (chunk1 > 0) promises.push(fetchQuizChunk(chunk1, grade, finalTopicStr, language, 'API 1', quizMode, engineDifficulty)); if (chunk2 > 0) promises.push(fetchQuizChunk(chunk2, grade, finalTopicStr, language, 'API 1', quizMode, engineDifficulty)); if (chunk3 > 0) promises.push(fetchQuizChunk(chunk3, grade, finalTopicStr, language, 'API 1', quizMode, engineDifficulty)); const results = await Promise.all(promises); allFetchedQuestions = results.flat(); questionsFetchedSoFar = allFetchedQuestions.length; } else { if(!isAdaptive) showGlobalLoader("Connecting to API 1 AI Engine..."); // 🚨 BUG FIXED allFetchedQuestions = await fetchQuizChunk(chunkSizes[0], grade, finalTopicStr, language, 'API 1', quizMode, engineDifficulty); questionsFetchedSoFar = chunkSizes[0]; } if(!allFetchedQuestions || allFetchedQuestions.length === 0) throw new Error("AI returned empty quiz array."); quizData = allFetchedQuestions.map(q => { let isVerbal = false; if(quizMode === 'mokhik') isVerbal = true; if(quizMode === 'mixed') isVerbal = Math.random() > 0.5; return { ...q, isVerbal: isVerbal }; }); window.activeQuizTitle = displayTitleStr; updateDifficultyBadge(); hideGlobalLoader(); setupEl.classList.remove('active'); activeEl.classList.add('active'); renderMiniMap(); renderQuestion(); } catch(err) { console.error("Quiz Generation Failed:", err); hideGlobalLoader(); // 🚨 FIX: SPIT OUT THE EXACT ERROR MESSAGE IN THE TOAST showToast("⚠️ ERROR: " + err.message); // 🚨 FIX: BRING BUTTON BACK SO YOU AREN'T STUCK startBtn.style.display = 'block'; if (fDock) fDock.style.display = 'flex'; } }); function updateDifficultyBadge() { const b = document.getElementById('difficultyBadge'); b.innerText = `Engine: ${engineDifficulty}`; b.style.color = engineDifficulty === 'Hard' ? '#ef4444' : (engineDifficulty === 'Easy' ? '#22c55e' : '#cbd5e1'); } // FEATURE: Mini-Map Update function renderMiniMap() { const map = document.getElementById('miniMap'); map.innerHTML = ''; for(let i=0; i<totalQuizCount; i++) { const dot = document.createElement('div'); dot.className = 'map-dot'; if (i < currentQuestionIndex) { if (userAnswers[i] && userAnswers[i] !== "Skipped") dot.classList.add('answered'); else dot.classList.add('skipped'); } else if (i === currentQuestionIndex) { dot.classList.add('current'); } map.appendChild(dot); } } function startTimer() { clearInterval(timerInterval); const timerContainer = document.getElementById('timerContainer'); const enableTimer = document.getElementById('enableTimer').checked; const vignette = document.getElementById('red-vignette'); vignette.classList.remove('active'); if (!enableTimer) { timerContainer.style.display = 'none'; return; } timerContainer.style.display = 'flex'; timeLeft = (chosenSubject === "Math") ? 120 : 60; const timerText = document.getElementById('timerText'); timerContainer.classList.remove('hurry'); timerText.innerText = timeLeft + "s"; timerInterval = setInterval(() => { timeLeft--; timerText.innerText = timeLeft + "s"; if (timeLeft === 5) vibe([50, 100, 50]); if(timeLeft <= 10 && timeLeft > 5) { timerContainer.classList.add('hurry'); vignette.classList.remove('active'); } else if (timeLeft <= 5 && timeLeft > 0) { timerContainer.classList.add('hurry'); vignette.classList.add('active'); } else { vignette.classList.remove('active'); } if (timeLeft <= 0) { clearInterval(timerInterval); vignette.classList.remove('active'); if (!userAnswers[currentQuestionIndex]) { userAnswers[currentQuestionIndex] = "Skipped"; } processNextStep(); } }, 1000); } function renderQuestion() { startTimer(); currentAudioUrl = null; currentTranscript = ""; document.getElementById('speakTranscript').value = ""; document.getElementById('verbalRecordedPreview').innerText = "No answer recorded yet."; renderMiniMap(); if('speechSynthesis' in window) speechSynthesis.cancel(); const qData = quizData[currentQuestionIndex]; const progressPct = ((currentQuestionIndex) / totalQuizCount) * 100; document.getElementById('quizProgressBar').style.width = progressPct + '%'; document.getElementById('quizProgress').innerText = `Question ${currentQuestionIndex + 1} of ${totalQuizCount}`; document.getElementById('questionText').innerHTML = String(qData.question).replace(/</g, "&lt;").replace(/>/g, "&gt;"); const optsContainer = document.getElementById('optionsContainer'); const verbalActionContainer = document.getElementById('verbalActionContainer'); const verbalBadge = document.getElementById('verbalModeBadge'); optsContainer.innerHTML = ''; if (qData.isVerbal) { optsContainer.style.display = 'none'; verbalActionContainer.style.display = 'block'; verbalBadge.style.display = 'block'; } else { optsContainer.style.display = 'flex'; verbalActionContainer.style.display = 'none'; verbalBadge.style.display = 'none'; const prevAns = userAnswers[currentQuestionIndex]; qData.options.forEach((opt, idx) => { const btn = document.createElement('button'); btn.className = 'option-btn'; btn.innerHTML = `<span class="shortcut-badge">${idx+1}</span> ` + String(opt).replace(/</g, "&lt;").replace(/>/g, "&gt;"); if (prevAns && opt === prevAns && prevAns !== "Skipped") btn.classList.add('selected'); btn.onclick = () => { vibe(50); userAnswers[currentQuestionIndex] = opt; Array.from(optsContainer.children).forEach(c => c.classList.remove('selected')); btn.classList.add('selected'); }; optsContainer.appendChild(btn); }); } nextBtn.innerText = currentQuestionIndex === totalQuizCount - 1 ? 'Finish 🏆' : 'Next ➡️'; if (window.MathJax) { MathJax.typesetPromise([document.getElementById('questionText'), document.getElementById('optionsContainer')]); } } // FEATURE 1: Text To Speech function speakQuestion() { if('speechSynthesis' in window) { speechSynthesis.cancel(); const qText = quizData[currentQuestionIndex].question.replace(/<[^>]*>?/gm, ''); const utterance = new SpeechSynthesisUtterance(qText); const lang = document.getElementById('quizLanguage').value; utterance.lang = lang === 'Hindi' ? 'hi-IN' : 'en-US'; utterance.rate = 0.9; speechSynthesis.speak(utterance); } else { showToast("TTS not supported in this browser."); } } // FEATURE 2: Focus Mode (No black background, just Zen nav) function toggleFocusMode() { document.body.classList.toggle('zen-focus-active'); const btn = document.getElementById('focusBtn'); if (document.body.classList.contains('zen-focus-active')) { btn.innerText = '🔆 Unfocus'; btn.style.color = '#22c55e'; showToast("Focus Mode Activated"); } else { btn.innerText = '🎯 Focus'; btn.style.color = 'white'; } } function openSpeakGui() { document.getElementById('speakModal').style.display = 'flex'; } function closeSpeakGui() { document.getElementById('speakModal').style.display = 'none'; } async function startRecording() { if(isRecordingActive) return; isRecordingActive = true; const btn = document.getElementById('speakMicBtn'); btn.classList.add('recording'); document.getElementById('speakStatus').innerText = "Listening... Speak your answer"; document.getElementById('speakTranscript').value = ""; currentTranscript = ""; try { streamReference = await navigator.mediaDevices.getUserMedia({ audio: true }); mediaRecorder = new MediaRecorder(streamReference); audioChunks = []; mediaRecorder.ondataavailable = e => { if (e.data.size > 0) audioChunks.push(e.data); }; mediaRecorder.onstop = () => { currentAudioUrl = URL.createObjectURL(new Blob(audioChunks, { type: 'audio/webm' })); }; mediaRecorder.start(); if (recognition) { recognition.lang = document.getElementById('quizLanguage').value === 'Hindi' ? 'hi-IN' : 'en-US'; recognition.start(); recognition.onresult = (e) => { let interimTranscript = ''; for (let i = e.resultIndex; i < e.results.length; ++i) { if (e.results[i].isFinal) currentTranscript += e.results[i][0].transcript + " "; else interimTranscript += e.results[i][0].transcript; } document.getElementById('speakTranscript').value = currentTranscript + interimTranscript; }; } } catch (e) { console.error(e); showToast("⚠️ Microphone access denied or error!"); stopRecording(); } } function stopRecording() { if(!isRecordingActive) return; isRecordingActive = false; document.getElementById('speakMicBtn').classList.remove('recording'); document.getElementById('speakStatus').innerText = "Recording stopped. You can edit the text before saving."; try { if(mediaRecorder && mediaRecorder.state !== 'inactive') mediaRecorder.stop(); if(streamReference) streamReference.getTracks().forEach(track => track.stop()); if(recognition) recognition.stop(); } catch(err) { console.error("Cleanup error", err); } } function clearRecording() { currentAudioUrl = null; currentTranscript = ""; document.getElementById('speakTranscript').value = ""; document.getElementById('speakStatus').innerText = "Hold to speak or type below..."; } function saveSpeakAnswer() { let finalTxt = document.getElementById('speakTranscript').value.trim(); if(finalTxt === "" && !currentAudioUrl) return showToast("⚠️ Please record or type an answer first!"); if (finalTxt === "") finalTxt = "Audio Only"; userAnswers[currentQuestionIndex] = { isVerbal: true, text: finalTxt, audioUrl: currentAudioUrl }; document.getElementById('verbalRecordedPreview').innerText = `🎙️ Saved: "${finalTxt}"`; closeSpeakGui(); showToast("✅ Answer Saved!"); } function isLenientMatch(userText, correctText) { if(!userText || userText === "Audio Only") return false; let u = userText.toLowerCase().trim(); let c = correctText.toLowerCase().trim(); if(u === c || u.includes(c) || c.includes(u)) return true; let cWords = c.split(' ').filter(w => w.length > 2); let uWords = u.split(' '); let matches = 0; cWords.forEach(cw => { if(uWords.some(uw => uw.includes(cw) || cw.includes(uw))) matches++; }); return cWords.length > 0 && (matches / cWords.length) >= 0.4; } document.getElementById('skipBtn').addEventListener('click', () => { userAnswers[currentQuestionIndex] = "Skipped"; processNextStep(); }); document.getElementById('nextBtn').addEventListener('click', () => { const qData = quizData[currentQuestionIndex]; if (qData.isVerbal && (!userAnswers[currentQuestionIndex] || !userAnswers[currentQuestionIndex].text)) { return showToast("⚠️ Please open the GUI and answer first!"); } if (!qData.isVerbal && !userAnswers[currentQuestionIndex]) { return showToast("⚠️ Please select an answer first! Wait for timer to skip."); } processNextStep(); }); async function processNextStep() { clearInterval(timerInterval); document.getElementById('red-vignette').classList.remove('active'); if('speechSynthesis' in window) speechSynthesis.cancel(); if (isAdaptive && (currentQuestionIndex + 1 === questionsFetchedSoFar) && (questionsFetchedSoFar < totalQuizCount)) { await handleAdaptiveTransition(); return; } currentQuestionIndex++; if (currentQuestionIndex >= totalQuizCount) { finishQuiz(); } else { document.getElementById('quizPageContainer').style.opacity = '0.3'; showGlobalLoader("Loading Question..."); // 🚨 BUG FIXED setTimeout(() => { hideGlobalLoader(); document.getElementById('quizPageContainer').style.opacity = '1'; renderQuestion(); }, 500); } } async function handleAdaptiveTransition() { const loader = document.getElementById('adaptiveLoader'); loader.style.display = 'flex'; const chunkStart = questionsFetchedSoFar - chunkSizes[currentChunkIndex]; let chunkCorrect = 0; for (let i = chunkStart; i < questionsFetchedSoFar; i++) { let ans = userAnswers[i]; let isC = false; if(ans && ans !== "Skipped") { if(quizData[i].isVerbal) isC = isLenientMatch(ans.text, quizData[i].correctOption); else isC = (ans.trim() === quizData[i].correctOption.trim()); } if(isC) chunkCorrect++; } const pct = chunkCorrect / chunkSizes[currentChunkIndex]; if (pct >= 0.8) { engineDifficulty = 'Hard'; } else if (pct <= 0.2) { engineDifficulty = 'Easy'; } else { engineDifficulty = 'Standard'; } updateDifficultyBadge(); currentChunkIndex++; const nextSize = chunkSizes[currentChunkIndex]; try { // 🚨 FORCED API 1 ONLY let nextQuestions = await fetchQuizChunk(nextSize, globalSetupConfig.grade, globalSetupConfig.finalTopicStr, globalSetupConfig.language, 'API 1', globalSetupConfig.quizMode, engineDifficulty); nextQuestions = nextQuestions.map(q => { let isVerbal = false; if(globalSetupConfig.quizMode === 'mokhik') isVerbal = true; if(globalSetupConfig.quizMode === 'mixed') isVerbal = Math.random() > 0.5; return { ...q, isVerbal: isVerbal }; }); quizData = quizData.concat(nextQuestions); questionsFetchedSoFar += nextSize; loader.style.display = 'none'; currentQuestionIndex++; renderQuestion(); } catch(e) { console.error(e); showToast("⚠️ Chunk Error: " + e.message); loader.style.display = 'none'; totalQuizCount = quizData.length; finishQuiz(); } } function finishQuiz() { activeEl.classList.remove('active'); resultsEl.classList.add('active'); document.body.classList.remove('zen-focus-active'); document.getElementById('red-vignette').classList.remove('active'); if('speechSynthesis' in window) speechSynthesis.cancel(); const fDock = document.getElementById('fontSizeDock'); if (fDock) fDock.style.display = 'flex'; if(typeof confetti === 'function') { const duration = 3000; const end = Date.now() + duration; (function frame() { confetti({ particleCount: 4, angle: 60, spread: 55, origin: { x: 0 }, colors: ['#a855f7', '#38bdf8', '#22c55e', '#ef4444', '#f59e0b'] }); confetti({ particleCount: 4, angle: 120, spread: 55, origin: { x: 1 }, colors: ['#a855f7', '#38bdf8', '#22c55e', '#ef4444', '#f59e0b'] }); if (Date.now() < end) requestAnimationFrame(frame); }()); } let correctCount = 0; let reviewHtml = ''; quizData.forEach((q, index) => { const userAns = userAnswers[index] || "Skipped"; let isCorrect = false; let statusIcon = '❌'; let colorClass = '#ef4444'; let displayAns = ""; let audioHtml = ""; if (userAns === "Skipped") { displayAns = "- (Skipped / Time Out)"; colorClass = '#f59e0b'; statusIcon = '⏳'; } else if (q.isVerbal) { isCorrect = isLenientMatch(userAns.text, q.correctOption); if (isCorrect) { correctCount++; statusIcon = '✅'; colorClass = '#22c55e'; } displayAns = `🎙️ "${userAns.text}"`; if (userAns.audioUrl) { audioHtml = `<div style="margin-top:8px;"><audio controls src="${userAns.audioUrl}" style="height:35px; width:100%; border-radius:30px;"></audio></div>`; } } else { isCorrect = String(userAns).trim() === String(q.correctOption).trim(); if (isCorrect) { correctCount++; statusIcon = '✅'; colorClass = '#22c55e'; } displayAns = String(userAns).replace(/</g, "&lt;").replace(/>/g, "&gt;"); } const safeQ = String(q.question).replace(/</g, "&lt;").replace(/>/g, "&gt;"); const safeC = String(q.correctOption).replace(/</g, "&lt;").replace(/>/g, "&gt;"); const safeE = String(q.explanation).replace(/</g, "&lt;").replace(/>/g, "&gt;"); reviewHtml += ` <div class="result-card"> <div style="font-weight: 700; font-size: 15px; margin-bottom: 10px; color: white;">${index + 1}. ${safeQ}</div> <div style="font-size: 13px; margin-bottom: 5px;"> <span style="color: #94a3b8;">Your Answer:</span> <span style="color: ${colorClass}; font-weight: 600;">${statusIcon} ${displayAns}</span> </div> ${audioHtml} <div style="font-size: 13px; margin-top: 10px; margin-bottom: 10px;"> <span style="color: #94a3b8;">Correct Answer:</span> <span style="color: #22c55e; font-weight: 600;">${safeC}</span> </div> <div class="exp-preview" style="margin-top: 15px;"> <button onclick="this.nextElementSibling.style.display = this.nextElementSibling.style.display === 'none' ? 'block' : 'none'; this.innerHTML = this.nextElementSibling.style.display === 'none' ? '📖 View Detailed Explanation ⬇️' : '📖 Hide Explanation ⬆️';" style="background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); color: #38bdf8; padding: 10px 15px; border-radius: 8px; cursor: pointer; font-size: 13px; font-weight: bold; width: 100%; text-align: center; transition: 0.2s;">📖 View Detailed Explanation ⬇️</button> <div style="display: none; font-size: 14px; color: #ffffff; background: rgba(0,0,0,0.3); padding: 15px; border-radius: 8px; border-left: 4px solid #a855f7; margin-top: 8px; font-weight: 500; border: 1px solid rgba(255,255,255,0.05);"> <div style="margin-bottom: 10px; color:#cbd5e1; border-bottom: 1px dashed rgba(255,255,255,0.1); padding-bottom: 8px;"><b>Question:</b> ${safeQ}</div> <div style="margin-bottom: 10px; color:#22c55e;"><b>Correct Logic:</b> ${safeC}</div> <div style="color: white; line-height: 1.5;"><b>Detailed Explanation:</b> <br>${safeE}</div> </div> </div> </div>`; }); const grade = document.getElementById('quizClass').value; const total = totalQuizCount; const percentage = total > 0 ? Math.round((correctCount / total) * 100) : 0; let perfMsg = ""; let perfColor = ""; if (percentage >= 90) { perfMsg = "Outstanding! You have mastered this topic! 🌟"; perfColor = "#22c55e"; } else if (percentage >= 70) { perfMsg = "Great job! Keep up the good work! 👏"; perfColor = "#38bdf8"; } else if (percentage >= 40) { perfMsg = "Good effort, but you need to study more to master this. 📚"; perfColor = "#f59e0b"; } else { perfMsg = "Needs improvement. Please review the concepts and try again. 📖"; perfColor = "#ef4444"; } // FEATURE 4: Animate Donut Chart const donut = document.getElementById('scoreDonut'); const dText = document.getElementById('donutText'); donut.style.setProperty('--pct', '0%'); dText.innerText = "0%"; setTimeout(() => { donut.style.setProperty('--pct', percentage + '%'); dText.innerText = percentage + "%"; donut.style.background = `conic-gradient(${perfColor} var(--pct), rgba(0,0,0,0.3) 0)`; }, 500); document.getElementById('performanceMessage').innerHTML = `<span style="color: ${perfColor};">${perfMsg}</span>`; document.getElementById('resultSubtext').innerText = window.activeQuizTitle; document.getElementById('statCorrect').innerText = correctCount; document.getElementById('statWrong').innerText = total - correctCount; document.getElementById('statTotal').innerText = total; document.getElementById('reviewContainer').innerHTML = reviewHtml; if (window.MathJax) MathJax.typesetPromise([document.getElementById('reviewContainer')]); saveQuizToHistory(window.activeQuizTitle, grade, correctCount, total, reviewHtml); } // FEATURE 5: Export Quiz JSON function exportQuizJSON() { const payload = { title: window.activeQuizTitle, date: new Date().toISOString(), questions: quizData, userAnswers: userAnswers }; const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(payload, null, 2)); const a = document.createElement('a'); a.href = dataStr; a.download = `AI_Quiz_${window.activeQuizTitle.replace(/\s+/g, '_')}.json`; document.body.appendChild(a); a.click(); document.body.removeChild(a); showToast("✅ JSON Data Exported"); } // --- KEYBOARD SHORTCUTS --- document.addEventListener('keydown', (e) => { if(document.getElementById('quizActive').classList.contains('active')) { if (['1','2','3','4'].includes(e.key)) { const idx = parseInt(e.key) - 1; const opts = document.querySelectorAll('.option-btn'); if (opts[idx]) opts[idx].click(); } else if (e.key === 'Enter') { if (document.getElementById('speakModal').style.display === 'flex') saveSpeakAnswer(); else document.getElementById('nextBtn').click(); } else if (e.code === 'Space') { const isVerbalActive = document.getElementById('verbalActionContainer').style.display === 'block'; const isModalOpen = document.getElementById('speakModal').style.display === 'flex'; if (isVerbalActive && !isModalOpen) { e.preventDefault(); openSpeakGui(); startRecording(); } else if (isModalOpen && !isRecordingActive) { e.preventDefault(); startRecording(); } } } }); document.addEventListener('keyup', (e) => { if (e.code === 'Space' && document.getElementById('speakModal').style.display === 'flex') { stopRecording(); } }); function saveQuizToHistory(subject, grade, correct, total, htmlDetails) { if (typeof localforage !== 'undefined') { let sessionId = Date.now(); let percentage = total > 0 ? Math.round((correct / total) * 100) : 0; let formattedAnswer = `<div style="font-size:16px; font-weight:bold; color:#22c55e;">Score: ${correct} out of ${total} (${percentage}%)</div><hr style="border-color:rgba(255,255,255,0.1); margin:10px 0;">${htmlDetails}`; let histItem = { id: sessionId, type: 'quiz', title: `${subject} Quiz (${correct}/${total})`, interactions: [{ question: `Take a ${total}-question quiz on ${subject} for Class ${grade}.`, answer: formattedAnswer, provider: "AI Quiz Engine" }], provider: "AI Quiz Engine", question: `Take a ${total}-question quiz on ${subject} for Class ${grade}.`, answer: formattedAnswer }; localforage.getItem('aiHistory').then(function(history) { history = history || []; history.unshift(histItem); localforage.setItem('aiHistory', history); console.log("Quiz saved to history successfully."); }).catch(function(err) { console.error("Failed to save quiz history", err); }); } } function downloadPDF() { const modal = document.getElementById('pdfModal'); const spinner = document.getElementById('pdfModalSpinner'); const text = document.getElementById('pdfModalText'); const manualBtn = document.getElementById('pdfManualBtn'); const closeBtn = document.getElementById('pdfCloseBtn'); modal.style.display = 'flex'; spinner.style.display = 'block'; text.innerText = "Creating your PDF..."; text.style.color = "white"; manualBtn.style.display = 'none'; closeBtn.style.display = 'none'; const element = document.getElementById('pdfExportArea'); const filenameSafe = window.activeQuizTitle ? window.activeQuizTitle.replace(/\s+/g, '_') : 'Mixed_Quiz'; window.scrollTo(0, 0); element.style.backgroundColor = "#0f172a"; element.style.color = "#ffffff"; setTimeout(() => { html2pdf().set({ margin: 10, filename: `AI_Quiz_Result_${filenameSafe}.pdf`, image: { type: 'jpeg', quality: 0.98 }, html2canvas: { scale: 2, useCORS: true, backgroundColor: '#0f172a', letterRendering: true }, jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' } }).from(element).output('blob').then((blob) => { const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `AI_Quiz_Result_${filenameSafe}.pdf`; document.body.appendChild(a); a.click(); document.body.removeChild(a); spinner.style.display = 'none'; text.innerText = "✅ PDF Ready & Downloading!"; text.style.color = "#22c55e"; manualBtn.style.display = 'block'; closeBtn.style.display = 'block'; manualBtn.onclick = () => { const manualA = document.createElement('a'); manualA.href = url; manualA.download = `AI_Quiz_Result_${filenameSafe}.pdf`; document.body.appendChild(manualA); manualA.click(); document.body.removeChild(manualA); showToast("✅ Manual Download Triggered"); }; }).catch((err) => { spinner.style.display = 'none'; text.innerText = "❌ Failed to generate PDF."; text.style.color = "#ef4444"; closeBtn.style.display = 'block'; }); }, 300); } document.addEventListener("DOMContentLoaded", () => { checkForHistoryRestore(); }); function checkForHistoryRestore() { const urlParams = new URLSearchParams(window.location.search); const restoreId = urlParams.get('restore'); if (restoreId) { try { let history = []; try { history = JSON.parse(localStorage.getItem('aiHistory') || '[]'); } catch(e) {} if (typeof localforage !== 'undefined') { localforage.getItem('aiHistory').then(data => { let merged = data || history; let item = merged.find(i => i.id == restoreId); if (item && item.interactions && item.interactions.length > 0) { executeQuizRestoration(item.interactions[0].answer, item.title || "Restored Quiz Review"); } }); } else { let item = history.find(i => i.id == restoreId); if (item && item.interactions && item.interactions.length > 0) { executeQuizRestoration(item.interactions[0].answer, item.title || "Restored Quiz Review"); } } } catch (err) { console.error("Quiz session restoration failed:", err); } } } function executeQuizRestoration(savedHtmlTable, quizTitle) { const setupView = document.getElementById('quizSetup'); const activeView = document.getElementById('quizActive'); const resultsView = document.getElementById('quizResults'); if (setupView) setupView.classList.remove('active'); if (activeView) activeView.classList.remove('active'); if (resultsView) resultsView.classList.add('active'); const reviewContainer = document.getElementById('reviewContainer'); const subtextHeader = document.getElementById('resultSubtext'); if (reviewContainer) { reviewContainer.innerHTML = savedHtmlTable; if (window.MathJax) { MathJax.typesetPromise([reviewContainer]).catch(e => console.log("MathJax error:", e)); } } if (subtextHeader) { subtextHeader.innerText = quizTitle; } let scoreMatch = savedHtmlTable.match(/Score:\s*(\d+)\s*out\s*of\s*(\d+)/i); if (scoreMatch) { const correctCount = parseInt(scoreMatch[1]); const totalCount = parseInt(scoreMatch[2]); const elCorrect = document.getElementById('statCorrect'); const elTotal = document.getElementById('statTotal'); const elWrong = document.getElementById('statWrong'); if (elCorrect) elCorrect.innerText = correctCount; if (elTotal) elTotal.innerText = totalCount; if (elWrong) elWrong.innerText = totalCount - correctCount; const percentage = totalCount > 0 ? Math.round((correctCount / totalCount) * 100) : 0; let perfMsg = ""; let perfColor = ""; if (percentage >= 90) { perfMsg = "Outstanding! You have mastered this topic! 🌟"; perfColor = "#22c55e"; } else if (percentage >= 70) { perfMsg = "Great job! Keep up the good work! 👏"; perfColor = "#38bdf8"; } else if (percentage >= 40) { perfMsg = "Good effort, but you need to study more to master this. 📚"; perfColor = "#f59e0b"; } else { perfMsg = "Needs improvement. Please review the concepts and try again. 📖"; perfColor = "#ef4444"; } let pContainer = document.getElementById('performanceMessage'); if(pContainer) pContainer.innerHTML = `<span style="color: ${perfColor};">${perfMsg}</span>`; // FEATURE 4: Restored Donut Chart const donut = document.getElementById('scoreDonut'); const dText = document.getElementById('donutText'); if(donut && dText) { setTimeout(() => { donut.style.setProperty('--pct', percentage + '%'); dText.innerText = percentage + "%"; donut.style.background = `conic-gradient(${perfColor} var(--pct), rgba(0,0,0,0.3) 0)`; }, 100); } } if (typeof showToast === "function") { showToast("🔄 Quiz Session Restored"); } } </script> </body> </html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>AI Pro Suite - Smart Quiz</title>
<link rel="manifest" href="/manifest.json">
<meta name="theme-color" content="#0f172a">
<!-- BRAND NEW MONOGLYPHIC-STYLE FONTS -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;600;700&family=JetBrains+Mono:wght@500;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/polyfill/v3/polyfill.min.js?version=4.8.0"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.6.0/dist/confetti.browser.min.js"></script>
<script>
MathJax = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']],
displayMath: [['$$', '$$'], ['\\[', '\\]']]
},
startup: { typeset: false }
};
</script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<style>
/* APPLYING THE NEW MONOGLYPHIC-STYLE FONTS GLOBALLY */
body, input, select, textarea, button, .option-btn {
font-family: 'Space Grotesk', sans-serif !important;
}
h1, h2, h3, .cardTitle, .appTitle, .quiz-btn {
font-family: 'Space Grotesk', sans-serif !important;
font-weight: 700 !important;
letter-spacing: -0.5px;
}
.num, .shortcut-badge, .timer-box {
font-family: 'JetBrains Mono', monospace !important;
}
.quiz-page-container { width: 100% !important; max-width: 600px !important; margin: 70px auto 0 auto !important; display: flex !important; flex-direction: column !important; padding: 30px 20px 150px 20px !important; transition: opacity 0.3s; }
.quiz-card { width: 100% !important; flex-shrink: 0 !important; }
.quiz-setup, .quiz-active, .quiz-results { display: none !important; animation: fadeIn 0.4s ease; }
.quiz-setup.active, .quiz-active.active, .quiz-results.active { display: flex !important; flex-direction: column !important; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
.quiz-btn { background: linear-gradient(135deg, #a855f7, #7e22ce); color: white; padding: 16px; border-radius: 30px; font-size: 19px; width: 100%; border: none; cursor: pointer; box-shadow: 0 10px 30px rgba(168,85,247,0.4); margin-top: 25px; transition: 0.2s; text-align: center; }
.quiz-btn:active { transform: scale(0.97); }
input[type="number"].standard, select.standard { width: 100%; padding: 15px 20px; background: rgba(15, 23, 42, 0.6); border: 1px solid rgba(255, 255, 255, 0.1); color: #f8fafc; border-radius: 12px; outline: none; font-size: 15px; box-sizing: border-box; appearance: none; font-weight: 600; }
input[type="number"].standard:focus, select.standard:focus { border-color: #c084fc; background: rgba(15, 23, 42, 0.9); }
.option-btn { background: rgba(255, 255, 255, 0.05); border: 2px solid rgba(255, 255, 255, 0.1); color: #f8fafc; padding: 16px; border-radius: 12px; font-size: 16px; font-weight: 600; text-align: left; cursor: pointer; transition: all 0.2s; margin-bottom: 12px; word-wrap: break-word; }
.option-btn:hover { background: rgba(255, 255, 255, 0.1); border-color: #38bdf8; }
.option-btn.selected { background: rgba(56, 189, 248, 0.2) !important; border-color: #38bdf8 !important; box-shadow: 0 0 15px rgba(56, 189, 248, 0.3) !important; }
.stat-box { background: rgba(0,0,0,0.3); border: 1px solid rgba(255,255,255,0.1); padding: 15px 10px; border-radius: 15px; text-align: center; flex: 1 1 28%; min-width: 80px; }
.stat-box .num { font-size: 32px; font-weight: 900; }
.result-card { background: rgba(0,0,0,0.2); border: 1px solid rgba(255,255,255,0.05); border-radius: 12px; padding: 20px; margin-bottom: 15px; text-align: left; word-wrap: break-word; }
select.standard option { background: #0f172a; color: white; }
.subj-btn { background: rgba(255, 255, 255, 0.05); border: 1px solid rgba(255, 255, 255, 0.1); color: #f8fafc; padding: 15px; border-radius: 12px; font-size: 16px; text-align: center; font-weight: 600; cursor: pointer; transition: all 0.2s; flex-shrink: 0; }
.subj-btn:hover { background: rgba(168, 85, 247, 0.2); border-color: #a855f7; }
.subj-scroll-container { display: flex; flex-direction: column; gap: 10px; max-height: 60vh; overflow-y: auto; padding-right: 10px; -webkit-overflow-scrolling: touch; }
.subj-scroll-container::-webkit-scrollbar { width: 4px; }
.subj-scroll-container::-webkit-scrollbar-thumb { background: rgba(168, 85, 247, 0.5); border-radius: 10px; }
/* Timer UI */
.timer-box { background: rgba(239, 68, 68, 0.15); border: 1px solid rgba(239, 68, 68, 0.4); color: #ef4444; padding: 5px 12px; border-radius: 20px; font-weight: 800; font-size: 15px; display: flex; align-items: center; gap: 6px; transition: 0.3s; }
.timer-box.hurry { animation: pulseRedText 1s infinite; }
@keyframes pulseRedText { 0% { background: rgba(239, 68, 68, 0.15); } 50% { background: rgba(239, 68, 68, 0.4); color: #fff; } 100% { background: rgba(239, 68, 68, 0.15); } }
/* Mic Buttons */
.mic-btn-main { background: rgba(239, 68, 68, 0.1); border: 2px solid #ef4444; color: #ef4444; padding: 20px; border-radius: 50%; font-size: 24px; cursor: pointer; transition: 0.3s; width: 80px; height: 80px; display: flex; align-items: center; justify-content: center; margin: 15px auto; box-shadow: 0 0 15px rgba(239,68,68,0.2); }
.mic-btn-main.recording { background: #ef4444; color: white; animation: pulseRedText 1s infinite; box-shadow: 0 0 30px rgba(239, 68, 68, 0.6); }
/* YOUTUBE APP ANIMATED LOADER */
#global-loader { position: fixed; top: -100px; left: 50%; transform: translateX(-50%); background: linear-gradient(135deg, #ff0844 0%, #ffb199 100%); color: white; padding: 12px 30px; border-radius: 20px; font-weight: 700; font-size: 16px; box-shadow: 0 10px 30px rgba(255,8,68,0.5); z-index: 10000; transition: top 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); display: flex; flex-direction: column; align-items: center; pointer-events: none;}
#global-loader.active { top: 30px; }
.spinner { width: 22px; height: 22px; border: 3px solid rgba(255,255,255,0.3); border-radius: 50%; border-top-color: white; animation: spin 1s ease-in-out infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
.indeterminate-loader-bar { width: 100%; min-width: 150px; height: 4px; background: rgba(255,255,255,0.2); border-radius: 2px; overflow: hidden; position: relative; margin-top: 8px; }
.indeterminate-loader-progress { position: absolute; top: 0; left: -50%; width: 50%; height: 100%; background: white; border-radius: 2px; animation: loaderSweep 1.2s infinite ease-in-out; box-shadow: 0 0 8px white; }
@keyframes loaderSweep { 0% { left: -50%; } 100% { left: 100%; } }
/* DANGER TIMER VIGNETTE (< 5s) */
#red-vignette { position: fixed; inset: 0; pointer-events: none; z-index: 9998; box-shadow: inset 0 0 0px rgba(239, 68, 68, 0); transition: box-shadow 0.3s ease; }
#red-vignette.active { animation: dangerFlash 0.8s infinite; }
@keyframes dangerFlash {
0% { box-shadow: inset 0 0 0px rgba(239, 68, 68, 0); }
50% { box-shadow: inset 0 0 80px rgba(239, 68, 68, 0.7), inset 0 0 20px rgba(239, 68, 68, 0.9); }
100% { box-shadow: inset 0 0 0px rgba(239, 68, 68, 0); }
}