Aichatbot12321 commited on
Commit
f9521a2
·
verified ·
1 Parent(s): 2b53d6d

Update books.html

Browse files
Files changed (1) hide show
  1. books.html +585 -91
books.html CHANGED
@@ -105,8 +105,7 @@ html, body {
105
  background: var(--border-light);
106
  transform: translateY(-2px);
107
  }
108
-
109
- /* 3. WIZARD & SETTINGS CONTROLS */
110
  .wizard-container {
111
  display: flex; flex-direction: column; align-items: center; justify-content: flex-start;
112
  padding: 24px; padding-top: 90px; padding-bottom: 40px; width: 100%; box-sizing: border-box;
@@ -123,8 +122,9 @@ html, body {
123
  .step-card h2 { color: var(--text-main); margin-top: 0; margin-bottom: 20px; font-weight: 800; font-size: 22px; }
124
  .step-card label { display: block; text-align: left; margin-bottom: 8px; font-weight: 600; color: var(--primary); text-transform: uppercase; font-size: 12px; }
125
 
 
126
  #closeSettingsWizardBtn {
127
- display: none;
128
  position: fixed;
129
  top: 16px;
130
  left: 16px;
@@ -155,6 +155,7 @@ html, body {
155
  }
156
  .floating-lang-btn:hover { transform: scale(1.1) rotate(15deg); background: var(--primary-glow); }
157
 
 
158
  select.standard, input.standard, textarea.standard {
159
  width: 100%; padding: 14px 16px; border-radius: 12px; border: 1px solid var(--border-light);
160
  background: var(--input-bg); color: var(--text-main); font-size: 15px; margin-bottom: 20px;
@@ -164,6 +165,7 @@ select.standard:focus, input.standard:focus, textarea.standard:focus {
164
  border-color: var(--primary); box-shadow: 0 0 0 3px var(--primary-glow);
165
  }
166
 
 
167
  .chapter-input-row {
168
  display: flex; gap: 10px; align-items: center; margin-bottom: 20px; width: 100%;
169
  }
@@ -299,17 +301,19 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
299
  @media (max-width: 600px) {
300
  .topbar .btn { color: var(--text-main) !important; }
301
  .topbar .btn::before { color: var(--text-main) !important; }
302
-
 
303
  .topbar .btn { padding: 8px !important; font-size: 0 !important; width: 36px; height: 36px; border-radius: 50%; }
304
  .topbar .btn::before { font-size: 16px; line-height: 1; display: block; }
305
 
306
  #shareBtn::before { content: "📤"; }
307
  #clearBtn::before { content: "🗑️"; }
308
- #settingsBtn::before { content: "⚙️"; display: none !important; } /* Hidden entirely */
309
 
310
  .appTitle { font-size: 15px; }
311
  .bubble { max-width: 90%; }
312
 
 
313
  .floating-lang-btn { top: 12px; right: 12px; width: 36px; height: 36px; font-size: 16px; }
314
  }
315
  /* 5. AUDIO PLAYER (FIXED) */
@@ -330,7 +334,7 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
330
  animation: slideDown 0.3s ease;
331
  box-shadow: 0 10px 30px rgba(0,0,0,0.4);
332
  }
333
- /* 6. CAMERA MODAL */
334
  #cameraModal {
335
  display: none;
336
  position: fixed; inset: 0; z-index: 999999999;
@@ -354,7 +358,7 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
354
  background: linear-gradient(to top, rgba(0,0,0,0.6), transparent);
355
  }
356
 
357
- /* 7. AI "THINKING" INDICATOR */
358
  .typing-indicator { display: flex; align-items: center; gap: 10px; padding: 4px 2px; }
359
  .typing-indicator .dots { display: flex; gap: 4px; }
360
  .typing-indicator .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--primary); opacity: 0.4; animation: typingBounce 1.1s infinite ease-in-out; }
@@ -366,7 +370,7 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
366
  .typing-status-text .status-fade { display: inline-block; animation: statusFadeIn 0.35s ease; }
367
  @keyframes statusFadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
368
 
369
- /* 8. SHARE MODE SELECTION HIGHLIGHT */
370
  .share-mode-active .bubble { cursor: pointer; transition: box-shadow 0.2s ease, transform 0.15s ease, border-color 0.2s ease; }
371
  .share-mode-active .bubble:active { transform: scale(0.98); }
372
  .bubble.selected-for-share {
@@ -382,7 +386,7 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
382
  box-shadow: 0 2px 6px rgba(0,0,0,0.3); z-index: 5;
383
  }
384
 
385
- /* 9. MATH WRAP-IN-BUBBLE */
386
  .bubble mjx-container { max-width: 100% !important; overflow-x: auto; overflow-y: hidden; display: block !important; }
387
 
388
  .audio-btn {
@@ -416,7 +420,7 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
416
  <div style="display:flex; gap:8px;">
417
  <button class="btn btn-primary" id="shareBtn" style="padding: 6px 12px; display: none; font-size: 13px; background: #25D366; border: none;" onclick="window.toggleShareMode()">📤 Share</button>
418
  <button class="btn btn-secondary" id="clearBtn" style="padding: 6px 12px; display: none; font-size: 13px;" onclick="window.clearChat()">🗑️ Clear</button>
419
- <button class="btn btn-primary" id="settingsBtn" style="padding: 6px 12px; display: none !important; font-size: 13px;" onclick="window.openSettings()">⚙️</button>
420
  </div>
421
  </div>
422
 
@@ -455,13 +459,136 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
455
  </div>
456
  </div>
457
 
458
- <!-- NUKED WIZARD HTML BUT KEPT IN DOM SO FUNCTIONS DON'T CRASH -->
459
- <div id="wizardPage" style="display: none !important;"></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
460
 
461
  <div id="chatPage">
462
  <div class="chat-scroll-area" id="chatHistory"></div>
463
 
464
  <div id="shareActionArea" class="bottom-action-container" style="display:none; border-top: 2px solid #25D366;">
 
465
  <div style="color:var(--text-main); text-align:center; font-weight:bold; font-size:14px; margin-bottom: 10px;">👆 Tap messages above to select them</div>
466
  <div style="display:flex; gap:10px;">
467
  <button class="btn btn-secondary" style="flex:1; padding: 12px;" onclick="window.cancelShareMode()">Cancel</button>
@@ -509,7 +636,10 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
509
  <div class="modal-box" style="text-align:center; border:2px solid #25D366; max-width: 450px;">
510
  <h3 style="color: #25D366; margin-bottom: 15px; font-size: 22px; font-weight: 900;">💬 Share Selected Notes</h3>
511
  <p style="font-size: 14px; color: var(--text-muted); margin-bottom: 20px;">Enter the mobile number to send notes.</p>
 
 
512
  <input type="number" id="waNumberInput" placeholder="9876543210" class="standard" style="width: 100%; padding: 15px; font-weight: bold; font-size: 18px; margin-bottom: 25px; text-align: center; box-sizing: border-box;">
 
513
  <div style="display: flex; gap: 10px;">
514
  <button id="waSendBtn" class="btn" style="flex: 1; padding: 12px; border-radius: 12px; background: #10b981; color: white;" onclick="window.submitWhatsAppSelection(event)">🚀 Send</button>
515
  <button class="btn" style="flex: 1; padding: 12px; border-radius: 12px; background: #ef4444; color: white;" onclick="document.getElementById('whatsappModal').style.display='none'">✖ Cancel</button>
@@ -565,6 +695,59 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
565
  <div id="publisherFinderModal" class="modal-overlay" style="z-index:99999998;">
566
  <div class="modal-box" style="max-width:480px; max-height:88vh; overflow-y:auto;">
567
  <h3 style="margin-top:0; color:var(--primary);">🔍 Find My Publisher</h3>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
568
  </div>
569
  </div>
570
 
@@ -581,6 +764,7 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
581
 
582
  <!-- 🚨 100% GLOBALLY BOUND SCRIPT BLOCK 🚨 -->
583
  <script>
 
584
  localforage.config({ name: 'AI_Pro_Suite', storeName: 'massive_chat_history' });
585
  let appHistory = [];
586
  let currentSessionId = Number(new URLSearchParams(window.location.search).get('restore')) || Date.now();
@@ -589,10 +773,10 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
589
  let currentTypewriterInterval = null;
590
  let isHindiUI = true;
591
  let selectedData = {};
592
- let currentImages = [];
593
  const MAX_CHAT_IMAGES = 10;
594
- let pfPhotoBase64 = null;
595
- let voiceDictateTarget = 'chat';
596
  let documentMemory = "";
597
  let webUrls = [];
598
  let cameraTarget = 'chat';
@@ -604,6 +788,7 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
604
  let voiceText = "";
605
  let localSessionHTMLSize = 0;
606
 
 
607
  window.showCustomAlert = function(msg) {
608
  document.getElementById('alertMessage').innerText = msg;
609
  document.getElementById('customAlertModal').style.display = 'flex';
@@ -617,22 +802,15 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
617
  document.body.appendChild(t); setTimeout(() => { t.style.opacity = '0'; t.style.transition = '0.3s'; setTimeout(() => t.remove(), 300); }, 2500);
618
  }
619
 
620
- // 🛑 AUTO RESTORE & BYPASS WIZARD ENTIRELY 🛑
621
  window.addEventListener('load', async function() {
 
 
 
622
  document.getElementById('closeSettingsWizardBtn').style.display = 'none';
623
  window.stopAudio();
624
  window.resetSendButton();
625
 
626
- // 1. NUKE THE WIZARD UI IMMEDIATELY
627
- document.getElementById('wizardPage').style.display = 'none';
628
- document.getElementById('chatPage').style.display = 'flex';
629
- document.getElementById('settingsBtn').style.display = 'block';
630
- document.getElementById('clearBtn').style.display = 'block';
631
- document.getElementById('shareBtn').style.display = 'block';
632
-
633
- // 2. SET DEFAULT DATA SO THE AI DOESN'T CRASH
634
- selectedData = { publisher: "General", subject: "General Studies", class: "Any", chapter: "General" };
635
-
636
  let ptiParam = new URLSearchParams(window.location.search).get('pti');
637
  if (ptiParam) {
638
  currentPti = ptiParam;
@@ -647,6 +825,9 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
647
  if(session) {
648
  selectedData = session.data; currentSessionId = session.id;
649
  document.getElementById('sessionTitleDisplay').innerText = session.title || "📚 Book Deep Study";
 
 
 
650
  document.getElementById('chatHistory').innerHTML = session.html;
651
  localSessionHTMLSize = session.html.length;
652
  setTimeout(() => { const c = document.getElementById('chatHistory'); c.scrollTo({top: c.scrollHeight, behavior: 'instant'}); }, 100);
@@ -657,13 +838,12 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
657
  if(activeSession && activeSettings) {
658
  selectedData = JSON.parse(activeSettings);
659
  document.getElementById('sessionTitleDisplay').innerText = `${selectedData.subject} - ${selectedData.chapter}`;
 
 
 
660
  document.getElementById('chatHistory').innerHTML = activeSession;
661
  localSessionHTMLSize = activeSession.length;
662
  setTimeout(() => { const c = document.getElementById('chatHistory'); c.scrollTo({top: c.scrollHeight, behavior: 'instant'}); }, 100);
663
- } else {
664
- // 3. IF NO HISTORY, INSTANTLY START A NEW CHAT
665
- document.getElementById('sessionTitleDisplay').innerText = "📚 Book Deep Study";
666
- window.startConversation(true);
667
  }
668
  }
669
  }
@@ -671,12 +851,14 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
671
  window.startMarquee();
672
  });
673
 
 
674
  window.toggleAppLanguage = function() {
675
  window.closePlusMenu();
676
  isHindiUI = !isHindiUI;
677
  showToast(isHindiUI ? "🌐 Language set to Hindi" : "🌐 Language set to English");
678
  }
679
 
 
680
  window.clearChat = function() {
681
  if(confirm("🗑️ Are you sure you want to completely clear this chapter's chat and memory?")) {
682
  document.getElementById('chatHistory').innerHTML = "";
@@ -686,14 +868,22 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
686
  currentPti = null;
687
  localSessionHTMLSize = 0;
688
 
 
689
  const newUrl = `${window.location.origin}${window.location.pathname}`;
690
  window.history.replaceState({ path: newUrl }, '', newUrl);
691
 
 
 
 
 
 
 
692
  showToast("🗑️ Memory Wiped Clean.");
693
- window.startConversation(true, true);
694
  }
695
  };
696
 
 
697
  let marqueeInterval;
698
  window.startMarquee = function() {
699
  const titleEl = document.getElementById('sessionTitleDisplay');
@@ -749,11 +939,68 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
749
  }
750
  }
751
 
752
- // ALL WIZARD LOGIC RETAINED BUT HIDDEN IN UI
753
- window.getEffectivePublisher = function() { return selectedData.publisher || "General"; }
754
- window.handlePublisherChange = function() {}
755
- window.validateCustomPublisher = function() {}
756
- window.nextStep = function(step) {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
757
 
758
  window.openCameraChat = function() { cameraTarget = 'chat'; window.openCamera(); }
759
  window.openBookRecognitionCamera = function() { cameraTarget = 'bookRecognition'; window.openCamera(); }
@@ -801,6 +1048,7 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
801
  }
802
  }
803
 
 
804
  window.renderImagePreviews = function() {
805
  const row = document.getElementById('imgChipRow');
806
  const wrap = document.getElementById('imagePreviewContainer');
@@ -815,21 +1063,208 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
815
  }
816
  window.removeImageAt = function(idx) { currentImages.splice(idx, 1); window.renderImagePreviews(); window.validateSendButton(); }
817
 
818
- window.openPublisherFinder = function() {}
819
- window.closePublisherFinder = function() {}
820
- window.clearPublisherFinderPhoto = function() {}
821
- window.runPublisherSearch = async function() {}
822
- window.donePublisherFinder = function() {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
823
 
824
  window.retakeBookPhoto = function() { document.getElementById('bookPreviewModal').style.display = 'none'; window.openBookRecognitionCamera(); }
825
  window.closeBookPreview = function() { document.getElementById('bookPreviewModal').style.display = 'none'; bookRecognitionImageBase64 = null; }
826
- window.submitBookPhoto = async function() {}
827
- window.triggerSubjectFetch = async function() {}
828
- window.handleSubjectChange = function() {}
829
- window.triggerChapterFetch = async function() {}
830
- window.fetchChapterContext = async function() {}
831
- window.fetchRealBookCover = async function(pub, sub, cls) {}
832
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
833
  window.validateSendButton = function() {
834
  const inp = document.getElementById('chatInput');
835
  const btn = document.getElementById('sendBtn');
@@ -1009,13 +1444,34 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
1009
  window.togglePlusMenu = function(e) { e.stopPropagation(); const m = document.getElementById("plusMenu"); m.style.display = m.style.display === "flex" ? "none" : "flex"; }
1010
  window.closePlusMenu = function() { document.getElementById("plusMenu").style.display = "none"; }
1011
 
1012
- window.openSettings = function() {}
1013
- window.closeSettingsWizard = function() {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1014
 
1015
  window.handleEnter = function(e) { if(e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); if (document.getElementById('sendBtn').classList.contains('active-btn')) window.sendMessage(); } }
1016
 
1017
  window.openVoiceLang = function(target) { voiceDictateTarget = target || 'chat'; window.closePlusMenu(); document.getElementById('voiceLangModal').style.display='flex'; }
1018
- let voiceFinalCount = 0;
1019
  window.selectVoiceLang = function(lang) {
1020
  document.getElementById('voiceLangModal').style.display='none';
1021
  document.getElementById('voiceDictateModal').style.display='flex';
@@ -1029,6 +1485,9 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
1029
  voiceRec.interimResults = true;
1030
 
1031
  voiceRec.onresult = (e) => {
 
 
 
1032
  let interim = "";
1033
  for(let i = 0; i < e.results.length; i++) {
1034
  const transcript = e.results[i][0].transcript;
@@ -1047,11 +1506,15 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
1047
  window.startDictation = function(e) { e.preventDefault(); if(e.stopPropagation) e.stopPropagation(); if(voiceRec && !isDictating) { isDictating = true; try { voiceRec.start(); } catch(err) {} holdBtn.innerHTML = "🎙️ Listening..."; holdBtn.style.background = "#ef4444"; } }
1048
  window.stopDictation = function(e) { e.preventDefault(); if(e.stopPropagation) e.stopPropagation(); if(voiceRec && isDictating) { isDictating = false; voiceRec.stop(); holdBtn.innerHTML = "👆 Hold to Speak"; holdBtn.style.background = "var(--primary)"; } }
1049
 
 
 
 
1050
  holdBtn.addEventListener('touchstart', window.startDictation, {passive:false});
1051
  holdBtn.addEventListener('mousedown', window.startDictation);
1052
  holdBtn.addEventListener('touchend', window.stopDictation); holdBtn.addEventListener('mouseup', window.stopDictation); holdBtn.addEventListener('mouseleave', window.stopDictation);
1053
 
1054
  window.commitVoice = function() {
 
1055
  const targetId = voiceDictateTarget === 'chapter' ? 'manualChapter' : 'chatInput';
1056
  const targetEl = document.getElementById(targetId);
1057
  const spoken = document.getElementById('voiceDictateText').value.trim();
@@ -1096,6 +1559,9 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
1096
  window.speechSynthesis.speak(window.activeUtterance);
1097
  };
1098
 
 
 
 
1099
  window.fetchAndInjectPtiSession = async function(ptiString) {
1100
  try {
1101
  const response = await fetch(`/api/pti-get?pti=${ptiString}`);
@@ -1108,8 +1574,10 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
1108
 
1109
  document.getElementById('sessionTitleDisplay').innerText = sessionRecord.title || "📚 Book Deep Study";
1110
 
 
 
1111
  document.getElementById('chatPage').style.display = 'flex';
1112
- document.getElementById('settingsBtn').style.display = 'none';
1113
  document.getElementById('clearBtn').style.display = 'block';
1114
  document.getElementById('shareBtn').style.display = 'block';
1115
 
@@ -1119,6 +1587,7 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
1119
  window.startMarquee();
1120
  } catch (e) {
1121
  showToast("❌ Unable to locate active PTI profile.");
 
1122
  }
1123
  }
1124
 
@@ -1170,46 +1639,65 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
1170
  const newUrl = `${window.location.origin}${window.location.pathname}?pti=${currentPti}`;
1171
  window.history.replaceState({ path: newUrl }, '', newUrl);
1172
  }
1173
- });
 
1174
  }
1175
 
 
1176
  window.startConversation = async function(forceNew = false, forceClear = false) {
 
 
 
 
 
 
 
 
 
1177
  if (forceClear) {
1178
  document.getElementById('chatHistory').innerHTML = ""; localStorage.removeItem('bookChatHistory_VUltimateAI'); currentSessionId = Date.now();
 
 
1179
  }
1180
 
 
1181
  document.getElementById('loadingPage').style.display = 'flex';
1182
 
1183
  let bar = document.getElementById('loadingBar'); let desc = document.getElementById('loadingDesc');
1184
- bar.style.width = '50%'; desc.innerText = "Setting up Tutor Interface...";
 
 
 
 
1185
  await new Promise(r => setTimeout(r, 400));
1186
  bar.style.width = '100%';
1187
 
1188
  setTimeout(async () => {
1189
  document.getElementById('loadingPage').style.display = 'none';
1190
  document.getElementById('chatPage').style.display = 'flex';
1191
- document.getElementById('settingsBtn').style.display = 'none';
1192
  document.getElementById('clearBtn').style.display = 'block';
1193
  document.getElementById('shareBtn').style.display = 'block';
1194
 
1195
- document.getElementById('sessionTitleDisplay').innerText = "📚 Book Deep Study";
1196
  window.startMarquee();
1197
  localStorage.setItem('bookSettings_VUltimateAI', JSON.stringify(selectedData));
1198
 
1199
- if(document.getElementById('chatHistory').innerHTML.trim() === "") {
1200
- let initialMessageHTML = !isHindiUI ?
1201
- `Hello! I am your AI Tutor. <br><br>**I will respond in English by default.**<br><br>
 
1202
  <div class="preset-chips" style="margin-top: 15px;">
1203
- <button class="preset-btn" onclick="window.runPreset('Generate detailed study notes.')">📝 Generate Notes</button>
1204
- <button class="preset-btn" onclick="window.runPreset('Create 10 important MCQs with answers.')">✅ Objectives</button>
1205
- <button class="preset-btn" onclick="window.runPreset('Analyze this topic in simple terms.')">📊 Analyze Topic</button>
1206
  </div>`
1207
  :
1208
- `नमस्ते! मैं आपका एआई शिक्षक हूँ। <br><br>**मैं आपके सभी सवालों के जवाब डिफ़ॉल्ट रूप से हिंदी में दूँगा।**<br><br>
1209
  <div class="preset-chips" style="margin-top: 15px;">
1210
- <button class="preset-btn" onclick="window.runPreset('विस्तृत और आसान नोट्स बनाएं।')">📝 जनरेट नोट्स</button>
1211
- <button class="preset-btn" onclick="window.runPreset('10 महत्वपूर्ण बहुविकल्पीय प्रश्न (MCQ) बनाएं और उत्तर भी दें।')">✅ ऑब्जेक्टिव प्रश्न</button>
1212
- <button class="preset-btn" onclick="window.runPreset('विस्तार स�� और आसान भाषा में विश्लेषण करें।')">📊 विषय का विश्लेषण</button>
1213
  </div>`;
1214
 
1215
  await window.addAiMessage(initialMessageHTML, false);
@@ -1220,7 +1708,7 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
1220
  window.sendMessage = async function() {
1221
  const inputEl = document.getElementById('chatInput');
1222
  const text = inputEl.value.trim();
1223
- const imgs = currentImages.slice();
1224
  const btn = document.getElementById('sendBtn');
1225
 
1226
  if(!btn.classList.contains('active-btn')) return;
@@ -1242,8 +1730,9 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
1242
  document.getElementById('chatHistory').appendChild(loadDiv);
1243
  c.scrollTo({top: c.scrollHeight, behavior: 'smooth'});
1244
 
1245
- const thinkingStages = imgs.length ? ["Understanding your question…", "Reading the attached image" + (imgs.length > 1 ? "s…" : "…"), "Checking memory…", "Drafting the answer…"]
1246
- : ["Understanding your question…", "Checking memory…", "Searching for the exact wording…", "Drafting the answer…"];
 
1247
  let stageIdx = 0;
1248
  const statusEl = () => document.getElementById(`${loadingId}_status`);
1249
  const thinkingInterval = setInterval(() => {
@@ -1260,31 +1749,41 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
1260
  let msgText = clone.innerText.trim().replace(/\s+/g, ' '); if(msgText) recentHistory += `${role}: ${msgText}\n`;
1261
  }
1262
 
1263
- let targetLang = !isHindiUI ? 'ENGLISH' : 'HINDI (Devanagari script)';
 
 
1264
 
1265
- let sysPrompt = `You are a premium AI expert educational tutor. Answer entirely in ${targetLang}.
 
1266
  STRICT RULES:
1267
  1. NO HASHTAGS (#) allowed anywhere. Use ** for bolding.
1268
  2. ALWAYS rewrite the user's core question at the very beginning of your answer in BOLD.
1269
  3. NO RAW UNITS like \\text{m/s}^2. Use standard text.
1270
-
1271
- 🚨 MATH TEMPLATE: For calculation questions, follow exactly:
1272
- **1. [Step 1 Heading]**
1273
- [Step 1 explanation in full words]
1274
- $$[Equation without using \\frac]$$
1275
- **✅ Final Answer**
1276
- [Final sentence in ${targetLang}]
1277
-
1278
- 🎨 VISUAL RULE: IF the question relates to Geometry, Physics concepts, Chemistry structures, or visual Math, YOU MUST generate a highly detailed, colorful <svg> diagram wrapped exactly in <div class="math-svg-wrap"><svg>...</svg></div>.`;
 
 
 
 
 
 
1279
 
1280
  if(recentHistory) sysPrompt += `\n\n--- CHAT HISTORY ---\n${recentHistory}`;
1281
- if (documentMemory) sysPrompt += `\n\n--- INBUILT MEMORY ---\n${documentMemory.substring(0, 40000)}`;
1282
 
1283
  let payloadImgs = imgs;
 
1284
 
1285
  const payload = payloadImgs.length
1286
  ? { imageBase64: payloadImgs[0], imageBase64Array: payloadImgs, userPrompt: text || "Please solve the questions visible in all the attached images.", systemPrompt: sysPrompt }
1287
- : { userPrompt: text || "Please provide the information requested.", systemPrompt: sysPrompt, useSearch: true };
1288
 
1289
  try {
1290
  currentAbortController = new AbortController();
@@ -1306,14 +1805,18 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
1306
  }
1307
  }
1308
 
 
1309
  window.addAiMessage = async function(text, typewrite = false) {
1310
  const msgDiv = document.createElement("div"); msgDiv.className = "msg ai";
1311
  const bubble = document.createElement("div"); bubble.className = "bubble";
1312
  msgDiv.appendChild(bubble); document.getElementById('chatHistory').appendChild(msgDiv);
1313
 
 
1314
  let cleanText = text.replace(/\\frac{([^}]+)}{([^}]+)}/g, '$1/$2').replace(/\\times/g, '×');
1315
  let formattedHTML = marked.parse(cleanText);
1316
 
 
 
1317
  const ttsId = `tts_${Date.now()}_${Math.floor(Math.random()*10000)}`;
1318
  let btnHtml = `<br><button class="listen-btn" onclick="window.playAudio(this)" data-target="${ttsId}">🔊 Listen</button>`;
1319
 
@@ -1338,7 +1841,7 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
1338
  currentHTML += formattedHTML.substring(i, end + 1);
1339
  i = end + 1;
1340
  txtBox.innerHTML = currentHTML;
1341
- return;
1342
  }
1343
  }
1344
 
@@ -1357,16 +1860,7 @@ textarea { flex: 1; background: transparent; border: none; color: var(--text-mai
1357
 
1358
  window.saveHistorySafe(); window.triggerCloudSyncEngine(); window.resetSendButton();
1359
  }
1360
- };
1361
- </script>
1362
-
1363
- <script>
1364
- if ('serviceWorker' in navigator) {
1365
- navigator.serviceWorker.register('/sw.js').then(() => {
1366
- console.log('✅ PWA App Mode Ready!');
1367
- }).catch((error) => {});
1368
  }
1369
  </script>
1370
-
1371
  </body>
1372
  </html>
 
105
  background: var(--border-light);
106
  transform: translateY(-2px);
107
  }
108
+ /* 3. WIZARD & SETTINGS CONTROLS (X Button & Language Icon) */
 
109
  .wizard-container {
110
  display: flex; flex-direction: column; align-items: center; justify-content: flex-start;
111
  padding: 24px; padding-top: 90px; padding-bottom: 40px; width: 100%; box-sizing: border-box;
 
122
  .step-card h2 { color: var(--text-main); margin-top: 0; margin-bottom: 20px; font-weight: 800; font-size: 22px; }
123
  .step-card label { display: block; text-align: left; margin-bottom: 8px; font-weight: 600; color: var(--primary); text-transform: uppercase; font-size: 12px; }
124
 
125
+ /* Fixed Settings Close (X) & Language Buttons */
126
  #closeSettingsWizardBtn {
127
+ display: none; /* Hidden by default; toggled purely via JS inline style (no !important, or JS can never re-show it) */
128
  position: fixed;
129
  top: 16px;
130
  left: 16px;
 
155
  }
156
  .floating-lang-btn:hover { transform: scale(1.1) rotate(15deg); background: var(--primary-glow); }
157
 
158
+ /* Premium Form Elements */
159
  select.standard, input.standard, textarea.standard {
160
  width: 100%; padding: 14px 16px; border-radius: 12px; border: 1px solid var(--border-light);
161
  background: var(--input-bg); color: var(--text-main); font-size: 15px; margin-bottom: 20px;
 
165
  border-color: var(--primary); box-shadow: 0 0 0 3px var(--primary-glow);
166
  }
167
 
168
+ /* 4. FIXING CHAPTER CAMERA/MIC ROW */
169
  .chapter-input-row {
170
  display: flex; gap: 10px; align-items: center; margin-bottom: 20px; width: 100%;
171
  }
 
301
  @media (max-width: 600px) {
302
  .topbar .btn { color: var(--text-main) !important; }
303
  .topbar .btn::before { color: var(--text-main) !important; }
304
+ }
305
+ /* Shrink the buttons to just icons on small screens to prevent squeezing */
306
  .topbar .btn { padding: 8px !important; font-size: 0 !important; width: 36px; height: 36px; border-radius: 50%; }
307
  .topbar .btn::before { font-size: 16px; line-height: 1; display: block; }
308
 
309
  #shareBtn::before { content: "📤"; }
310
  #clearBtn::before { content: "🗑️"; }
311
+ #settingsBtn::before { content: "⚙️"; }
312
 
313
  .appTitle { font-size: 15px; }
314
  .bubble { max-width: 90%; }
315
 
316
+ /* Make sure settings icon and X button don't overlap on mobile */
317
  .floating-lang-btn { top: 12px; right: 12px; width: 36px; height: 36px; font-size: 16px; }
318
  }
319
  /* 5. AUDIO PLAYER (FIXED) */
 
334
  animation: slideDown 0.3s ease;
335
  box-shadow: 0 10px 30px rgba(0,0,0,0.4);
336
  }
337
+ /* 6. CAMERA MODAL (was completely unstyled — this is why the UI never appeared) */
338
  #cameraModal {
339
  display: none;
340
  position: fixed; inset: 0; z-index: 999999999;
 
358
  background: linear-gradient(to top, rgba(0,0,0,0.6), transparent);
359
  }
360
 
361
+ /* 7. AI "THINKING" INDICATOR (real staged status, not just static dots) */
362
  .typing-indicator { display: flex; align-items: center; gap: 10px; padding: 4px 2px; }
363
  .typing-indicator .dots { display: flex; gap: 4px; }
364
  .typing-indicator .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--primary); opacity: 0.4; animation: typingBounce 1.1s infinite ease-in-out; }
 
370
  .typing-status-text .status-fade { display: inline-block; animation: statusFadeIn 0.35s ease; }
371
  @keyframes statusFadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }
372
 
373
+ /* 8. SHARE MODE SELECTION HIGHLIGHT (the "green grid" — previously no CSS existed at all) */
374
  .share-mode-active .bubble { cursor: pointer; transition: box-shadow 0.2s ease, transform 0.15s ease, border-color 0.2s ease; }
375
  .share-mode-active .bubble:active { transform: scale(0.98); }
376
  .bubble.selected-for-share {
 
386
  box-shadow: 0 2px 6px rgba(0,0,0,0.3); z-index: 5;
387
  }
388
 
389
+ /* 9. MATH WRAP-IN-BUBBLE: MathJax's <mjx-container> ignored bubble width and could overflow the screen. */
390
  .bubble mjx-container { max-width: 100% !important; overflow-x: auto; overflow-y: hidden; display: block !important; }
391
 
392
  .audio-btn {
 
420
  <div style="display:flex; gap:8px;">
421
  <button class="btn btn-primary" id="shareBtn" style="padding: 6px 12px; display: none; font-size: 13px; background: #25D366; border: none;" onclick="window.toggleShareMode()">📤 Share</button>
422
  <button class="btn btn-secondary" id="clearBtn" style="padding: 6px 12px; display: none; font-size: 13px;" onclick="window.clearChat()">🗑️ Clear</button>
423
+ <button class="btn btn-primary" id="settingsBtn" style="padding: 6px 12px; display: none; font-size: 13px;" onclick="window.openSettings()">⚙️</button>
424
  </div>
425
  </div>
426
 
 
459
  </div>
460
  </div>
461
 
462
+ <div id="wizardPage">
463
+ <button id="closeSettingsWizardBtn" onclick="window.closeSettingsWizard()">✖</button>
464
+ <button class="floating-lang-btn" onclick="window.toggleAppLanguage()" title="Toggle Language">🌐</button>
465
+
466
+ <div class="wizard-container" id="wizardContainer">
467
+
468
+ <div class="step-card active" id="step-1">
469
+ <h2>Step 1: Board / Publisher</h2>
470
+ <label>Select Publisher:</label>
471
+ <select id="publisherSelect" class="standard" onchange="window.handlePublisherChange()">
472
+ <option value="" selected disabled>-- Select Publisher --</option>
473
+ <option value="NCERT">NCERT</option>
474
+ <option value="SCERT">SCERT</option>
475
+ <option value="Arvind Vigyan">Arvind Vigyan</option>
476
+ <option value="Bharti Bhawan">Bharti Bhawan</option>
477
+ <option value="Sugam">Sugam</option>
478
+ <option value="Bihar Board">Bihar Board</option>
479
+ <option value="New Way">New Way</option>
480
+ <option value="R.D. Sharma">R.D. Sharma</option>
481
+ <option value="R.S. Aggarwal">R.S. Aggarwal</option>
482
+ <option value="Laxmi Publications">Laxmi Publications</option>
483
+ <option value="Goyal Brothers">Goyal Brothers</option>
484
+ <option value="CBSE Reference">CBSE Reference</option>
485
+ <option value="Lucent">Lucent</option>
486
+ <option value="Arihant">Arihant</option>
487
+ <option value="Oswaal">Oswaal</option>
488
+ <option value="S Chand">S Chand</option>
489
+ <option value="Other">Other (Type / Find Manually)</option>
490
+ </select>
491
+
492
+ <div id="customPublisherContainer" style="display:none; margin-top:-10px;">
493
+ <label>Type Publisher Name (or skip to search):</label>
494
+ <input type="text" id="customPublisherInput" class="standard" placeholder="e.g. Rajasthan Board / Vidya Bharti..." oninput="window.validateCustomPublisher()">
495
+ <div class="btn-row" style="margin-bottom:20px;">
496
+ <button class="btn btn-secondary" style="flex:1;" onclick="document.getElementById('customPublisherInput').value=''; window.validateCustomPublisher();">⏭️ Skip Naming It</button>
497
+ <button class="btn" style="flex:1; background:#8b5cf6; color:white;" onclick="window.openPublisherFinder()">🔍 Find Publisher for Me</button>
498
+ </div>
499
+ </div>
500
+
501
+ <div class="btn-row">
502
+ <button class="btn btn-primary" onclick="window.nextStep(2)">Next ➔</button>
503
+ </div>
504
+ </div>
505
+
506
+ <div class="step-card" id="step-2">
507
+ <h2>Step 2: Class</h2>
508
+ <label>Select Class:</label>
509
+ <select id="classSelect" class="standard" onchange="window.triggerSubjectFetch()">
510
+ <option value="" selected disabled>-- Select Class --</option>
511
+ <option value="Class 1">Class 1</option>
512
+ <option value="Class 2">Class 2</option>
513
+ <option value="Class 3">Class 3</option>
514
+ <option value="Class 4">Class 4</option>
515
+ <option value="Class 5">Class 5</option>
516
+ <option value="Class 6">Class 6</option>
517
+ <option value="Class 7">Class 7</option>
518
+ <option value="Class 8">Class 8</option>
519
+ <option value="Class 9">Class 9</option>
520
+ <option value="Class 10">Class 10</option>
521
+ <option value="Class 11">Class 11</option>
522
+ <option value="Class 12">Class 12</option>
523
+ </select>
524
+ <div class="btn-row">
525
+ <button class="btn btn-secondary" onclick="window.nextStep(1)">⬅ Back</button>
526
+ <button class="btn btn-primary" onclick="window.nextStep(3)">Next ➔</button>
527
+ </div>
528
+ </div>
529
+
530
+ <div class="step-card" id="step-3">
531
+ <h2>Step 3: Subject</h2>
532
+ <label id="subjectFetchStatus">Select Subject (AI Fetched):</label>
533
+ <select id="subjectSelect" class="standard" onchange="window.handleSubjectChange()">
534
+ <option value="" selected disabled>-- Select Publisher & Class First --</option>
535
+ </select>
536
+
537
+ <div id="customSubjectContainer" style="display:none; margin-top: 10px;">
538
+ <input type="text" id="customSubjectInput" class="standard" placeholder="Type custom subject here (e.g. Computer)..." oninput="window.triggerChapterFetch()">
539
+ </div>
540
+
541
+ <div class="btn-row">
542
+ <button class="btn btn-secondary" onclick="window.nextStep(2)">⬅ Back</button>
543
+ <button class="btn btn-primary" onclick="window.nextStep(4)">Next ➔</button>
544
+ </div>
545
+ </div>
546
+
547
+ <div class="step-card" id="step-4">
548
+ <h2>Step 4: Chapter & Photo</h2>
549
+ <label id="chapterFetchStatus">Select Chapter (AI Generated):</label>
550
+ <select id="chapterSelect" class="standard">
551
+ <option value="" selected disabled>-- Select Subject First --</option>
552
+ </select>
553
+
554
+ <label style="margin-top:10px;">Or Type Chapter Manually:</label>
555
+ <div style="display: flex; gap: 10px; align-items: center; margin-bottom: 20px;">
556
+ <input type="text" id="manualChapter" class="standard" placeholder="e.g. Motion / गति" style="margin-bottom: 0;">
557
+ <button id="manualChapterMicBtn" class="icon-btn" style="background:var(--primary); color:white; border-radius:12px; width:50px; height:50px;" onclick="window.openVoiceLang('chapter')">🎤</button>
558
+ <button class="icon-btn" style="background:#10b981; color:white; border-radius:12px; width:50px; height:50px;" onclick="window.openBookRecognitionCamera()" title="Take photo of book page">📷</button>
559
+ </div>
560
+
561
+ <div class="btn-row">
562
+ <button class="btn btn-secondary" onclick="window.nextStep(3)">⬅ Back</button>
563
+ <button class="btn btn-primary" id="initBtnStep4" onclick="window.nextStep(5)">Next ➔</button>
564
+ </div>
565
+ </div>
566
+
567
+ <div class="step-card" id="step-5">
568
+ <h2>Ready!</h2>
569
+ <div id="dynamicBookCover">
570
+ <div class="generated-cover">
571
+ <span style="font-size:11px; text-transform:uppercase; letter-spacing:1px; opacity:0.9;" id="coverPub">Publisher</span>
572
+ <span style="font-size:20px; font-weight:800; line-height:1.2; margin:10px 0;" id="coverSub">Loading...</span>
573
+ <span style="font-size:12px; font-weight:bold; background:rgba(0,0,0,0.4); padding:4px 10px; border-radius:12px; border:1px solid rgba(255,255,255,0.2);" id="coverCls">Class</span>
574
+ </div>
575
+ </div>
576
+
577
+ <div id="selectionSummary" style="text-align:left; background: var(--input-bg); border: 1px solid var(--border-light); padding:15px; border-radius:12px; margin-bottom:20px; font-weight:600; line-height:2;"></div>
578
+
579
+ <button id="initFinalBtn" class="btn btn-primary" style="width: 100%; background: linear-gradient(135deg, #10b981, #047857); padding: 18px; font-size: 18px;" onclick="window.startConversation(false)">Initialize AI Tutor 🚀</button>
580
+ <div class="btn-row">
581
+ <button class="btn btn-secondary" onclick="window.nextStep(4)">⬅ Edit Details</button>
582
+ </div>
583
+ </div>
584
+ </div>
585
+ </div>
586
 
587
  <div id="chatPage">
588
  <div class="chat-scroll-area" id="chatHistory"></div>
589
 
590
  <div id="shareActionArea" class="bottom-action-container" style="display:none; border-top: 2px solid #25D366;">
591
+ <!-- 🚨 FIXED SHARE TEXT VISIBILITY 🚨 -->
592
  <div style="color:var(--text-main); text-align:center; font-weight:bold; font-size:14px; margin-bottom: 10px;">👆 Tap messages above to select them</div>
593
  <div style="display:flex; gap:10px;">
594
  <button class="btn btn-secondary" style="flex:1; padding: 12px;" onclick="window.cancelShareMode()">Cancel</button>
 
636
  <div class="modal-box" style="text-align:center; border:2px solid #25D366; max-width: 450px;">
637
  <h3 style="color: #25D366; margin-bottom: 15px; font-size: 22px; font-weight: 900;">💬 Share Selected Notes</h3>
638
  <p style="font-size: 14px; color: var(--text-muted); margin-bottom: 20px;">Enter the mobile number to send notes.</p>
639
+
640
+ <!-- 🚨 FIXED SINGLE NUMBER INPUT 🚨 -->
641
  <input type="number" id="waNumberInput" placeholder="9876543210" class="standard" style="width: 100%; padding: 15px; font-weight: bold; font-size: 18px; margin-bottom: 25px; text-align: center; box-sizing: border-box;">
642
+
643
  <div style="display: flex; gap: 10px;">
644
  <button id="waSendBtn" class="btn" style="flex: 1; padding: 12px; border-radius: 12px; background: #10b981; color: white;" onclick="window.submitWhatsAppSelection(event)">🚀 Send</button>
645
  <button class="btn" style="flex: 1; padding: 12px; border-radius: 12px; background: #ef4444; color: white;" onclick="document.getElementById('whatsappModal').style.display='none'">✖ Cancel</button>
 
695
  <div id="publisherFinderModal" class="modal-overlay" style="z-index:99999998;">
696
  <div class="modal-box" style="max-width:480px; max-height:88vh; overflow-y:auto;">
697
  <h3 style="margin-top:0; color:var(--primary);">🔍 Find My Publisher</h3>
698
+ <p style="font-size:13px; color:var(--text-muted); margin-top:-8px;">Give us your class, subject, and any chapter names you know (skip the rest) — AI will identify your book's publisher.</p>
699
+
700
+ <label>Class:</label>
701
+ <select id="pfClass" class="standard">
702
+ <option value="" selected disabled>-- Select Class --</option>
703
+ <option value="Class 1">Class 1</option><option value="Class 2">Class 2</option>
704
+ <option value="Class 3">Class 3</option><option value="Class 4">Class 4</option>
705
+ <option value="Class 5">Class 5</option><option value="Class 6">Class 6</option>
706
+ <option value="Class 7">Class 7</option><option value="Class 8">Class 8</option>
707
+ <option value="Class 9">Class 9</option><option value="Class 10">Class 10</option>
708
+ <option value="Class 11">Class 11</option><option value="Class 12">Class 12</option>
709
+ </select>
710
+
711
+ <label>Subject:</label>
712
+ <input type="text" id="pfSubject" class="standard" placeholder="e.g. Science, Maths, Hindi...">
713
+
714
+ <label>Chapter Names (fill in as many as you know — skip the rest):</label>
715
+ <div style="display:flex; flex-direction:column; gap:8px; margin-bottom:10px;">
716
+ <input type="text" class="standard pf-chapter-input" style="margin-bottom:0;" placeholder="Chapter 1 (optional)">
717
+ <input type="text" class="standard pf-chapter-input" style="margin-bottom:0;" placeholder="Chapter 2 (optional)">
718
+ <input type="text" class="standard pf-chapter-input" style="margin-bottom:0;" placeholder="Chapter 3 (optional)">
719
+ <input type="text" class="standard pf-chapter-input" style="margin-bottom:0;" placeholder="Chapter 4 (optional)">
720
+ <input type="text" class="standard pf-chapter-input" style="margin-bottom:0;" placeholder="Chapter 5 (optional)">
721
+ <input type="text" class="standard pf-chapter-input" style="margin-bottom:0;" placeholder="Chapter 6 (optional)">
722
+ <input type="text" class="standard pf-chapter-input" style="margin-bottom:0;" placeholder="Chapter 7 (optional)">
723
+ <input type="text" class="standard pf-chapter-input" style="margin-bottom:0;" placeholder="Chapter 8 (optional)">
724
+ </div>
725
+
726
+ <div style="display:flex; align-items:center; gap:10px; margin:18px 0;">
727
+ <div style="flex:1; height:1px; background:var(--border-light);"></div>
728
+ <span style="font-size:12px; font-weight:900; color:var(--text-muted);">OR</span>
729
+ <div style="flex:1; height:1px; background:var(--border-light);"></div>
730
+ </div>
731
+
732
+ <button class="btn btn-secondary" style="width:100%; margin-bottom:15px;" onclick="window.openPublisherFinderCamera()">📷 Take Photo of Chapter List Instead</button>
733
+ <div id="pfPhotoPreviewWrap" style="display:none; margin-bottom:15px;">
734
+ <img id="pfPhotoPreview" style="width:100%; border-radius:12px; border:2px solid var(--primary); display:block;">
735
+ <button class="btn btn-secondary" style="width:100%; margin-top:8px;" onclick="window.clearPublisherFinderPhoto()">🗑️ Remove Photo</button>
736
+ </div>
737
+
738
+ <div id="pfStatusLabel" style="font-size:13px; font-weight:600; color:var(--text-muted); text-align:center; min-height:18px; margin-bottom:10px;"></div>
739
+
740
+ <button id="pfSearchBtn" class="btn btn-primary" style="width:100%; margin-bottom:10px;" onclick="window.runPublisherSearch()">🤖 AI Search Publisher</button>
741
+
742
+ <div id="pfResultBox" style="display:none; background:var(--input-bg); border:1px solid var(--primary); border-radius:12px; padding:15px; margin-bottom:15px; text-align:center;">
743
+ <div style="font-size:12px; color:var(--text-muted); text-transform:uppercase; font-weight:700;">Found Publisher:</div>
744
+ <div id="pfFoundName" style="font-size:18px; font-weight:800; color:var(--primary); margin-top:5px;"></div>
745
+ </div>
746
+
747
+ <div class="btn-row">
748
+ <button class="btn btn-secondary" style="flex:1;" onclick="window.closePublisherFinder()">Cancel</button>
749
+ <button class="btn" style="flex:1.5; background:#10b981; color:white;" onclick="window.donePublisherFinder()">✅ Done</button>
750
+ </div>
751
  </div>
752
  </div>
753
 
 
764
 
765
  <!-- 🚨 100% GLOBALLY BOUND SCRIPT BLOCK 🚨 -->
766
  <script>
767
+ // GLOBAL STATE VARIABLES (MUST BE AT THE TOP)
768
  localforage.config({ name: 'AI_Pro_Suite', storeName: 'massive_chat_history' });
769
  let appHistory = [];
770
  let currentSessionId = Number(new URLSearchParams(window.location.search).get('restore')) || Date.now();
 
773
  let currentTypewriterInterval = null;
774
  let isHindiUI = true;
775
  let selectedData = {};
776
+ let currentImages = []; // supports up to 10 attached images per message (was a single image before)
777
  const MAX_CHAT_IMAGES = 10;
778
+ let pfPhotoBase64 = null; // photo captured inside the Find Publisher tool
779
+ let voiceDictateTarget = 'chat'; // 'chat' -> chatInput box, 'chapter' -> manualChapter box
780
  let documentMemory = "";
781
  let webUrls = [];
782
  let cameraTarget = 'chat';
 
788
  let voiceText = "";
789
  let localSessionHTMLSize = 0;
790
 
791
+ // GLOBALLY BOUND UTILITIES
792
  window.showCustomAlert = function(msg) {
793
  document.getElementById('alertMessage').innerText = msg;
794
  document.getElementById('customAlertModal').style.display = 'flex';
 
802
  document.body.appendChild(t); setTimeout(() => { t.style.opacity = '0'; t.style.transition = '0.3s'; setTimeout(() => t.remove(), 300); }, 2500);
803
  }
804
 
805
+ // 🛑 AUTO RESTORE & SYNC LOOP INIT 🛑
806
  window.addEventListener('load', async function() {
807
+ // 🚨 FIX: force a clean, known UI state before any session restore runs.
808
+ // Previously nothing reset these, so a restored session could boot up showing
809
+ // a stray red X (close-wizard button) and a stuck TTS "stop" icon.
810
  document.getElementById('closeSettingsWizardBtn').style.display = 'none';
811
  window.stopAudio();
812
  window.resetSendButton();
813
 
 
 
 
 
 
 
 
 
 
 
814
  let ptiParam = new URLSearchParams(window.location.search).get('pti');
815
  if (ptiParam) {
816
  currentPti = ptiParam;
 
825
  if(session) {
826
  selectedData = session.data; currentSessionId = session.id;
827
  document.getElementById('sessionTitleDisplay').innerText = session.title || "📚 Book Deep Study";
828
+ document.getElementById('wizardPage').style.display = 'none'; document.getElementById('chatPage').style.display = 'flex';
829
+ document.getElementById('settingsBtn').style.display = 'block'; document.getElementById('clearBtn').style.display = 'block';
830
+ document.getElementById('shareBtn').style.display = 'block';
831
  document.getElementById('chatHistory').innerHTML = session.html;
832
  localSessionHTMLSize = session.html.length;
833
  setTimeout(() => { const c = document.getElementById('chatHistory'); c.scrollTo({top: c.scrollHeight, behavior: 'instant'}); }, 100);
 
838
  if(activeSession && activeSettings) {
839
  selectedData = JSON.parse(activeSettings);
840
  document.getElementById('sessionTitleDisplay').innerText = `${selectedData.subject} - ${selectedData.chapter}`;
841
+ document.getElementById('wizardPage').style.display = 'none'; document.getElementById('chatPage').style.display = 'flex';
842
+ document.getElementById('settingsBtn').style.display = 'block'; document.getElementById('clearBtn').style.display = 'block';
843
+ document.getElementById('shareBtn').style.display = 'block';
844
  document.getElementById('chatHistory').innerHTML = activeSession;
845
  localSessionHTMLSize = activeSession.length;
846
  setTimeout(() => { const c = document.getElementById('chatHistory'); c.scrollTo({top: c.scrollHeight, behavior: 'instant'}); }, 100);
 
 
 
 
847
  }
848
  }
849
  }
 
851
  window.startMarquee();
852
  });
853
 
854
+ // 🌐 LANGUAGE TOGGLE
855
  window.toggleAppLanguage = function() {
856
  window.closePlusMenu();
857
  isHindiUI = !isHindiUI;
858
  showToast(isHindiUI ? "🌐 Language set to Hindi" : "🌐 Language set to English");
859
  }
860
 
861
+ // 🛑 CLEAR CHAT ENGINE (FIXED) 🛑
862
  window.clearChat = function() {
863
  if(confirm("🗑️ Are you sure you want to completely clear this chapter's chat and memory?")) {
864
  document.getElementById('chatHistory').innerHTML = "";
 
868
  currentPti = null;
869
  localSessionHTMLSize = 0;
870
 
871
+ // Strip the PTI from URL without reloading
872
  const newUrl = `${window.location.origin}${window.location.pathname}`;
873
  window.history.replaceState({ path: newUrl }, '', newUrl);
874
 
875
+ document.getElementById('chatPage').style.display = 'none';
876
+ document.getElementById('wizardPage').style.display = 'block';
877
+ document.getElementById('settingsBtn').style.display = 'none';
878
+ document.getElementById('clearBtn').style.display = 'none';
879
+ document.getElementById('shareBtn').style.display = 'none';
880
+
881
  showToast("🗑️ Memory Wiped Clean.");
882
+ window.nextStep(1); // Kick back to start
883
  }
884
  };
885
 
886
+ // 🛑 MARQUEE TITLE LOGIC 🛑
887
  let marqueeInterval;
888
  window.startMarquee = function() {
889
  const titleEl = document.getElementById('sessionTitleDisplay');
 
939
  }
940
  }
941
 
942
+ // 🚨 FIX: resolves the REAL publisher name even when "Other (Custom)" is selected —
943
+ // previously every downstream call read publisherSelect.value directly, which for "Other" was
944
+ // literally the string "Other", never the name the user typed or the AI found.
945
+ window.getEffectivePublisher = function() {
946
+ let sel = document.getElementById('publisherSelect').value;
947
+ if (sel === 'Other') {
948
+ let custom = document.getElementById('customPublisherInput').value.trim();
949
+ return custom || 'Local/Unnamed Publisher';
950
+ }
951
+ return sel;
952
+ }
953
+
954
+ window.handlePublisherChange = function() {
955
+ let val = document.getElementById('publisherSelect').value;
956
+ const box = document.getElementById('customPublisherContainer');
957
+ if (val === 'Other') {
958
+ box.style.display = 'block';
959
+ } else {
960
+ box.style.display = 'none';
961
+ window.triggerSubjectFetch();
962
+ }
963
+ }
964
+ window.validateCustomPublisher = function() {
965
+ clearTimeout(window._pubDebounce);
966
+ window._pubDebounce = setTimeout(() => { window.triggerSubjectFetch(); }, 700);
967
+ }
968
+
969
+ window.nextStep = function(step) {
970
+ cameraTarget = 'chat';
971
+ if(step === 2 && !document.getElementById('publisherSelect').value) return window.showCustomAlert("Please Select Publisher!");
972
+ if(step === 3 && !document.getElementById('classSelect').value) return window.showCustomAlert("Please Select Class!");
973
+ if(step === 4 && !document.getElementById('subjectSelect').value) return window.showCustomAlert("Please Select Subject!");
974
+
975
+ document.querySelectorAll('.step-card').forEach(el => el.classList.remove('active'));
976
+ document.getElementById(`step-${step}`).classList.add('active');
977
+
978
+ if(step === 5) {
979
+ let pub = window.getEffectivePublisher();
980
+ let sub = document.getElementById('subjectSelect').value;
981
+ let cls = document.getElementById('classSelect').value;
982
+ let chapList = document.getElementById('chapterSelect').value;
983
+ let chapMan = document.getElementById('manualChapter').value;
984
+
985
+ if(sub === 'Other') sub = document.getElementById('customSubjectInput').value || "Custom Subject";
986
+
987
+ let finalChap = chapMan ? chapMan : chapList;
988
+ if(!finalChap) { window.nextStep(4); return window.showCustomAlert("Please select or type a chapter!"); }
989
+
990
+ selectedData = { publisher: pub, subject: sub, class: cls, chapter: finalChap };
991
+
992
+ document.getElementById('coverPub').innerText = pub;
993
+ document.getElementById('coverSub').innerText = sub;
994
+ document.getElementById('coverCls').innerText = cls;
995
+
996
+ if (bookRecognitionImageBase64) {
997
+ let coverDiv = document.getElementById('dynamicBookCover');
998
+ coverDiv.innerHTML = `<img src="${bookRecognitionImageBase64}" style="width:140px; height:190px; object-fit:cover; border-radius:8px; border:2px solid var(--primary); box-shadow:0 10px 20px rgba(0,0,0,0.5); margin:0 auto 20px auto; display:block;">`;
999
+ } else { window.fetchRealBookCover(pub, sub, cls); }
1000
+
1001
+ document.getElementById('selectionSummary').innerHTML = `<span style="color:var(--primary)">Publisher:</span> ${pub}<br><span style="color:var(--secondary)">Class:</span> ${cls}<br><span style="color:var(--accent)">Subject:</span> ${sub}<br><span style="color:#10b981">Chapter:</span> ${finalChap}`;
1002
+ }
1003
+ }
1004
 
1005
  window.openCameraChat = function() { cameraTarget = 'chat'; window.openCamera(); }
1006
  window.openBookRecognitionCamera = function() { cameraTarget = 'bookRecognition'; window.openCamera(); }
 
1048
  }
1049
  }
1050
 
1051
+ // 🖼️ MULTI-IMAGE ATTACHMENT ENGINE (up to 10 images per message, all sent to AI — not just the first)
1052
  window.renderImagePreviews = function() {
1053
  const row = document.getElementById('imgChipRow');
1054
  const wrap = document.getElementById('imagePreviewContainer');
 
1063
  }
1064
  window.removeImageAt = function(idx) { currentImages.splice(idx, 1); window.renderImagePreviews(); window.validateSendButton(); }
1065
 
1066
+ // 🔍 FIND PUBLISHER TOOL
1067
+ window.openPublisherFinder = function() {
1068
+ document.getElementById('publisherFinderModal').style.display = 'flex';
1069
+ document.getElementById('pfResultBox').style.display = 'none';
1070
+ document.getElementById('pfStatusLabel').innerText = '';
1071
+ window._pfFoundPublisher = null;
1072
+ let clsVal = document.getElementById('classSelect').value;
1073
+ if (clsVal) document.getElementById('pfClass').value = clsVal;
1074
+ }
1075
+ window.closePublisherFinder = function() { document.getElementById('publisherFinderModal').style.display = 'none'; }
1076
+ window.clearPublisherFinderPhoto = function() { pfPhotoBase64 = null; document.getElementById('pfPhotoPreviewWrap').style.display = 'none'; }
1077
+
1078
+ window.runPublisherSearch = async function() {
1079
+ const btn = document.getElementById('pfSearchBtn');
1080
+ const status = document.getElementById('pfStatusLabel');
1081
+ let cls = document.getElementById('pfClass').value;
1082
+ let sub = document.getElementById('pfSubject').value.trim();
1083
+ let chapters = Array.from(document.querySelectorAll('.pf-chapter-input')).map(i => i.value.trim()).filter(Boolean);
1084
+
1085
+ if (!cls && !sub && chapters.length === 0 && !pfPhotoBase64) {
1086
+ return window.showCustomAlert("Please provide at least a class, subject, some chapter names, or a photo.");
1087
+ }
1088
+
1089
+ btn.disabled = true; btn.innerHTML = "⏳ Searching...";
1090
+ document.getElementById('pfResultBox').style.display = 'none';
1091
+
1092
+ try {
1093
+ let extractedChapters = chapters;
1094
+ let extractedSubject = sub;
1095
+
1096
+ if (pfPhotoBase64) {
1097
+ status.innerText = "📷 Reading chapter names from photo...";
1098
+ const visionPrompt = "This is a photo of a textbook's table of contents / chapter list page. Extract the Subject name (if visible) and a JSON array of the chapter names you can read. Return ONLY valid JSON: {\"subject\": \"...\", \"chapters\": [\"...\"]}. No markdown, no extra text.";
1099
+ const vr = await fetch("/api/gemini-vision", { method: "POST", headers: {"Content-Type":"application/json"}, body: JSON.stringify({ imageBase64: pfPhotoBase64, userPrompt: visionPrompt }) });
1100
+ const vdata = await vr.json();
1101
+ let vjson = (vdata.text || "").replace(/```json/gi,'').replace(/```/g,'').trim();
1102
+ try {
1103
+ let parsed = JSON.parse(vjson);
1104
+ if (parsed.chapters && parsed.chapters.length) extractedChapters = extractedChapters.concat(parsed.chapters);
1105
+ if (!extractedSubject && parsed.subject) extractedSubject = parsed.subject;
1106
+ } catch(e) {}
1107
+ }
1108
+
1109
+ status.innerText = "🔎 Cross-referencing publisher databases...";
1110
+ const sysPrompt = `You are a textbook identification expert for the Indian school curriculum. Based on the details given, identify the most likely PUBLISHER or BOARD (e.g. NCERT, SCERT, Bihar Board, Bharti Bhawan, Sugam, Arvind Vigyan, New Way, S Chand, etc.) that publishes this exact book. Use real search results if you have access to them — do not guess blindly.
1111
+ Class: ${cls || 'Unknown'}
1112
+ Subject: ${extractedSubject || 'Unknown'}
1113
+ Chapter names provided: ${extractedChapters.length ? extractedChapters.join(', ') : 'None provided'}
1114
+ Return ONLY a raw JSON object: {"publisher": "Exact Publisher Name", "confidence": "high|medium|low"}. If you truly cannot determine it, return {"publisher": "", "confidence": "low"}. No markdown.`;
1115
+
1116
+ const r = await fetch("/api/gemini-text", { method: "POST", headers: {"Content-Type":"application/json"}, body: JSON.stringify({ systemPrompt: sysPrompt, userPrompt: "Identify the publisher.", useSearch: true }) });
1117
+ const data = await r.json();
1118
+ let cleanJson = (data.text || "").replace(/```json/gi,'').replace(/```/g,'').trim();
1119
+ let parsed = JSON.parse(cleanJson);
1120
+
1121
+ if (parsed.publisher) {
1122
+ document.getElementById('pfFoundName').innerText = parsed.publisher;
1123
+ document.getElementById('pfResultBox').style.display = 'block';
1124
+ status.innerText = `✅ Found (confidence: ${parsed.confidence || 'medium'})`;
1125
+ window._pfFoundPublisher = parsed.publisher;
1126
+ } else {
1127
+ status.innerText = "❌ Couldn't confidently identify it. Try adding more chapter names or a clearer photo.";
1128
+ }
1129
+ } catch(e) {
1130
+ status.innerText = "❌ Search failed. Please try again.";
1131
+ }
1132
+ btn.disabled = false; btn.innerHTML = "🤖 AI Search Publisher";
1133
+ }
1134
+
1135
+ window.donePublisherFinder = function() {
1136
+ let foundName = window._pfFoundPublisher || document.getElementById('pfFoundName').innerText.trim();
1137
+ if (foundName) {
1138
+ document.getElementById('publisherSelect').value = 'Other';
1139
+ document.getElementById('customPublisherContainer').style.display = 'block';
1140
+ document.getElementById('customPublisherInput').value = foundName;
1141
+ }
1142
+ if (document.getElementById('pfClass').value) document.getElementById('classSelect').value = document.getElementById('pfClass').value;
1143
+ window.closePublisherFinder();
1144
+ if (foundName) { showToast(`✅ Publisher set to "${foundName}"`); window.triggerSubjectFetch(); }
1145
+ else showToast("Closed publisher finder.");
1146
+ }
1147
 
1148
  window.retakeBookPhoto = function() { document.getElementById('bookPreviewModal').style.display = 'none'; window.openBookRecognitionCamera(); }
1149
  window.closeBookPreview = function() { document.getElementById('bookPreviewModal').style.display = 'none'; bookRecognitionImageBase64 = null; }
 
 
 
 
 
 
1150
 
1151
+ window.submitBookPhoto = async function() {
1152
+ document.getElementById('bookPreviewModal').style.display = 'none';
1153
+ document.getElementById('loadingPage').style.display = 'flex';
1154
+ document.getElementById('wizardPage').style.display = 'none';
1155
+
1156
+ let bar = document.getElementById('loadingBar'); let desc = document.getElementById('loadingDesc');
1157
+ bar.style.width = '20%'; desc.innerText = "Analyzing page structure...";
1158
+
1159
+ try {
1160
+ let prompt = "Extract the Subject Name and Chapter Name/Number from this textbook page image. Return ONLY a valid JSON object: {\"subject\": \"...\", \"chapter\": \"...\"}. Do not include markdown formatting.";
1161
+ const r = await fetch("/api/gemini-vision", { method: "POST", headers: {"Content-Type":"application/json"}, body: JSON.stringify({ imageBase64: bookRecognitionImageBase64, userPrompt: prompt }) });
1162
+ const data = await r.json();
1163
+ bar.style.width = '60%'; desc.innerText = "Extracting Chapter Details...";
1164
+
1165
+ let cleanJson = data.text.replace(/```json/gi, '').replace(/```/g, '').trim();
1166
+ let parsed = JSON.parse(cleanJson);
1167
+
1168
+ selectedData.subject = parsed.subject || document.getElementById('subjectSelect').value || "Unknown Subject";
1169
+ selectedData.chapter = parsed.chapter || "Extracted Chapter";
1170
+ selectedData.publisher = window.getEffectivePublisher() || "Unknown Publisher";
1171
+ selectedData.class = document.getElementById('classSelect').value || "Unknown Class";
1172
+
1173
+ bar.style.width = '100%';
1174
+ setTimeout(() => { window.startConversation(false); }, 300);
1175
+ } catch(e) {
1176
+ window.showCustomAlert("Failed to analyze image. Please type details manually.");
1177
+ document.getElementById('loadingPage').style.display = 'none';
1178
+ document.getElementById('wizardPage').style.display = 'block';
1179
+ }
1180
+ }
1181
+
1182
+ // 🚨 FIXED SUBJECT FETCH TO BE ULTRA STRICT 🚨
1183
+ window.triggerSubjectFetch = async function() {
1184
+ let pub = window.getEffectivePublisher(); let cls = document.getElementById('classSelect').value; let subSelect = document.getElementById('subjectSelect');
1185
+ if(!pub || !cls) return;
1186
+
1187
+ subSelect.innerHTML = '<option value="" selected disabled>-- 🤖 Fetching Subjects... --</option>';
1188
+ try {
1189
+ const sysPrompt = `You are a syllabus mapping expert. The user wants the EXACT subjects published for Class ${cls} by the publisher/board "${pub}".
1190
+ CRITICAL RULES:
1191
+ 1. ONLY return subjects that are ACTUALLY PUBLISHED by "${pub}" for Class ${cls}.
1192
+ 2. If "${pub}" is a specialized publisher (e.g. R.D. Sharma only does Mathematics), you MUST ONLY RETURN ["Mathematics"].
1193
+ 3. DO NOT hallucinate generic subjects if the publisher does not print them.
1194
+ 4. Return a raw JSON array of strings ONLY. Example: ["Mathematics", "Science"].`;
1195
+
1196
+ const r = await fetch("/api/gemini-text", { method: "POST", headers: {"Content-Type":"application/json"}, body: JSON.stringify({ systemPrompt: sysPrompt, userPrompt: `Fetch real subjects for ${cls} ${pub}`, useSearch: true }) });
1197
+ const data = await r.json(); let cleanJson = data.text.replace(/```json/gi, '').replace(/```/g, '').trim(); let fetchedSubjects = JSON.parse(cleanJson);
1198
+
1199
+ if(!Array.isArray(fetchedSubjects) || fetchedSubjects.length === 0) throw new Error("Fallback");
1200
+ subSelect.innerHTML = '<option value="" selected disabled>-- Select Subject --</option>';
1201
+ fetchedSubjects.forEach(sub => { subSelect.innerHTML += `<option value="${sub}">${sub}</option>`; });
1202
+ subSelect.innerHTML += `<option value="Other">Other Subject (Type Manually)</option>`;
1203
+ } catch(e) {
1204
+ subSelect.innerHTML = `<option value="" selected disabled>-- Select Subject --</option><option value="Science">Science</option><option value="Mathematics">Mathematics</option><option value="English">English</option><option value="English Grammar">English Grammar</option><option value="Hindi">Hindi</option><option value="History">History</option><option value="Geography">Geography</option><option value="Other">Other Subject (Type Manually)</option>`;
1205
+ }
1206
+ }
1207
+
1208
+ window.handleSubjectChange = function() {
1209
+ let sub = document.getElementById('subjectSelect').value;
1210
+ if(sub === 'Other') { document.getElementById('customSubjectContainer').style.display = 'block'; }
1211
+ else { document.getElementById('customSubjectContainer').style.display = 'none'; }
1212
+ window.triggerChapterFetch();
1213
+ }
1214
+
1215
+ window.triggerChapterFetch = async function() {
1216
+ let pub = window.getEffectivePublisher(); let sub = document.getElementById('subjectSelect').value; let cls = document.getElementById('classSelect').value; let chapSelect = document.getElementById('chapterSelect'); let statusLabel = document.getElementById('chapterFetchStatus');
1217
+ if(sub === 'Other') sub = document.getElementById('customSubjectInput').value;
1218
+
1219
+ if(!sub || !cls) { statusLabel.innerText = "Please select Subject and Class first."; statusLabel.style.color = "var(--text-muted)"; return; }
1220
+
1221
+ statusLabel.innerText = "⏳ Checking Database..."; chapSelect.innerHTML = '<option value="" selected disabled>-- 🤖 Fetching... --</option>';
1222
+ document.getElementById('initBtnStep4').style.display = 'block';
1223
+
1224
+ let isEnglishSub = ['English', 'English Grammar', 'Computer Science', 'Information Technology'].includes(sub);
1225
+ let targetLang = (isEnglishSub || !isHindiUI) ? 'ENGLISH' : 'HINDI (Devanagari script)';
1226
+
1227
+ try {
1228
+ const sysPrompt = `You are a syllabus expert. The user wants the EXACT chapter index for Class ${cls}, Subject ${sub}, Publisher ${pub}.
1229
+ CRITICAL: Do NOT return standard NCERT chapters if the publisher is ${pub}. You MUST search for the specific state board or private publisher index for ${pub}.
1230
+ Return JSON array of strings. Output strictly in ${targetLang}. ONLY output the raw JSON array.`;
1231
+
1232
+ const r = await fetch("/api/gemini-text", { method: "POST", headers: {"Content-Type":"application/json"}, body: JSON.stringify({ systemPrompt: sysPrompt, userPrompt: "Fetch chapters", useSearch: true }) });
1233
+ const data = await r.json(); let cleanJson = data.text.replace(/```json/gi, '').replace(/```/g, '').trim(); let fetchedChapters = JSON.parse(cleanJson);
1234
+ if(!Array.isArray(fetchedChapters)) throw new Error("Invalid Array");
1235
+
1236
+ if(fetchedChapters.length === 0) {
1237
+ chapSelect.innerHTML = '<option value="" selected disabled>-- ❌ Subject not found --</option>'; statusLabel.innerText = "Subject not found in database! Type manually below."; statusLabel.style.color = "#ef4444"; return;
1238
+ }
1239
+ statusLabel.style.color = "var(--text-muted)"; chapSelect.innerHTML = '<option value="" selected disabled>-- Select Chapter --</option>';
1240
+ fetchedChapters.forEach((chap, i) => { chapSelect.innerHTML += `<option value="Chapter ${i+1}: ${chap}">Chapter ${i+1}: ${chap}</option>`; });
1241
+ statusLabel.innerText = "Select Chapter (Generated by AI):";
1242
+ } catch(e) { statusLabel.innerText = "Select Chapter (Fetch Failed):"; chapSelect.innerHTML = '<option value="" selected disabled>-- ❌ Fetch Failed. Please type manually below --</option>'; }
1243
+ }
1244
+
1245
+ window.fetchChapterContext = async function() {
1246
+ try {
1247
+ const sysPrompt = `Search the internet for real textbook solutions for: Publisher: ${selectedData.publisher}, Class: ${selectedData.class}, Subject: ${selectedData.subject}, Chapter: ${selectedData.chapter}. Extract the ACTUAL end-of-chapter questions and answers from real sources you find — do not invent or guess them. Just store them internally. Do not output markdown.`;
1248
+ const r = await fetch("/api/gemini-text", { method: "POST", headers: {"Content-Type":"application/json"}, body: JSON.stringify({ systemPrompt: sysPrompt, userPrompt: `Find textbook exercises for ${selectedData.publisher} Class ${selectedData.class} ${selectedData.subject} ${selectedData.chapter}`, useSearch: true }) });
1249
+ const data = await r.json(); if(data.text) documentMemory = data.text;
1250
+ } catch(e) {}
1251
+ }
1252
+
1253
+ window.fetchRealBookCover = async function(pub, sub, cls) {
1254
+ if (bookRecognitionImageBase64) return;
1255
+ let coverDiv = document.getElementById('dynamicBookCover'); let statusSub = document.getElementById('coverSub');
1256
+ try {
1257
+ statusSub.innerText = "Searching...";
1258
+ let query = encodeURIComponent(`intitle:${sub} ${pub} class ${cls.replace('Class ','')}`);
1259
+ let res = await fetch(`https://www.googleapis.com/books/v1/volumes?q=${query}&maxResults=1`);
1260
+ let data = await res.json(); let thumb = null;
1261
+ if (data.items && data.items.length > 0 && data.items[0].volumeInfo.imageLinks) { thumb = data.items[0].volumeInfo.imageLinks.thumbnail.replace(/^http:\/\//i, 'https://'); }
1262
+ if (thumb) coverDiv.innerHTML = `<img src="${thumb}" style="width:140px; height:190px; object-fit:cover; border-radius:8px; border:2px solid var(--primary); box-shadow:0 10px 20px rgba(0,0,0,0.5); margin:0 auto 20px auto; display:block;">`;
1263
+ else statusSub.innerText = sub;
1264
+ } catch(e) { statusSub.innerText = sub; }
1265
+ }
1266
+
1267
+ // 🚨 RESTORED BLANK MESSAGE BLOCKER 🚨
1268
  window.validateSendButton = function() {
1269
  const inp = document.getElementById('chatInput');
1270
  const btn = document.getElementById('sendBtn');
 
1444
  window.togglePlusMenu = function(e) { e.stopPropagation(); const m = document.getElementById("plusMenu"); m.style.display = m.style.display === "flex" ? "none" : "flex"; }
1445
  window.closePlusMenu = function() { document.getElementById("plusMenu").style.display = "none"; }
1446
 
1447
+ window.openSettings = function() {
1448
+ document.getElementById('chatPage').style.display = 'none';
1449
+ document.getElementById('wizardPage').style.display = 'block';
1450
+
1451
+ // Hide the settings button when the menu is open
1452
+ document.getElementById('settingsBtn').style.display = 'none';
1453
+
1454
+ let chatContent = document.getElementById('chatHistory').innerHTML.trim();
1455
+ if (chatContent !== "") {
1456
+ document.getElementById('closeSettingsWizardBtn').style.display = 'flex';
1457
+ } else {
1458
+ document.getElementById('closeSettingsWizardBtn').style.display = 'none';
1459
+ }
1460
+ window.nextStep(1);
1461
+ }
1462
+
1463
+ window.closeSettingsWizard = function() {
1464
+ document.getElementById('wizardPage').style.display = 'none';
1465
+ document.getElementById('chatPage').style.display = 'flex';
1466
+
1467
+ // Bring the settings button back when the menu closes
1468
+ document.getElementById('settingsBtn').style.display = 'block';
1469
+ }
1470
 
1471
  window.handleEnter = function(e) { if(e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); if (document.getElementById('sendBtn').classList.contains('active-btn')) window.sendMessage(); } }
1472
 
1473
  window.openVoiceLang = function(target) { voiceDictateTarget = target || 'chat'; window.closePlusMenu(); document.getElementById('voiceLangModal').style.display='flex'; }
1474
+ let voiceFinalCount = 0; // 🚨 FIX: tracks how many "final" results we've already appended, independent of resultIndex
1475
  window.selectVoiceLang = function(lang) {
1476
  document.getElementById('voiceLangModal').style.display='none';
1477
  document.getElementById('voiceDictateModal').style.display='flex';
 
1485
  voiceRec.interimResults = true;
1486
 
1487
  voiceRec.onresult = (e) => {
1488
+ // 🚨 FIX (duplicate text bug): some mobile/webview browsers don't respect e.resultIndex and
1489
+ // resend all previous results on every callback. We now only append a "final" result once,
1490
+ // tracked by voiceFinalCount, instead of trusting e.resultIndex to avoid re-processing.
1491
  let interim = "";
1492
  for(let i = 0; i < e.results.length; i++) {
1493
  const transcript = e.results[i][0].transcript;
 
1506
  window.startDictation = function(e) { e.preventDefault(); if(e.stopPropagation) e.stopPropagation(); if(voiceRec && !isDictating) { isDictating = true; try { voiceRec.start(); } catch(err) {} holdBtn.innerHTML = "🎙️ Listening..."; holdBtn.style.background = "#ef4444"; } }
1507
  window.stopDictation = function(e) { e.preventDefault(); if(e.stopPropagation) e.stopPropagation(); if(voiceRec && isDictating) { isDictating = false; voiceRec.stop(); holdBtn.innerHTML = "👆 Hold to Speak"; holdBtn.style.background = "var(--primary)"; } }
1508
 
1509
+ // 🚨 FIX: touchstart + mousedown both firing on the same tap (mobile) caused the mic to start/stop
1510
+ // twice in quick succession. isDictating guard above + passive:false + preventDefault stops the
1511
+ // synthetic mouse event from double-triggering.
1512
  holdBtn.addEventListener('touchstart', window.startDictation, {passive:false});
1513
  holdBtn.addEventListener('mousedown', window.startDictation);
1514
  holdBtn.addEventListener('touchend', window.stopDictation); holdBtn.addEventListener('mouseup', window.stopDictation); holdBtn.addEventListener('mouseleave', window.stopDictation);
1515
 
1516
  window.commitVoice = function() {
1517
+ // 🚨 FIX: previously always wrote into #chatInput even when opened from the chapter-name mic button.
1518
  const targetId = voiceDictateTarget === 'chapter' ? 'manualChapter' : 'chatInput';
1519
  const targetEl = document.getElementById(targetId);
1520
  const spoken = document.getElementById('voiceDictateText').value.trim();
 
1559
  window.speechSynthesis.speak(window.activeUtterance);
1560
  };
1561
 
1562
+ // =========================================================================
1563
+ // 🧠 PTI SYNC ENGINE CODES
1564
+ // ==========================================================================
1565
  window.fetchAndInjectPtiSession = async function(ptiString) {
1566
  try {
1567
  const response = await fetch(`/api/pti-get?pti=${ptiString}`);
 
1574
 
1575
  document.getElementById('sessionTitleDisplay').innerText = sessionRecord.title || "📚 Book Deep Study";
1576
 
1577
+ // 🚨 FIXED: BYPASS WIZARD ENTIRELY ON MOBILE LINK LOAD 🚨
1578
+ document.getElementById('wizardPage').style.display = 'none';
1579
  document.getElementById('chatPage').style.display = 'flex';
1580
+ document.getElementById('settingsBtn').style.display = 'block';
1581
  document.getElementById('clearBtn').style.display = 'block';
1582
  document.getElementById('shareBtn').style.display = 'block';
1583
 
 
1587
  window.startMarquee();
1588
  } catch (e) {
1589
  showToast("❌ Unable to locate active PTI profile.");
1590
+ console.error("Fetch Error:", e);
1591
  }
1592
  }
1593
 
 
1639
  const newUrl = `${window.location.origin}${window.location.pathname}?pti=${currentPti}`;
1640
  window.history.replaceState({ path: newUrl }, '', newUrl);
1641
  }
1642
+ })
1643
+ .catch(err => console.error("Cloud Sync Failed:", err));
1644
  }
1645
 
1646
+ // 🚨 RESTORED INITIAL MESSAGES AND DIVIDERS 🚨
1647
  window.startConversation = async function(forceNew = false, forceClear = false) {
1648
+ let oldSettingsStr = localStorage.getItem('bookSettings_VUltimateAI');
1649
+ let oldHistory = localStorage.getItem('bookChatHistory_VUltimateAI');
1650
+ let isNewChapter = false;
1651
+
1652
+ if (oldSettingsStr && oldHistory) {
1653
+ let oldSettings = JSON.parse(oldSettingsStr);
1654
+ if (oldSettings.chapter !== selectedData.chapter || oldSettings.subject !== selectedData.subject) isNewChapter = true;
1655
+ }
1656
+
1657
  if (forceClear) {
1658
  document.getElementById('chatHistory').innerHTML = ""; localStorage.removeItem('bookChatHistory_VUltimateAI'); currentSessionId = Date.now();
1659
+ } else if (isNewChapter) {
1660
+ document.getElementById('chatHistory').insertAdjacentHTML('beforeend', `<div class="chapter-divider">--- Started New Session: ${selectedData.chapter} ---</div>`);
1661
  }
1662
 
1663
+ document.getElementById('wizardPage').style.display = 'none';
1664
  document.getElementById('loadingPage').style.display = 'flex';
1665
 
1666
  let bar = document.getElementById('loadingBar'); let desc = document.getElementById('loadingDesc');
1667
+ bar.style.width = '30%'; desc.innerText = "Connecting to AI Core...";
1668
+ await new Promise(r => setTimeout(r, 400));
1669
+ bar.style.width = '60%'; desc.innerText = "Analyzing Chapter Context...";
1670
+ await window.fetchChapterContext();
1671
+ bar.style.width = '90%'; desc.innerText = "Setting up Tutor Interface...";
1672
  await new Promise(r => setTimeout(r, 400));
1673
  bar.style.width = '100%';
1674
 
1675
  setTimeout(async () => {
1676
  document.getElementById('loadingPage').style.display = 'none';
1677
  document.getElementById('chatPage').style.display = 'flex';
1678
+ document.getElementById('settingsBtn').style.display = 'block';
1679
  document.getElementById('clearBtn').style.display = 'block';
1680
  document.getElementById('shareBtn').style.display = 'block';
1681
 
1682
+ document.getElementById('sessionTitleDisplay').innerText = `${selectedData.subject} - ${selectedData.chapter}`;
1683
  window.startMarquee();
1684
  localStorage.setItem('bookSettings_VUltimateAI', JSON.stringify(selectedData));
1685
 
1686
+ if(document.getElementById('chatHistory').innerHTML.trim() === "" || isNewChapter) {
1687
+ let isEnglishSub = ['English', 'English Grammar', 'Computer Science', 'Information Technology'].includes(selectedData.subject);
1688
+ let initialMessageHTML = (isEnglishSub || !isHindiUI) ?
1689
+ `Hello! I am your AI Tutor. <br><br>We are ready to discuss Chapter **"${selectedData.chapter}"** of **${selectedData.subject}** (${selectedData.class}). <br><br>**I will respond in English by default.**<br>*Note: If you ask to solve a specific exercise, I will check the real textbook data first!*<br><br>
1690
  <div class="preset-chips" style="margin-top: 15px;">
1691
+ <button class="preset-btn" onclick="window.runPreset('Generate detailed study notes for this chapter.')">📝 Generate Notes</button>
1692
+ <button class="preset-btn" onclick="window.runPreset('Create 10 important MCQs from this chapter with answers.')">✅ Objectives</button>
1693
+ <button class="preset-btn" onclick="window.runPreset('Analyze this chapter in simple terms.')">📊 Analyze Chapter</button>
1694
  </div>`
1695
  :
1696
+ `नमस्ते! मैं आपका एआई शिक्षक हूँ। <br><br>हम **${selectedData.class}** के **${selectedData.subject}** विषय के अध्याय **"${selectedData.chapter}"** पर चर्चा करने के लिए तैयार हैं। <br><br>**मैं आपके सभी सवालों के जवाब डिफ़ॉल्ट रूप से हिंदी में दूँगा।**<br><br>
1697
  <div class="preset-chips" style="margin-top: 15px;">
1698
+ <button class="preset-btn" onclick="window.runPreset('इस अध्याय के लिए विस्तृत और आसान नोट्स बनाएं।')">📝 जनरेट नोट्स</button>
1699
+ <button class="preset-btn" onclick="window.runPreset('इस अध्याय से 10 महत्वपूर्ण बहुविकल्पीय प्रश्न (MCQ) बनाएं और उत्तर भी दें।')">✅ ऑब्जेक्टिव प्रश्न</button>
1700
+ <button class="preset-btn" onclick="window.runPreset('इस अध्याय का विस्तार से और आसान भाषा में विश्लेषण करें।')">📊 अध्याय का विश्लेषण</button>
1701
  </div>`;
1702
 
1703
  await window.addAiMessage(initialMessageHTML, false);
 
1708
  window.sendMessage = async function() {
1709
  const inputEl = document.getElementById('chatInput');
1710
  const text = inputEl.value.trim();
1711
+ const imgs = currentImages.slice(); // snapshot all attached images (up to 10) before we clear the input
1712
  const btn = document.getElementById('sendBtn');
1713
 
1714
  if(!btn.classList.contains('active-btn')) return;
 
1730
  document.getElementById('chatHistory').appendChild(loadDiv);
1731
  c.scrollTo({top: c.scrollHeight, behavior: 'smooth'});
1732
 
1733
+ // 🧠 REAL "THINKING" STAGES — cycles through what the tutor is actually doing while it waits on the AI
1734
+ const thinkingStages = imgs.length ? ["Understanding your question…", "Reading the attached image" + (imgs.length > 1 ? "s…" : "…"), "Checking chapter memory…", "Drafting the answer…"]
1735
+ : ["Understanding your question…", "Checking chapter memory…", "Searching for the exact textbook wording…", "Drafting the answer…"];
1736
  let stageIdx = 0;
1737
  const statusEl = () => document.getElementById(`${loadingId}_status`);
1738
  const thinkingInterval = setInterval(() => {
 
1749
  let msgText = clone.innerText.trim().replace(/\s+/g, ' '); if(msgText) recentHistory += `${role}: ${msgText}\n`;
1750
  }
1751
 
1752
+ let isEnglishSub = ['English', 'English Grammar', 'Computer Science', 'Information Technology'].includes(selectedData.subject);
1753
+ let targetLang = (isEnglishSub || !isHindiUI) ? 'ENGLISH' : 'HINDI (Devanagari script)';
1754
+ let isMathSub = ['Mathematics', 'Physics', 'Chemistry', 'Science'].includes(selectedData.subject);
1755
 
1756
+ // 🚨 STRICT NO HASHTAG AND BOLD QUESTION RULES APPLIED 🚨
1757
+ let sysPrompt = `You are a premium AI expert educational tutor. Answer entirely in ${targetLang}. Context: Publisher: ${selectedData.publisher}, ${selectedData.class}, Subject: ${selectedData.subject}, Chapter: "${selectedData.chapter}".
1758
  STRICT RULES:
1759
  1. NO HASHTAGS (#) allowed anywhere. Use ** for bolding.
1760
  2. ALWAYS rewrite the user's core question at the very beginning of your answer in BOLD.
1761
  3. NO RAW UNITS like \\text{m/s}^2. Use standard text.
1762
+ 4. If asked for exact textbook exercise questions/answers, use the real search results available to you — do not invent or guess exercise numbers or wording.`;
1763
+
1764
+ // 🚨 RESTORED SVGS AND MATH FRACTIONS 🚨
1765
+ if (isMathSub) {
1766
+ sysPrompt += `\n\n🚨 MATH TEMPLATE: For calculation questions, follow exactly:
1767
+ **1. [Step 1 Heading]**
1768
+ [Step 1 explanation in full words]
1769
+ $$[Equation without using \\frac]$$
1770
+ **✅ Final Answer**
1771
+ [Final sentence in ${targetLang}]`;
1772
+
1773
+ sysPrompt += `\n\n🎨 VISUAL RULE: IF the question relates to Geometry, Physics concepts, Chemistry structures, or visual Math, YOU MUST generate a highly detailed, colorful <svg> diagram wrapped exactly in <div class="math-svg-wrap"><svg>...</svg></div>.`;
1774
+ } else {
1775
+ sysPrompt += `\n\nIF SUBJECT IS NOT MATH OR SCIENCE, DO NOT INVENT MATH FORMULAS.`;
1776
+ }
1777
 
1778
  if(recentHistory) sysPrompt += `\n\n--- CHAT HISTORY ---\n${recentHistory}`;
1779
+ if (documentMemory) sysPrompt += `\n\n--- INBUILT CHAPTER MEMORY (real textbook search results — trust this over your own memory) ---\n${documentMemory.substring(0, 40000)}`;
1780
 
1781
  let payloadImgs = imgs;
1782
+ if (!payloadImgs.length && bookRecognitionImageBase64) { payloadImgs = [bookRecognitionImageBase64]; sysPrompt += `\nCRITICAL: Extract the text/questions strictly from the provided image.`; }
1783
 
1784
  const payload = payloadImgs.length
1785
  ? { imageBase64: payloadImgs[0], imageBase64Array: payloadImgs, userPrompt: text || "Please solve the questions visible in all the attached images.", systemPrompt: sysPrompt }
1786
+ : { userPrompt: text || "Please provide the chapter exercises.", systemPrompt: sysPrompt, useSearch: true };
1787
 
1788
  try {
1789
  currentAbortController = new AbortController();
 
1805
  }
1806
  }
1807
 
1808
+ // 🚨 FIXED MARKDOWN PARSER (NO REGEX CORRUPTION) 🚨
1809
  window.addAiMessage = async function(text, typewrite = false) {
1810
  const msgDiv = document.createElement("div"); msgDiv.className = "msg ai";
1811
  const bubble = document.createElement("div"); bubble.className = "bubble";
1812
  msgDiv.appendChild(bubble); document.getElementById('chatHistory').appendChild(msgDiv);
1813
 
1814
+ // Remove LaTeX fractions before markdown parse
1815
  let cleanText = text.replace(/\\frac{([^}]+)}{([^}]+)}/g, '$1/$2').replace(/\\times/g, '×');
1816
  let formattedHTML = marked.parse(cleanText);
1817
 
1818
+ // 🚨 FIX: single ID generated once and reused for both the div AND the Listen button's data-target
1819
+ // (previously two separate Date.now() calls almost never matched, so clicking "Listen" silently failed)
1820
  const ttsId = `tts_${Date.now()}_${Math.floor(Math.random()*10000)}`;
1821
  let btnHtml = `<br><button class="listen-btn" onclick="window.playAudio(this)" data-target="${ttsId}">🔊 Listen</button>`;
1822
 
 
1841
  currentHTML += formattedHTML.substring(i, end + 1);
1842
  i = end + 1;
1843
  txtBox.innerHTML = currentHTML;
1844
+ return; // Skip over HTML tags instantly
1845
  }
1846
  }
1847
 
 
1860
 
1861
  window.saveHistorySafe(); window.triggerCloudSyncEngine(); window.resetSendButton();
1862
  }
 
 
 
 
 
 
 
 
1863
  }
1864
  </script>
 
1865
  </body>
1866
  </html>