Transaltor / books.html
Aichatbot12321's picture
Upload 27 files
84e1dd3 verified
Raw History Blame Contribute Delete
124 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>Book Deep Study</title> <link rel="manifest" href="/manifest.json"> <meta name="theme-color" content="#0f172a"> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap" rel="stylesheet"> <link rel="stylesheet" href="style.css"> <script src="https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.min.js"></script> <script>pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.worker.min.js';</script> <script src="https://cdn.jsdelivr.net/npm/marked@4.3.0/marked.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.js"></script> <script> MathJax = { options: { ignoreHtmlClass: 'code-box', processHtmlClass: 'markdown-body' }, tex: { inlineMath: [['$', '$'], ['\\(', '\\)']], displayMath: [['$$', '$$'], ['\\[', '\\]']] }, svg: { fontCache: 'global' }, chtml: { displayAlign: 'left' } }; </script> <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script> <STYLE> /* 1. AUTO LIGHT/DARK THEME SYSTEM */ :root { /* DEFAULT LIGHT MODE */ --app-bg: #f8fafc; --bg-base: #f8fafc; --bg-surface: rgba(255, 255, 255, 0.85); --input-bg: #ffffff; --primary: #3b82f6; --primary-glow: rgba(59, 130, 246, 0.25); --secondary: #6366f1; --accent: #10b981; --text-main: #0f172a; --text-muted: #64748b; --border-light: rgba(0, 0, 0, 0.1); --chat-user-bg: linear-gradient(135deg, #3b82f6, #2563eb); --chat-user-text: #ffffff; --chat-ai-bg: rgba(255, 255, 255, 0.9); --chat-ai-border: rgba(0, 0, 0, 0.1); --backdrop-blur: blur(16px); } @media (prefers-color-scheme: dark) { :root { /* OVERRIDE WITH DARK MODE */ --app-bg: #090d16; --bg-base: #090d16; --bg-surface: rgba(20, 29, 47, 0.85); --input-bg: rgba(13, 20, 35, 0.6); --text-main: #f8fafc; --text-muted: #94a3b8; --border-light: rgba(255, 255, 255, 0.08); --chat-ai-bg: rgba(22, 32, 54, 0.5); --chat-ai-border: rgba(255, 255, 255, 0.06); } } /* Global Foundations */ html, body { height: 100%; width: 100%; overflow: hidden; margin: 0; padding: 0; font-family: 'Poppins', sans-serif; background: var(--app-bg); color: var(--text-main); -webkit-font-smoothing: antialiased; transition: background-color 0.3s ease, color 0.3s ease; } /* 2. TOPBAR FIXES (Resizing & Squeezing) */ .topbar { position: fixed; top: 0; left: 0; width: 100%; z-index: 500; transition: transform 0.4s ease; display: flex; justify-content: space-between; align-items: center; padding: 12px 20px; background: var(--bg-surface); border-bottom: 1px solid var(--border-light); backdrop-filter: var(--backdrop-blur); -webkit-backdrop-filter: var(--backdrop-blur); box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05); box-sizing: border-box; gap: 10px; } .topbar.hidden { transform: translateY(-100%); } .appTitle-container { flex: 1; overflow-x: auto; white-space: nowrap; margin: 0 10px; position: relative; border-radius: 8px; cursor: pointer; touch-action: pan-x; scrollbar-width: none; } .appTitle-container::-webkit-scrollbar { display: none; } .appTitle { font-size: 16px; font-weight: 700; color: var(--text-main); display: inline-block; padding: 2px 0; } .topbar-actions { display: flex; gap: 8px; flex-shrink: 0; align-items: center; } /* Universal Buttons */ .btn { padding: 10px 16px; font-weight: 600; border-radius: 12px; border: 1px solid transparent; cursor: pointer; transition: all 0.2s ease; font-size: 14px; display: inline-flex; align-items: center; justify-content: center; gap: 6px; } .btn-primary { background: linear-gradient(135deg, var(--primary), var(--secondary)); color: white; box-shadow: 0 4px 12px var(--primary-glow); } .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 6px 16px var(--primary-glow); filter: brightness(1.1); } .btn-secondary { background: var(--input-bg); color: var(--text-main) !important; border: 1px solid var(--border-light); } .btn-secondary:hover { background: var(--border-light); transform: translateY(-2px); } /* 3. WIZARD & SETTINGS CONTROLS (X Button & Language Icon) */ .wizard-container { display: flex; flex-direction: column; align-items: center; justify-content: flex-start; padding: 24px; padding-top: 90px; padding-bottom: 40px; width: 100%; box-sizing: border-box; overflow-y: auto; height: 100vh; position: relative; } .step-card { width: 100%; max-width: 500px; display: none; background: var(--bg-surface); padding: 30px; border-radius: 20px; backdrop-filter: var(--backdrop-blur); -webkit-backdrop-filter: var(--backdrop-blur); box-shadow: 0 10px 40px rgba(0,0,0,0.15); border: 1px solid var(--border-light); box-sizing: border-box; margin-bottom: 30px; position: relative; animation: popInCard 0.4s cubic-bezier(0.34, 1.56, 0.64, 1); } .step-card.active { display: block; } .step-card h2 { color: var(--text-main); margin-top: 0; margin-bottom: 20px; font-weight: 800; font-size: 22px; } .step-card label { display: block; text-align: left; margin-bottom: 8px; font-weight: 600; color: var(--primary); text-transform: uppercase; font-size: 12px; } /* Fixed Settings Close (X) & Language Buttons */ #closeSettingsWizardBtn { display: none; position: fixed; top: 16px; left: 16px; background: var(--bg-surface); border: 1px solid var(--border-light); color: var(--text-main); width: 42px; height: 42px; border-radius: 50%; font-size: 18px; font-weight: bold; cursor: pointer; transition: all 0.2s ease; z-index: 600; box-shadow: 0 4px 10px rgba(0,0,0,0.1); align-items: center; justify-content: center; backdrop-filter: var(--backdrop-blur); } #closeSettingsWizardBtn:hover { background: #ef4444; color: white; border-color: #ef4444; } .floating-lang-btn { position: fixed; top: 16px; right: 16px; font-size: 20px; background: var(--bg-surface); border: 1px solid var(--border-light); border-radius: 50%; width: 42px; height: 42px; cursor: pointer; transition: all 0.3s ease; z-index: 600; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 10px rgba(0,0,0,0.1); backdrop-filter: var(--backdrop-blur); } .floating-lang-btn:hover { transform: scale(1.1) rotate(15deg); background: var(--primary-glow); } /* Premium Form Elements */ select.standard, input.standard, textarea.standard { width: 100%; padding: 14px 16px; border-radius: 12px; border: 1px solid var(--border-light); background: var(--input-bg); color: var(--text-main); font-size: 15px; margin-bottom: 20px; box-sizing: border-box; outline: none; transition: all 0.2s ease; font-family: inherit; } select.standard:focus, input.standard:focus, textarea.standard:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--primary-glow); } /* 4. FIXING CHAPTER CAMERA/MIC ROW */ .chapter-input-row { display: flex; gap: 10px; align-items: center; margin-bottom: 20px; width: 100%; } .chapter-input-row input { margin-bottom: 0 !important; flex: 1; min-width: 0; } .chapter-icon-btn { background: var(--primary); color: white; border: none; border-radius: 12px; width: 50px; height: 50px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; font-size: 20px; cursor: pointer; transition: 0.2s ease; } .chapter-icon-btn.green { background: var(--accent); } .chapter-icon-btn:hover { transform: scale(1.05); filter: brightness(1.1); } /* Chat Layout */ #chatPage { display: none; flex-direction: column; position: fixed; inset: 0; background: var(--bg-base); z-index: 50; overflow: hidden; } .chat-scroll-area { flex: 1; overflow-y: auto; padding: 20px; padding-top: 85px; display: flex; flex-direction: column; gap: 16px; scroll-behavior: smooth; } .msg { display: flex; width: 100%; flex-direction: column; animation: floatUp 0.3s ease forwards; } .user { align-items: flex-end; } .ai { align-items: flex-start; } .bubble { max-width: 85%; padding: 14px 20px; border-radius: 18px; line-height: 1.6; font-size: 15px; position: relative; box-shadow: 0 4px 15px rgba(0,0,0,0.08); word-wrap: break-word; padding-right: 45px !important; overflow: visible !important; } .user .bubble { background: var(--chat-user-bg) !important; color: var(--chat-user-text) !important; border-bottom-right-radius: 4px; } .ai .bubble { background: var(--chat-ai-bg) !important; color: var(--text-main) !important; border: 1px solid var(--chat-ai-border) !important; border-bottom-left-radius: 4px; backdrop-filter: var(--backdrop-blur); -webkit-backdrop-filter: var(--backdrop-blur); } .bubble img { max-width: 100%; border-radius: 10px; margin-top: 10px; border: 1px solid var(--border-light); } .chapter-divider { text-align: center; color: var(--text-muted); font-weight: 700; font-size: 11px; margin: 20px 0; text-transform: uppercase; letter-spacing: 1px; position: relative; } .chapter-divider::before, .chapter-divider::after { content: ''; position: absolute; top: 50%; width: 15%; height: 1px; background: var(--border-light); } .chapter-divider::before { left: 0; } .chapter-divider::after { right: 0; } .user-copy-btn { position: absolute; top: -10px; left: -10px; background: var(--bg-surface); color: var(--text-main); border: 1px solid var(--border-light); border-radius: 50%; width: 28px; height: 28px; font-size: 12px; cursor: pointer; display: none; justify-content: center; align-items: center; box-shadow: 0 2px 5px rgba(0,0,0,0.2); transition: 0.2s; z-index: 10; } .user-copy-btn:hover { background: var(--primary); color: white; transform: scale(1.1); } .user .bubble:hover .user-copy-btn { display: flex; animation: popUp 0.2s ease; } .preset-chips { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 12px; } .preset-btn { background: var(--input-bg); border: 1px solid var(--primary); color: var(--primary); padding: 8px 12px; border-radius: 16px; font-size: 12px; font-weight: 600; cursor: pointer; transition: 0.2s; } .preset-btn:hover { background: var(--primary); color: white; transform: translateY(-2px); } .listen-btn { background: linear-gradient(135deg, #10b981, #059669); color: white; border-radius: 20px; padding: 6px 14px; display: inline-flex; align-items: center; gap: 6px; box-shadow: 0 4px 10px rgba(16,185,129,0.2); transition: 0.2s; border: none; font-weight: 600; font-size: 12px; cursor: pointer; margin-top: 10px; text-transform: uppercase; } .listen-btn:hover { transform: translateY(-2px); box-shadow: 0 6px 15px rgba(16,185,129,0.3); } /* Bottom Chat Input Controls */ .bottom-action-container { flex-shrink: 0; width: 100%; background: var(--bg-surface); backdrop-filter: var(--backdrop-blur); -webkit-backdrop-filter: var(--backdrop-blur); border-top: 1px solid var(--border-light); display: flex; flex-direction: column; box-sizing: border-box; padding: 12px 16px; padding-bottom: calc(12px + env(safe-area-inset-bottom)); z-index: 100; position: relative; } .chat-input-wrapper { display: flex; align-items: center; gap: 8px; width: 100%; box-sizing: border-box; background: var(--input-bg); border: 1px solid var(--border-light); border-radius: 24px; padding: 6px 12px; transition: 0.2s ease; } .chat-input-wrapper:focus-within { border-color: var(--primary); box-shadow: 0 0 0 3px var(--primary-glow); } textarea { flex: 1; background: transparent; border: none; color: var(--text-main); font-family: inherit; font-size: 15px; resize: none; padding: 8px 0; outline: none; min-height: 24px; max-height: 120px; } .icon-btn { background: transparent; border: none; color: var(--primary); font-size: 20px; cursor: pointer; padding: 6px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; transition: 0.2s; border-radius: 50%; } .icon-btn:hover { background: var(--border-light); } .send-btn { background: var(--border-light); color: var(--text-muted); border-radius: 50%; width: 36px; height: 36px; padding: 0; margin-left: 4px; flex-shrink: 0; pointer-events: none; transition: 0.2s; opacity: 0.5; } .send-btn.active-btn { background: linear-gradient(135deg, var(--primary), var(--secondary)); color: white; box-shadow: 0 4px 10px var(--primary-glow); pointer-events: auto; opacity: 1; } .send-btn.active-btn:hover { transform: scale(1.1); } .send-btn.stop-btn { background: #ef4444 !important; pointer-events: auto; animation: pulse 1s infinite alternate; opacity: 1; color: white;} /* Plus Menu & Modals */ .glass-panel { background: var(--bg-surface); backdrop-filter: var(--backdrop-blur); border: 1px solid var(--border-light); box-shadow: 0 10px 30px rgba(0,0,0,0.3); } #plusMenu { display: none; position: absolute; bottom: 70px; left: 16px; border-radius: 16px; flex-direction: column; z-index: 200; width: 220px; animation: popUp 0.2s ease; overflow: hidden; } .menu-item { background: transparent; border: none; color: var(--text-main); padding: 14px; text-align: left; font-size: 14px; font-weight: 600; cursor: pointer; border-bottom: 1px solid var(--border-light); display: flex; align-items: center; gap: 10px; transition: 0.2s; } .menu-item:hover { background: var(--primary-glow); padding-left: 18px; } .menu-item:last-child { border-bottom: none; } .modal-overlay { display:none; position:fixed; inset:0; background:rgba(0,0,0,0.7); z-index:9999999; justify-content:center; align-items:center; backdrop-filter: blur(5px); } .modal-box { background:var(--bg-surface); width:90%; max-width:400px; padding:25px; border-radius:20px; position:relative; border: 1px solid var(--border-light); box-shadow: 0 15px 40px rgba(0,0,0,0.4); animation: popUp 0.3s ease; } /* Message Dropdowns */ .msg-menu-wrap { position: absolute; top: 10px; right: 8px; z-index: 10; display: flex; gap: 4px;} .msg-action-btn { background: transparent; border: none; color: inherit; opacity: 0.5; cursor: pointer; font-size: 16px; padding: 2px; transition:0.2s;} .msg-action-btn:hover { opacity: 1; transform: scale(1.1); } .msg-dropdown { display: none; position: absolute; right: 0; top: 24px; background: var(--bg-surface); border: 1px solid var(--border-light); border-radius: 8px; box-shadow: 0 5px 15px rgba(0,0,0,0.3); overflow: hidden; min-width: 100px; z-index: 1000; } .msg-dropdown button { width: 100%; background: transparent; border: none; color: #ef4444; padding: 10px 14px; text-align: left; font-size: 13px; font-weight: bold; cursor: pointer; } .msg-dropdown button:hover { background: rgba(239,68,68,0.1); } /* Misc UI */ .sidebar { position: fixed; top: 0; left: 0; transform: translateX(-100%); width: 280px; height: 100vh; background: var(--bg-base); border-right: 1px solid var(--border-light); box-shadow: 20px 0 40px rgba(0,0,0,0.2); z-index: 999999; transition: transform 0.3s ease; padding: 20px 15px; box-sizing: border-box; display: flex; flex-direction: column; gap: 8px; } .sidebar.active { transform: translateX(0); } .overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 999998; display: none; opacity: 0; transition: 0.3s; } .overlay.active { display: block; opacity: 1; } .status-chip { display: none; align-items: center; gap: 8px; background: var(--primary-glow); color: var(--primary); padding: 6px 14px; border-radius: 20px; font-size: 12px; font-weight: bold; width: max-content; border: 1px solid var(--primary); margin-bottom: 10px; animation: slideIn 0.3s ease; } #imagePreviewContainer { position: relative; margin-bottom: 10px; display: none; width: 100%; } .img-chip-row { display: flex; gap: 8px; flex-wrap: wrap; } .img-chip-item { position: relative; flex-shrink: 0; } .img-chip { width: 60px; height: 60px; border-radius: 10px; object-fit: cover; border: 2px solid var(--primary); display: block; } .img-chip-item .remove-img-btn { position: absolute; top: -6px; right: -6px; background: #ef4444; color: #fff; border: 2px solid var(--bg-base); width: 20px; height: 20px; border-radius: 50%; font-size: 11px; display: flex; align-items: center; justify-content: center; cursor: pointer; padding: 0; } .img-count-badge { font-size: 11px; font-weight: 700; color: var(--text-muted); margin-top: 4px; } .math-svg-wrap { background: #ffffff !important; border-radius: 12px; padding: 15px; margin: 15px 0; text-align: center; overflow-x: auto; box-shadow: 0 4px 12px rgba(0,0,0,0.1); border: 2px solid var(--primary); } .math-svg-wrap svg { max-width: 100%; height: auto; border-radius: 8px; } .markdown-body h1, .markdown-body h2, .markdown-body h3 { margin-top: 0; color: inherit; font-weight: 700; } .markdown-body strong { font-weight: 700; color: inherit; } @keyframes floatUp { 0% { opacity:0; transform:translateY(15px); } 100% { opacity:1; transform:translateY(0); } } @keyframes popInCard { 0% { opacity: 0; transform: scale(0.95) translateY(10px); } 100% { opacity: 1; transform: scale(1) translateY(0); } } @keyframes popUp { 0% { transform: scale(0.9) translateY(10px); opacity: 0; } 100% { transform: scale(1) translateY(0); opacity: 1; } } @keyframes slideIn { from { transform: translateX(-15px); opacity: 0; } to { transform: translateX(0); opacity: 1; } } @keyframes pulse { from { transform: scale(1); } to { transform: scale(1.05); } } /* 5. RESPONSIVE MOBILE SQUEEZE FIXES */ @media (max-width: 600px) { .topbar .btn { color: var(--text-main) !important; } .topbar .btn::before { color: var(--text-main) !important; } /* Shrink the buttons to just icons on small screens to prevent squeezing */ .topbar .btn { padding: 8px !important; font-size: 0 !important; width: 36px; height: 36px; border-radius: 50%; } .topbar .btn::before { font-size: 16px; line-height: 1; display: block; } #shareBtn::before { content: "📤"; } #clearBtn::before { content: "🗑️"; } #settingsBtn::before { content: "⚙️"; } .appTitle { font-size: 15px; } .bubble { max-width: 90%; } /* Make sure settings icon and X button don't overlap on mobile */ .floating-lang-btn { top: 12px; right: 12px; width: 36px; height: 36px; font-size: 16px; } } /* 5. AUDIO PLAYER (FIXED) */ #topAudioPlayer { display: none; position: fixed; top: 85px; left: 50%; transform: translateX(-50%); z-index: 9999; align-items: center; gap: 15px; padding: 10px 20px; border-radius: 30px; border: 2px solid var(--primary); background: var(--bg-surface); backdrop-filter: var(--backdrop-blur); animation: slideDown 0.3s ease; box-shadow: 0 10px 30px rgba(0,0,0,0.4); } /* 6. CAMERA MODAL (was completely unstyled — this is why the UI never appeared) */ #cameraModal { display: none; position: fixed; inset: 0; z-index: 999999999; background: #000; flex-direction: column; align-items: center; justify-content: center; overflow: hidden; } #cameraModal video#cameraVideo { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; background: #000; } .camera-controls-container { position: absolute; left: 0; right: 0; bottom: 0; display: flex; align-items: center; justify-content: center; gap: 40px; padding: 20px 20px calc(30px + env(safe-area-inset-bottom)); box-sizing: border-box; z-index: 10; background: linear-gradient(to top, rgba(0,0,0,0.6), transparent); } /* 7. AI "THINKING" INDICATOR (real staged status, not just static dots) */ .typing-indicator { display: flex; align-items: center; gap: 10px; padding: 4px 2px; } .typing-indicator .dots { display: flex; gap: 4px; } .typing-indicator .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--primary); opacity: 0.4; animation: typingBounce 1.1s infinite ease-in-out; } .typing-indicator .dot:nth-child(1) { animation-delay: 0s; } .typing-indicator .dot:nth-child(2) { animation-delay: 0.15s; } .typing-indicator .dot:nth-child(3) { animation-delay: 0.3s; } @keyframes typingBounce { 0%, 60%, 100% { transform: translateY(0); opacity: 0.4; } 30% { transform: translateY(-6px); opacity: 1; } } .typing-status-text { font-size: 13px; font-weight: 600; color: var(--text-muted); position: relative; overflow: hidden; } .typing-status-text .status-fade { display: inline-block; animation: statusFadeIn 0.35s ease; } @keyframes statusFadeIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } } /* 8. SHARE MODE SELECTION HIGHLIGHT (the "green grid" — previously no CSS existed at all) */ .share-mode-active .bubble { cursor: pointer; transition: box-shadow 0.2s ease, transform 0.15s ease, border-color 0.2s ease; } .share-mode-active .bubble:active { transform: scale(0.98); } .bubble.selected-for-share { outline: 3px solid #25D366 !important; outline-offset: 2px; box-shadow: 0 0 0 6px rgba(37, 211, 102, 0.18) !important; position: relative; } .bubble.selected-for-share::after { content: '✓'; position: absolute; top: -10px; right: -10px; width: 24px; height: 24px; border-radius: 50%; background: #25D366; color: #fff; display: flex; align-items: center; justify-content: center; font-size: 13px; font-weight: 900; box-shadow: 0 2px 6px rgba(0,0,0,0.3); z-index: 5; } /* 9. MATH WRAP-IN-BUBBLE: MathJax's <mjx-container> ignored bubble width and could overflow the screen. */ .bubble mjx-container { max-width: 100% !important; overflow-x: auto; overflow-y: hidden; display: block !important; } .audio-btn { background: var(--primary); color: white; border: none; width: 35px; height: 35px; border-radius: 50%; font-size: 16px; cursor: pointer; display: flex; justify-content: center; align-items: center; transition: 0.2s; } .audio-btn:hover { transform: scale(1.1); } /* 💥 HORIZONTAL SWIPE FIX FOR LONG MATH EQUATIONS 💥 */ .bubble mjx-container[display="true"] { overflow-x: auto !important; overflow-y: hidden !important; max-width: 100% !important; display: block !important; padding-bottom: 10px !important; -webkit-overflow-scrolling: touch; } .bubble mjx-container[display="true"]::-webkit-scrollbar { height: 4px !important; } .bubble mjx-container[display="true"]::-webkit-scrollbar-thumb { background: var(--primary) !important; border-radius: 10px !important; } </STYLE> </head> <body onclick="closePlusMenu(event)"> <div class="overlay" id="overlay"></div> <div class="topbar" id="appTopbar"> <div style="display:flex; align-items:center; flex: 1; overflow: hidden;"> <div class="menuBtn" onclick="toggleSidebar()" style="font-size:24px; cursor:pointer; margin-right: 15px; color:var(--text-main);">☰</div> <div class="appTitle-container" id="titleContainer"> <div class="appTitle" id="sessionTitleDisplay" onclick="window.renameSession()">📚 Book Deep Study</div> </div> </div> <div style="display:flex; gap:8px;"> <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> <button class="btn btn-secondary" id="clearBtn" style="padding: 6px 12px; display: none; font-size: 13px;" onclick="window.clearChat()">🗑️ Clear</button> <button class="btn btn-primary" id="settingsBtn" style="padding: 6px 12px; display: none; font-size: 13px;" onclick="window.openSettings()">⚙️</button> </div> </div> <div id="topAudioPlayer"> <span style="font-weight:bold; font-size:13px; color:var(--text-main);">🔊 AI Voice</span> <button class="audio-btn" id="audioToggleBtn" onclick="window.toggleAudio()">⏸</button> <button class="audio-btn" style="background:#ef4444;" onclick="window.stopAudio()">⏹</button> </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'" style="border-left: 4px solid var(--primary); color: var(--primary); background: var(--border-light);">📚 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'">📝 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> <div id="loadingPage" style="display:none; position:fixed; inset:0; background:rgba(15, 23, 42, 0.98); z-index:99999; flex-direction:column; justify-content:center; align-items:center; backdrop-filter: blur(10px);"> <h2 id="loadingTitle" style="color: var(--primary); font-size: 26px; margin-bottom: 10px; font-weight: 800; text-align: center;">📚 Preparing Tutor...</h2> <p id="loadingDesc" style="color: #cbd5e1; font-size: 14px; text-align: center; max-width: 80%;">Please wait...</p> <div style="width:80%; max-width:300px; height:6px; background:rgba(255,255,255,0.2); border-radius:3px; margin-top:20px; overflow:hidden;"> <div id="loadingBar" style="width:0%; height:100%; background:var(--primary); transition:width 0.3s;"></div> </div> </div> <div id="wizardPage"> <button id="closeSettingsWizardBtn" onclick="window.closeSettingsWizard()">✖</button> <button class="floating-lang-btn" onclick="window.toggleAppLanguage()" title="Toggle Language">🌐</button> <div class="wizard-container" id="wizardContainer"> <div class="step-card active" id="step-1"> <h2>Step 1: Board / Publisher</h2> <label>Select Publisher:</label> <select id="publisherSelect" class="standard" onchange="window.handlePublisherChange()"> <option value="" selected disabled>-- Select Publisher --</option> <option value="NCERT">NCERT</option> <option value="SCERT">SCERT</option> <option value="Arvind Vigyan">Arvind Vigyan</option> <option value="Bharti Bhawan">Bharti Bhawan</option> <option value="Sugam">Sugam</option> <option value="Bihar Board">Bihar Board</option> <option value="New Way">New Way</option> <option value="R.D. Sharma">R.D. Sharma</option> <option value="R.S. Aggarwal">R.S. Aggarwal</option> <option value="Laxmi Publications">Laxmi Publications</option> <option value="Goyal Brothers">Goyal Brothers</option> <option value="CBSE Reference">CBSE Reference</option> <option value="Lucent">Lucent</option> <option value="Arihant">Arihant</option> <option value="Oswaal">Oswaal</option> <option value="S Chand">S Chand</option> <option value="Other">Other (Type / Find Manually)</option> </select> <div id="customPublisherContainer" style="display:none; margin-top:-10px;"> <label>Type Publisher Name (or skip to search):</label> <input type="text" id="customPublisherInput" class="standard" placeholder="e.g. Rajasthan Board / Vidya Bharti..." oninput="window.validateCustomPublisher()"> <div class="btn-row" style="margin-bottom:20px;"> <button class="btn btn-secondary" style="flex:1;" onclick="document.getElementById('customPublisherInput').value=''; window.validateCustomPublisher();">⏭️ Skip Naming It</button> <button class="btn" style="flex:1; background:#8b5cf6; color:white;" onclick="window.openPublisherFinder()">🔍 Find Publisher for Me</button> </div> </div> <div class="btn-row"> <button class="btn btn-primary" onclick="window.nextStep(2)">Next ➔</button> </div> </div> <div class="step-card" id="step-2"> <h2>Step 2: Class</h2> <label>Select Class:</label> <select id="classSelect" class="standard" onchange="window.triggerSubjectFetch()"> <option value="" selected disabled>-- Select Class --</option> <option value="Class 1">Class 1</option> <option value="Class 2">Class 2</option> <option value="Class 3">Class 3</option> <option value="Class 4">Class 4</option> <option value="Class 5">Class 5</option> <option value="Class 6">Class 6</option> <option value="Class 7">Class 7</option> <option value="Class 8">Class 8</option> <option value="Class 9">Class 9</option> <option value="Class 10">Class 10</option> <option value="Class 11">Class 11</option> <option value="Class 12">Class 12</option> </select> <div class="btn-row"> <button class="btn btn-secondary" onclick="window.nextStep(1)">⬅ Back</button> <button class="btn btn-primary" onclick="window.nextStep(3)">Next ➔</button> </div> </div> <div class="step-card" id="step-3"> <h2>Step 3: Subject</h2> <label id="subjectFetchStatus">Select Subject (AI Fetched):</label> <select id="subjectSelect" class="standard" onchange="window.handleSubjectChange()"> <option value="" selected disabled>-- Select Publisher & Class First --</option> </select> <div id="customSubjectContainer" style="display:none; margin-top: 10px;"> <input type="text" id="customSubjectInput" class="standard" placeholder="Type custom subject here (e.g. Computer)..." oninput="window.debounceChapterFetch()"> </div> <div class="btn-row"> <button class="btn btn-secondary" onclick="window.nextStep(2)">⬅ Back</button> <button class="btn btn-primary" onclick="window.nextStep(4)">Next ➔</button> </div> </div> <div class="step-card" id="step-4"> <h2>Step 4: Chapter & Photo</h2> <label id="chapterFetchStatus">Select Chapter (AI Generated):</label> <select id="chapterSelect" class="standard"> <option value="" selected disabled>-- Select Subject First --</option> </select> <label style="margin-top:10px;">Or Type Chapter Manually:</label> <div style="display: flex; gap: 10px; align-items: center; margin-bottom: 20px;"> <input type="text" id="manualChapter" class="standard" placeholder="e.g. Motion / गति" style="margin-bottom: 0;"> <button id="manualChapterMicBtn" class="icon-btn" style="background:var(--primary); color:white; border-radius:12px; width:50px; height:50px;" onclick="window.openVoiceLang('chapter')">🎤</button> <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> </div> <div class="btn-row"> <button class="btn btn-secondary" onclick="window.nextStep(3)">⬅ Back</button> <button class="btn btn-primary" id="initBtnStep4" onclick="window.nextStep(5)">Next ➔</button> </div> </div> <div class="step-card" id="step-5"> <h2>Ready!</h2> <div id="dynamicBookCover"> <div class="generated-cover"> <span style="font-size:11px; text-transform:uppercase; letter-spacing:1px; opacity:0.9;" id="coverPub">Publisher</span> <span style="font-size:20px; font-weight:800; line-height:1.2; margin:10px 0;" id="coverSub">Loading...</span> <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> </div> </div> <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> <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> <div class="btn-row"> <button class="btn btn-secondary" onclick="window.nextStep(4)">⬅ Edit Details</button> </div> </div> </div> </div> <div id="chatPage"> <div class="chat-scroll-area" id="chatHistory"></div> <div id="shareActionArea" class="bottom-action-container" style="display:none; border-top: 2px solid #25D366;"> <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> <div style="display:flex; gap:10px;"> <button class="btn btn-secondary" style="flex:1; padding: 12px;" onclick="window.cancelShareMode()">Cancel</button> <button class="btn btn-primary" style="flex:1; background:#3b82f6; border:none; padding: 12px;" onclick="window.downloadSelectedAsPDF()">📄 Save PDF</button> <button class="btn btn-primary" style="flex:1; background:#25D366; border:none; padding: 12px;" onclick="window.proceedToShare()">📤 WhatsApp</button> </div> </div> <div class="bottom-action-container" id="mainInputArea"> <div id="attachmentChip" class="status-chip">📎 <span id="attachName" style="max-width:200px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">Document Attached</span> <button class="chip-close" onclick="window.clearAttachment()">✕</button></div> <input type="file" id="imageInput" accept="image/*,.pdf" multiple style="display:none;" onchange="window.handleFileSelect(event)"> <div id="imagePreviewContainer"> <div class="img-chip-row" id="imgChipRow"></div> <div class="img-count-badge" id="imgCountBadge"></div> </div> <div id="plusMenu" class="glass-panel"> <button class="menu-item" onclick="window.openCameraChat()">📷 Open Camera</button> <button class="menu-item" onclick="document.getElementById('imageInput').click()">📎 Upload PDF/Image</button> <button class="menu-item" onclick="window.openWebImport()">🌐 Import from Web</button> <button class="menu-item" onclick="window.toggleAppLanguage()">🌐 Toggle AI Language (Hindi/Eng)</button> <button class="menu-item" onclick="window.printFullChat()">🖨️ Print Chat</button> </div> <div class="chat-input-wrapper"> <button id="plusBtn" class="icon-btn" onclick="window.togglePlusMenu(event)">➕</button> <button id="micBtn" class="icon-btn" onclick="window.openVoiceLang()" style="transition: 0.3s;">🎤</button> <textarea id="chatInput" placeholder="Ask your question here..." rows="1" onkeypress="window.handleEnter(event)" oninput="window.resizeInputBox()"></textarea> <button id="sendBtn" class="icon-btn send-btn" onclick="window.sendMessage()">➤</button> </div> </div> </div> <div id="customAlertModal" class="modal-overlay" style="z-index: 99999999;"> <div class="modal-box" style="text-align: center; max-width: 350px;"> <h3 style="color: var(--primary); margin-bottom: 15px; font-size: 20px; font-weight: bold;">System Notice</h3> <p id="alertMessage" style="font-size: 15px; color: var(--text-main); margin-bottom: 25px;"></p> <button class="btn btn-primary" style="width: 100%; padding: 12px; border-radius: 12px; font-size: 16px;" onclick="window.closeCustomAlert()">Done</button> </div> </div> <div id="whatsappModal" class="modal-overlay"> <div class="modal-box" style="text-align:center; border:2px solid #25D366; max-width: 450px;"> <h3 style="color: #25D366; margin-bottom: 15px; font-size: 22px; font-weight: 900;">💬 Share Selected Notes</h3> <p style="font-size: 14px; color: var(--text-muted); margin-bottom: 20px;">Enter the mobile number to send notes.</p> <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;"> <div style="display: flex; gap: 10px;"> <button id="waSendBtn" class="btn" style="flex: 1; padding: 12px; border-radius: 12px; background: #10b981; color: white;" onclick="window.submitWhatsAppSelection(event)">🚀 Send</button> <button class="btn" style="flex: 1; padding: 12px; border-radius: 12px; background: #ef4444; color: white;" onclick="document.getElementById('whatsappModal').style.display='none'">✖ Cancel</button> </div> </div> </div> <div id="webImportModal" class="modal-overlay"> <div class="modal-box" style="text-align: center;"> <h3 style="color: var(--primary); margin-bottom: 10px; font-size: 22px; font-weight: 900;">🌐 Import from Web</h3> <textarea id="webUrlInput" class="standard" rows="5" placeholder="https://example.com/chapter.pdf"></textarea> <div style="display: flex; gap: 10px;"> <button class="btn btn-primary" style="flex: 1; padding: 12px; background: #10b981;" onclick="window.saveWebUrls()">💾 Save</button> <button class="btn" style="flex: 1; padding: 12px; background: #ef4444; color:white;" onclick="document.getElementById('webImportModal').style.display='none'">✖ Cancel</button> </div> </div> </div> <div id="voiceLangModal" class="modal-overlay"> <div class="modal-box" style="text-align: center;"> <h3 style="color: var(--primary); margin-bottom: 10px; font-size: 22px; font-weight: 900;">🎤 Speak to Type</h3> <div style="display: flex; flex-direction: column; gap: 10px;"> <button class="btn btn-primary" style="padding: 15px; border-radius: 12px; font-size: 15px;" onclick="window.selectVoiceLang('hi-IN')">🇮🇳 Speak in Hindi</button> <button class="btn btn-primary" style="padding: 15px; background: #10b981; border-radius: 12px; font-size: 15px;" onclick="window.selectVoiceLang('en-US')">🇺🇸 Speak in English</button> <button class="btn" style="padding: 12px; background: transparent; color: #ef4444; border: 2px solid #ef4444; border-radius: 12px;" onclick="document.getElementById('voiceLangModal').style.display='none'">Cancel</button> </div> </div> </div> <div id="voiceDictateModal" class="modal-overlay"> <div class="modal-box" style="text-align:center; width:95%; max-width:400px; display:flex; flex-direction:column; gap:15px;"> <h3 style="color:var(--primary); margin:0;">🎤 Dictation</h3> <textarea id="voiceDictateText" class="standard" rows="5" placeholder="Your speech will appear here..." style="margin:0;"></textarea> <button id="holdToSpeakBtn" class="btn btn-primary" style="padding:20px; font-size:18px; border-radius:15px; user-select:none; -webkit-user-select:none;">👆 Hold to Speak</button> <div style="display:flex; gap:10px;"> <button class="btn btn-primary" style="flex:1; background:#10b981;" onclick="window.commitVoice()">✅ Done</button> <button class="btn btn-secondary" style="flex:1;" onclick="window.clearVoice()">🗑️ Clear</button> <button class="btn" style="flex:1; background:#ef4444; color:white;" onclick="window.closeVoiceDictate()">✖ Close</button> </div> </div> </div> <div id="bookPreviewModal" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.95); z-index:9999999; flex-direction:column; align-items:center; justify-content:center; padding: 20px; backdrop-filter: blur(10px);"> <h3 style="color:white; margin-bottom:15px; font-size:20px; font-weight:bold;">📸 Review Chapter Photo</h3> <img id="bookPreviewImg" style="max-width:100%; max-height:60vh; border-radius:12px; border:3px solid var(--primary); box-shadow: 0 10px 30px rgba(0,0,0,0.8);"> <div style="display:flex; gap:15px; margin-top:25px; width: 100%; max-width: 400px;"> <button class="btn" style="flex:1; background: rgba(255,255,255,0.2); color:white; border-radius:12px; padding:15px;" onclick="window.retakeBookPhoto()">🔄 Retake</button> <button class="btn btn-primary" style="flex:1.5; font-size: 16px; border-radius:12px; padding:15px;" onclick="window.submitBookPhoto()">✅ Auto-Start Chat</button> </div> <button style="margin-top:25px; background:transparent; border:none; color:#ef4444; font-weight:bold; font-size:16px; cursor:pointer;" onclick="window.closeBookPreview()">✖ Cancel</button> </div> <div id="publisherFinderModal" class="modal-overlay" style="z-index:99999998;"> <div class="modal-box" style="max-width:480px; max-height:88vh; overflow-y:auto;"> <h3 style="margin-top:0; color:var(--primary);">🔍 Find My Publisher</h3> <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> <label>Class:</label> <select id="pfClass" class="standard"> <option value="" selected disabled>-- Select Class --</option> <option value="Class 1">Class 1</option><option value="Class 2">Class 2</option> <option value="Class 3">Class 3</option><option value="Class 4">Class 4</option> <option value="Class 5">Class 5</option><option value="Class 6">Class 6</option> <option value="Class 7">Class 7</option><option value="Class 8">Class 8</option> <option value="Class 9">Class 9</option><option value="Class 10">Class 10</option> <option value="Class 11">Class 11</option><option value="Class 12">Class 12</option> </select> <label>Subject:</label> <input type="text" id="pfSubject" class="standard" placeholder="e.g. Science, Maths, Hindi..."> <label>Chapter Names (fill in as many as you know — skip the rest):</label> <div style="display:flex; flex-direction:column; gap:8px; margin-bottom:10px;"> <input type="text" class="standard pf-chapter-input" style="margin-bottom:0;" placeholder="Chapter 1 (optional)"> <input type="text" class="standard pf-chapter-input" style="margin-bottom:0;" placeholder="Chapter 2 (optional)"> <input type="text" class="standard pf-chapter-input" style="margin-bottom:0;" placeholder="Chapter 3 (optional)"> <input type="text" class="standard pf-chapter-input" style="margin-bottom:0;" placeholder="Chapter 4 (optional)"> <input type="text" class="standard pf-chapter-input" style="margin-bottom:0;" placeholder="Chapter 5 (optional)"> <input type="text" class="standard pf-chapter-input" style="margin-bottom:0;" placeholder="Chapter 6 (optional)"> <input type="text" class="standard pf-chapter-input" style="margin-bottom:0;" placeholder="Chapter 7 (optional)"> <input type="text" class="standard pf-chapter-input" style="margin-bottom:0;" placeholder="Chapter 8 (optional)"> </div> <div style="display:flex; align-items:center; gap:10px; margin:18px 0;"> <div style="flex:1; height:1px; background:var(--border-light);"></div> <span style="font-size:12px; font-weight:900; color:var(--text-muted);">OR</span> <div style="flex:1; height:1px; background:var(--border-light);"></div> </div> <button class="btn btn-secondary" style="width:100%; margin-bottom:15px;" onclick="window.openPublisherFinderCamera()">📷 Take Photo of Chapter List Instead</button> <div id="pfPhotoPreviewWrap" style="display:none; margin-bottom:15px;"> <img id="pfPhotoPreview" style="width:100%; border-radius:12px; border:2px solid var(--primary); display:block;"> <button class="btn btn-secondary" style="width:100%; margin-top:8px;" onclick="window.clearPublisherFinderPhoto()">🗑️ Remove Photo</button> </div> <div id="pfStatusLabel" style="font-size:13px; font-weight:600; color:var(--text-muted); text-align:center; min-height:18px; margin-bottom:10px;"></div> <button id="pfSearchBtn" class="btn btn-primary" style="width:100%; margin-bottom:10px;" onclick="window.runPublisherSearch()">🤖 AI Search Publisher</button> <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;"> <div style="font-size:12px; color:var(--text-muted); text-transform:uppercase; font-weight:700;">Found Publisher:</div> <div id="pfFoundName" style="font-size:18px; font-weight:800; color:var(--primary); margin-top:5px;"></div> </div> <div class="btn-row"> <button class="btn btn-secondary" style="flex:1;" onclick="window.closePublisherFinder()">Cancel</button> <button class="btn" style="flex:1.5; background:#10b981; color:white;" onclick="window.donePublisherFinder()">✅ Done</button> </div> </div> </div> <div id="cameraModal"> <video id="cameraVideo" autoplay playsinline></video> <button style="position:absolute; top:25px; right:25px; background:#ef4444; color:white; border:none; width:45px; height:45px; border-radius:50%; font-size:20px; cursor:pointer; z-index:1000; box-shadow:0 4px 10px rgba(0,0,0,0.5);" onclick="window.closeCamera()">✕</button> <div class="camera-controls-container"> <button id="flashBtn" onclick="window.toggleFlash()" style="background:rgba(255,255,255,0.2); border:none; color:white; width:50px; height:50px; border-radius:50%; font-size:20px; cursor:pointer; backdrop-filter: blur(5px); box-shadow:0 4px 10px rgba(0,0,0,0.5);">🔦</button> <div onclick="window.takePhoto()" style="width:75px; height:75px; background:white; border:5px solid #cbd5e1; border-radius:50%; cursor:pointer; box-shadow:0 4px 15px rgba(0,0,0,0.5); transition: 0.2s;" onmousedown="this.style.transform='scale(0.9)'" onmouseup="this.style.transform='scale(1)'"></div> <button onclick="window.switchCamera()" style="background:rgba(255,255,255,0.2); border:none; color:white; width:50px; height:50px; border-radius:50%; font-size:20px; cursor:pointer; backdrop-filter: blur(5px); box-shadow:0 4px 10px rgba(0,0,0,0.5);">🔄</button> </div> <canvas id="captureCanvas" style="display:none;"></canvas> </div> <!-- 🚨 100% GLOBALLY BOUND SCRIPT BLOCK 🚨 --> <script> // GLOBAL STATE VARIABLES (MUST BE AT THE TOP) localforage.config({ name: 'AI_Pro_Suite', storeName: 'massive_chat_history' }); let appHistory = []; let currentSessionId = Number(new URLSearchParams(window.location.search).get('restore')) || Date.now(); let currentPti = new URLSearchParams(window.location.search).get('pti') || null; let currentAbortController = null; let currentTypewriterInterval = null; let isHindiUI = true; let selectedData = {}; let currentImages = []; const MAX_CHAT_IMAGES = 10; let pfPhotoBase64 = null; let voiceDictateTarget = 'chat'; let documentMemory = ""; let webUrls = []; let cameraTarget = 'chat'; let bookRecognitionImageBase64 = null; let camStream = null; let camFacing = "environment"; let isFlash = false; let voiceRec = null; let voiceText = ""; let localSessionHTMLSize = 0; // GLOBALLY BOUND UTILITIES window.showCustomAlert = function(msg) { document.getElementById('alertMessage').innerText = msg; document.getElementById('customAlertModal').style.display = 'flex'; }; window.closeCustomAlert = function() { document.getElementById('customAlertModal').style.display = 'none'; }; window.alert = function(msg) { window.showCustomAlert(msg); }; function showToast(msg) { let t = document.createElement('div'); t.innerText = msg; t.style.cssText = "position:fixed; bottom:130px; left:50%; transform:translateX(-50%); background:var(--primary); color:white; padding:10px 20px; border-radius:20px; z-index:9999999; font-weight:bold; font-size:13px; box-shadow:0 5px 15px rgba(0,0,0,0.5); animation:slideUpToast 0.3s ease;"; document.body.appendChild(t); setTimeout(() => { t.style.opacity = '0'; t.style.transition = '0.3s'; setTimeout(() => t.remove(), 300); }, 2500); } // 🛑 AUTO RESTORE & SYNC LOOP INIT 🛑 window.addEventListener('load', async function() { document.getElementById('closeSettingsWizardBtn').style.display = 'none'; window.stopAudio(); window.resetSendButton(); let ptiParam = new URLSearchParams(window.location.search).get('pti'); if (ptiParam) { currentPti = ptiParam; await window.fetchAndInjectPtiSession(currentPti); setInterval(() => { window.silentCheckPtiUpdates(); }, 4000); } else { // 🚨 LOCAL FORGE IMPLEMENTATION let savedSessions = (await localforage.getItem('bookSessionsArray_VUltimateAI')) || []; let urlRestoreId = new URLSearchParams(window.location.search).get('restore'); if(urlRestoreId) { let session = savedSessions.find(s => s.id == urlRestoreId); if(session) { selectedData = session.data; currentSessionId = session.id; document.getElementById('sessionTitleDisplay').innerText = session.title || "📚 Book Deep Study"; document.getElementById('wizardPage').style.display = 'none'; document.getElementById('chatPage').style.display = 'flex'; document.getElementById('settingsBtn').style.display = 'block'; document.getElementById('clearBtn').style.display = 'block'; document.getElementById('shareBtn').style.display = 'block'; document.getElementById('chatHistory').innerHTML = session.html; localSessionHTMLSize = session.html.length; setTimeout(() => { const c = document.getElementById('chatHistory'); c.scrollTo({top: c.scrollHeight, behavior: 'instant'}); }, 100); } } else { let activeSession = await localforage.getItem('bookChatHistory_VUltimateAI'); let activeSettings = await localforage.getItem('bookSettings_VUltimateAI'); if(activeSession && activeSettings) { selectedData = activeSettings; document.getElementById('sessionTitleDisplay').innerText = `${selectedData.subject} - ${selectedData.chapter}`; document.getElementById('wizardPage').style.display = 'none'; document.getElementById('chatPage').style.display = 'flex'; document.getElementById('settingsBtn').style.display = 'block'; document.getElementById('clearBtn').style.display = 'block'; document.getElementById('shareBtn').style.display = 'block'; document.getElementById('chatHistory').innerHTML = activeSession; localSessionHTMLSize = activeSession.length; setTimeout(() => { const c = document.getElementById('chatHistory'); c.scrollTo({top: c.scrollHeight, behavior: 'instant'}); }, 100); } } } window.validateSendButton(); window.startMarquee(); }); window.toggleAppLanguage = function() { window.closePlusMenu(); isHindiUI = !isHindiUI; showToast(isHindiUI ? "🌐 Language set to Hindi" : "🌐 Language set to English"); } // 🛑 CLEAR CHAT ENGINE 🛑 window.clearChat = async function() { if(confirm("🗑️ Are you sure you want to completely clear this chapter's chat and memory?")) { document.getElementById('chatHistory').innerHTML = ""; await localforage.removeItem('bookChatHistory_VUltimateAI'); appHistory = []; currentSessionId = Date.now(); currentPti = null; localSessionHTMLSize = 0; const newUrl = `${window.location.origin}${window.location.pathname}`; window.history.replaceState({ path: newUrl }, '', newUrl); document.getElementById('chatPage').style.display = 'none'; document.getElementById('wizardPage').style.display = 'block'; document.getElementById('settingsBtn').style.display = 'none'; document.getElementById('clearBtn').style.display = 'none'; document.getElementById('shareBtn').style.display = 'none'; showToast("🗑️ Memory Wiped Clean."); window.nextStep(1); } }; let marqueeInterval; window.startMarquee = function() { const titleEl = document.getElementById('sessionTitleDisplay'); const container = document.getElementById('titleContainer'); clearInterval(marqueeInterval); if(titleEl.scrollWidth > container.clientWidth) { marqueeInterval = setInterval(() => { container.scrollLeft += 1; if(container.scrollLeft >= (titleEl.scrollWidth - container.clientWidth)) { clearInterval(marqueeInterval); setTimeout(() => { container.scrollLeft = 0; window.startMarquee(); }, 2000); } }, 30); } } document.getElementById('titleContainer').addEventListener('touchstart', () => clearInterval(marqueeInterval)); document.getElementById('titleContainer').addEventListener('touchend', () => setTimeout(window.startMarquee, 3000)); window.saveHistorySafe = function() { localforage.setItem('aiHistory', appHistory).catch(e => console.log("Vault error")); const histHTML = document.getElementById('chatHistory').innerHTML; localforage.setItem('bookChatHistory_VUltimateAI', histHTML); localSessionHTMLSize = histHTML.length; } window.runPreset = function(cmd) { document.getElementById('chatInput').value = cmd; window.resizeInputBox(); window.sendMessage(); } window.copyUserText = function(btn) { navigator.clipboard.writeText(decodeURIComponent(btn.getAttribute('data-text'))); showToast("✅ Copied your message!"); } function toggleSidebar() { const s = document.getElementById("sidebar"), o = document.getElementById("overlay"); const a = !s.classList.contains("active"); s.classList.toggle("active", a); o.classList.toggle("active", a); } window.toggleMsgMenu = function(btn, e) { e.stopPropagation(); let dropdown = btn.nextElementSibling; let isVis = dropdown.style.display === 'block'; document.querySelectorAll('.msg-dropdown').forEach(d => d.style.display = 'none'); dropdown.style.display = isVis ? 'none' : 'block'; } window.deleteMsg = function(btn, e) { e.stopPropagation(); let msg = btn.closest('.msg'); if(msg) { msg.remove(); window.saveHistorySafe(); window.triggerCloudSyncEngine(); showToast("Message deleted."); } document.querySelectorAll('.msg-dropdown').forEach(d => d.style.display = 'none'); } window.copyMsg = function(btn, e) { e.stopPropagation(); let bubble = btn.closest('.bubble'); let text = bubble.innerText.replace('⋮','').replace('📋','').replace('🗑️ Delete','').replace('🔊 Listen','').trim(); navigator.clipboard.writeText(text); let orig = btn.innerHTML; btn.innerHTML = '✅'; setTimeout(() => { btn.innerHTML = orig; }, 1500); } const msgMenuHTML = `<div class="msg-menu-wrap"><button class="msg-action-btn" onclick="window.copyMsg(this, event)" title="Copy">📋</button><button class="msg-action-btn" onclick="window.toggleMsgMenu(this, event)">⋮</button><div class="msg-dropdown"><button onclick="window.deleteMsg(this, event)">🗑️ Delete</button></div></div>`; window.addEventListener('click', function(e) { if (!document.getElementById('plusMenu').contains(e.target) && !e.target.closest('#plusBtn')) window.closePlusMenu(); if (!e.target.closest('.msg-menu-wrap')) document.querySelectorAll('.msg-dropdown').forEach(d => d.style.display = 'none'); if (document.getElementById("overlay").contains(e.target)) toggleSidebar(); }); window.renameSession = function() { let newTitle = prompt("Enter new session name:", document.getElementById('sessionTitleDisplay').innerText); if(newTitle && newTitle.trim()) { document.getElementById('sessionTitleDisplay').innerText = newTitle.trim(); window.triggerCloudSyncEngine(); window.startMarquee(); } } window.getEffectivePublisher = function() { let sel = document.getElementById('publisherSelect').value; if (sel === 'Other') { let custom = document.getElementById('customPublisherInput').value.trim(); return custom || 'Local/Unnamed Publisher'; } return sel; } window.handlePublisherChange = function() { let val = document.getElementById('publisherSelect').value; const box = document.getElementById('customPublisherContainer'); if (val === 'Other') { box.style.display = 'block'; } else { box.style.display = 'none'; window.triggerSubjectFetch(); } } window.validateCustomPublisher = function() { clearTimeout(window._pubDebounce); window._pubDebounce = setTimeout(() => { window.triggerSubjectFetch(); }, 700); } window.debounceChapterFetch = function() { clearTimeout(window._chapDebounceTimer); window._chapDebounceTimer = setTimeout(() => { window.triggerChapterFetch(); }, 600); }; window.nextStep = function(step) { cameraTarget = 'chat'; if(step === 2 && !document.getElementById('publisherSelect').value) return window.showCustomAlert("Please Select Publisher!"); if(step === 3 && !document.getElementById('classSelect').value) return window.showCustomAlert("Please Select Class!"); if(step === 4 && !document.getElementById('subjectSelect').value) return window.showCustomAlert("Please Select Subject!"); document.querySelectorAll('.step-card').forEach(el => el.classList.remove('active')); document.getElementById(`step-${step}`).classList.add('active'); if(step === 5) { let pub = window.getEffectivePublisher(); let sub = document.getElementById('subjectSelect').value; let cls = document.getElementById('classSelect').value; let chapList = document.getElementById('chapterSelect').value; let chapMan = document.getElementById('manualChapter').value; if(sub === 'Other') sub = document.getElementById('customSubjectInput').value || "Custom Subject"; let finalChap = chapMan ? chapMan : chapList; if(!finalChap) { window.nextStep(4); return window.showCustomAlert("Please select or type a chapter!"); } selectedData = { publisher: pub, subject: sub, class: cls, chapter: finalChap }; const coverDiv = document.getElementById('dynamicBookCover'); if (bookRecognitionImageBase64) { 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;">`; } else { coverDiv.innerHTML = ` <div class="generated-cover"> <span style="font-size:11px; text-transform:uppercase; letter-spacing:1px; opacity:0.9;" id="coverPub">${pub}</span> <span style="font-size:20px; font-weight:800; line-height:1.2; margin:10px 0;" id="coverSub">${sub}</span> <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">${cls}</span> </div>`; window.fetchRealBookCover(pub, sub, cls); } const summaryBox = document.getElementById('selectionSummary'); if (summaryBox) { summaryBox.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}`; } } } window.openCameraChat = function() { cameraTarget = 'chat'; window.openCamera(); } window.openBookRecognitionCamera = function() { cameraTarget = 'bookRecognition'; window.openCamera(); } window.openPublisherFinderCamera = function() { cameraTarget = 'publisherFinder'; window.openCamera(); } window.openCamera = async function() { window.closePlusMenu(); const mod = document.getElementById('cameraModal'); mod.style.display = 'flex'; try { if(camStream) camStream.getTracks().forEach(t => t.stop()); camStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: camFacing, width: {ideal: 1920}, height: {ideal: 1080} } }); document.getElementById("cameraVideo").srcObject = camStream; setTimeout(async () => { const track = camStream.getVideoTracks()[0]; if (track && track.getCapabilities && track.getCapabilities().torch && camFacing === "environment") { isFlash = true; await track.applyConstraints({ advanced: [{ torch: true }] }); document.getElementById('flashBtn').innerText = "💡"; } else { isFlash = false; document.getElementById('flashBtn').innerText = "🔦"; } }, 500); } catch(e) { window.showCustomAlert("Camera Error: Please grant camera permissions."); mod.style.display = 'none'; } } window.closeCamera = function() { document.getElementById('cameraModal').style.display = 'none'; if(camStream) { const track = camStream.getVideoTracks()[0]; try { if (track && track.getCapabilities && track.getCapabilities().torch) track.applyConstraints({ advanced: [{ torch: false }] }); } catch(err){} camStream.getTracks().forEach(t => t.stop()); } isFlash = false; } window.switchCamera = async function() { camFacing = camFacing === "environment" ? "user" : "environment"; await window.openCamera(); } window.toggleFlash = async function() { if(!camStream) return; const track = camStream.getVideoTracks()[0]; try { if(track && track.getCapabilities && track.getCapabilities().torch) { isFlash = !isFlash; await track.applyConstraints({ advanced: [{ torch: isFlash }] }); document.getElementById('flashBtn').innerText = isFlash ? "💡" : "🔦"; } else { showToast("Flash not supported."); } } catch(err) {} } window.takePhoto = function() { const v = document.getElementById("cameraVideo"), c = document.getElementById("captureCanvas"); c.width = v.videoWidth; c.height = v.videoHeight; c.getContext("2d").drawImage(v, 0, 0, c.width, c.height); if (cameraTarget === 'chat') { if (currentImages.length >= MAX_CHAT_IMAGES) { showToast(`⚠️ Max ${MAX_CHAT_IMAGES} images per message.`); window.closeCamera(); return; } currentImages.push(c.toDataURL("image/jpeg", 0.7)); window.renderImagePreviews(); window.closeCamera(); window.validateSendButton(); } else if (cameraTarget === 'bookRecognition') { bookRecognitionImageBase64 = c.toDataURL("image/jpeg", 0.7); document.getElementById('bookPreviewImg').src = bookRecognitionImageBase64; document.getElementById('bookPreviewModal').style.display = 'flex'; window.closeCamera(); } else if (cameraTarget === 'publisherFinder') { pfPhotoBase64 = c.toDataURL("image/jpeg", 0.7); document.getElementById('pfPhotoPreview').src = pfPhotoBase64; document.getElementById('pfPhotoPreviewWrap').style.display = 'block'; window.closeCamera(); } } window.renderImagePreviews = function() { const row = document.getElementById('imgChipRow'); const wrap = document.getElementById('imagePreviewContainer'); const badge = document.getElementById('imgCountBadge'); if (!row) return; if (currentImages.length === 0) { wrap.style.display = 'none'; row.innerHTML = ''; badge.innerText = ''; return; } wrap.style.display = 'block'; row.innerHTML = currentImages.map((src, i) => `<div class="img-chip-item"><img class="img-chip" src="${src}"><button class="remove-img-btn" onclick="window.removeImageAt(${i})">✖</button></div>` ).join(''); badge.innerText = `${currentImages.length}/${MAX_CHAT_IMAGES} image${currentImages.length > 1 ? 's' : ''} attached`; } window.removeImageAt = function(idx) { currentImages.splice(idx, 1); window.renderImagePreviews(); window.validateSendButton(); } window.openPublisherFinder = function() { document.getElementById('publisherFinderModal').style.display = 'flex'; document.getElementById('pfResultBox').style.display = 'none'; document.getElementById('pfStatusLabel').innerText = ''; window._pfFoundPublisher = null; let clsVal = document.getElementById('classSelect').value; if (clsVal) document.getElementById('pfClass').value = clsVal; } window.closePublisherFinder = function() { document.getElementById('publisherFinderModal').style.display = 'none'; } window.clearPublisherFinderPhoto = function() { pfPhotoBase64 = null; document.getElementById('pfPhotoPreviewWrap').style.display = 'none'; } window.runPublisherSearch = async function() { const btn = document.getElementById('pfSearchBtn'); const status = document.getElementById('pfStatusLabel'); let cls = document.getElementById('pfClass').value; let sub = document.getElementById('pfSubject').value.trim(); let chapters = Array.from(document.querySelectorAll('.pf-chapter-input')).map(i => i.value.trim()).filter(Boolean); if (!cls && !sub && chapters.length === 0 && !pfPhotoBase64) { return window.showCustomAlert("Please provide at least a class, subject, some chapter names, or a photo."); } btn.disabled = true; btn.innerHTML = "⏳ Searching..."; document.getElementById('pfResultBox').style.display = 'none'; try { let extractedChapters = chapters; let extractedSubject = sub; if (pfPhotoBase64) { status.innerText = "📷 Reading chapter names from photo..."; 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."; const vr = await fetch("/api/gemini-vision", { method: "POST", headers: {"Content-Type":"application/json"}, body: JSON.stringify({ imageBase64: pfPhotoBase64, userPrompt: visionPrompt }) }); const vdata = await vr.json(); let vjson = (vdata.text || "").replace(/```json/gi,'').replace(/```/g,'').trim(); try { let parsed = JSON.parse(vjson); if (parsed.chapters && parsed.chapters.length) extractedChapters = extractedChapters.concat(parsed.chapters); if (!extractedSubject && parsed.subject) extractedSubject = parsed.subject; } catch(e) {} } status.innerText = "🔎 Cross-referencing publisher databases..."; 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. Class: ${cls || 'Unknown'} Subject: ${extractedSubject || 'Unknown'} Chapter names provided: ${extractedChapters.length ? extractedChapters.join(', ') : 'None provided'} 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.`; 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 }) }); const data = await r.json(); let cleanJson = (data.text || "").replace(/```json/gi,'').replace(/```/g,'').trim(); let parsed = JSON.parse(cleanJson); if (parsed.publisher) { document.getElementById('pfFoundName').innerText = parsed.publisher; document.getElementById('pfResultBox').style.display = 'block'; status.innerText = `✅ Found (confidence: ${parsed.confidence || 'medium'})`; window._pfFoundPublisher = parsed.publisher; } else { status.innerText = "❌ Couldn't confidently identify it. Try adding more chapter names or a clearer photo."; } } catch(e) { status.innerText = "❌ Search failed. Please try again."; } btn.disabled = false; btn.innerHTML = "🤖 AI Search Publisher"; } window.donePublisherFinder = function() { let foundName = window._pfFoundPublisher || document.getElementById('pfFoundName').innerText.trim(); if (foundName) { document.getElementById('publisherSelect').value = 'Other'; document.getElementById('customPublisherContainer').style.display = 'block'; document.getElementById('customPublisherInput').value = foundName; } if (document.getElementById('pfClass').value) document.getElementById('classSelect').value = document.getElementById('pfClass').value; window.closePublisherFinder(); if (foundName) { showToast(`✅ Publisher set to "${foundName}"`); window.triggerSubjectFetch(); } else showToast("Closed publisher finder."); } window.retakeBookPhoto = function() { document.getElementById('bookPreviewModal').style.display = 'none'; window.openBookRecognitionCamera(); } window.closeBookPreview = function() { document.getElementById('bookPreviewModal').style.display = 'none'; bookRecognitionImageBase64 = null; } window.submitBookPhoto = async function() { document.getElementById('bookPreviewModal').style.display = 'none'; document.getElementById('loadingPage').style.display = 'flex'; document.getElementById('wizardPage').style.display = 'none'; let bar = document.getElementById('loadingBar'); let desc = document.getElementById('loadingDesc'); bar.style.width = '20%'; desc.innerText = "Analyzing page structure..."; try { 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."; const r = await fetch("/api/gemini-vision", { method: "POST", headers: {"Content-Type":"application/json"}, body: JSON.stringify({ imageBase64: bookRecognitionImageBase64, userPrompt: prompt }) }); const data = await r.json(); bar.style.width = '60%'; desc.innerText = "Extracting Chapter Details..."; let cleanJson = data.text.replace(/```json/gi, '').replace(/```/g, '').trim(); let parsed = JSON.parse(cleanJson); selectedData.subject = parsed.subject || document.getElementById('subjectSelect').value || "Unknown Subject"; selectedData.chapter = parsed.chapter || "Extracted Chapter"; selectedData.publisher = window.getEffectivePublisher() || "Unknown Publisher"; selectedData.class = document.getElementById('classSelect').value || "Unknown Class"; bar.style.width = '100%'; setTimeout(() => { window.startConversation(false); }, 300); } catch(e) { window.showCustomAlert("Failed to analyze image. Please type details manually."); document.getElementById('loadingPage').style.display = 'none'; document.getElementById('wizardPage').style.display = 'block'; } } window.triggerSubjectFetch = async function() { let pub = window.getEffectivePublisher(); let cls = document.getElementById('classSelect').value; let subSelect = document.getElementById('subjectSelect'); if(!pub || !cls) return; subSelect.innerHTML = '<option value="" selected disabled>-- 🤖 Fetching Subjects... --</option>'; try { const sysPrompt = `You are a syllabus mapping expert. The user wants the EXACT subjects published for Class ${cls} by the publisher/board "${pub}". CRITICAL RULES: 1. ONLY return subjects that are ACTUALLY PUBLISHED by "${pub}" for Class ${cls}. 2. If "${pub}" is a specialized publisher (e.g. R.D. Sharma only does Mathematics), you MUST ONLY RETURN ["Mathematics"]. 3. DO NOT hallucinate generic subjects if the publisher does not print them. 4. Return a raw JSON array of strings ONLY. Example: ["Mathematics", "Science"].`; 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 }) }); const data = await r.json(); let cleanJson = data.text.replace(/```json/gi, '').replace(/```/g, '').trim(); let fetchedSubjects = JSON.parse(cleanJson); if(!Array.isArray(fetchedSubjects) || fetchedSubjects.length === 0) throw new Error("Fallback"); subSelect.innerHTML = '<option value="" selected disabled>-- Select Subject --</option>'; fetchedSubjects.forEach(sub => { subSelect.innerHTML += `<option value="${sub}">${sub}</option>`; }); subSelect.innerHTML += `<option value="Other">Other Subject (Type Manually)</option>`; } catch(e) { 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>`; } } window.handleSubjectChange = function() { let sub = document.getElementById('subjectSelect').value; if(sub === 'Other') { document.getElementById('customSubjectContainer').style.display = 'block'; } else { document.getElementById('customSubjectContainer').style.display = 'none'; } window.triggerChapterFetch(); } window.triggerChapterFetch = async function() { 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'); if(sub === 'Other') sub = document.getElementById('customSubjectInput').value; if(!sub || !cls) { statusLabel.innerText = "Please select Subject and Class first."; statusLabel.style.color = "var(--text-muted)"; return; } statusLabel.innerText = "⏳ Checking Database..."; chapSelect.innerHTML = '<option value="" selected disabled>-- 🤖 Fetching... --</option>'; document.getElementById('initBtnStep4').style.display = 'block'; let isEnglishSub = ['English', 'English Grammar', 'Computer Science', 'Information Technology'].includes(sub); let targetLang = (isEnglishSub || !isHindiUI) ? 'ENGLISH' : 'HINDI (Devanagari script)'; try { const sysPrompt = `You are a syllabus expert. The user wants the EXACT chapter index for Class ${cls}, Subject ${sub}, Publisher ${pub}. 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}. Return JSON array of strings. Output strictly in ${targetLang}. ONLY output the raw JSON array.`; const r = await fetch("/api/gemini-text", { method: "POST", headers: {"Content-Type":"application/json"}, body: JSON.stringify({ systemPrompt: sysPrompt, userPrompt: "Fetch chapters", useSearch: true }) }); const data = await r.json(); let cleanJson = data.text.replace(/```json/gi, '').replace(/```/g, '').trim(); let fetchedChapters = JSON.parse(cleanJson); if(!Array.isArray(fetchedChapters)) throw new Error("Invalid Array"); if(fetchedChapters.length === 0) { 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; } statusLabel.style.color = "var(--text-muted)"; chapSelect.innerHTML = '<option value="" selected disabled>-- Select Chapter --</option>'; fetchedChapters.forEach((chap, i) => { chapSelect.innerHTML += `<option value="Chapter ${i+1}: ${chap}">Chapter ${i+1}: ${chap}</option>`; }); statusLabel.innerText = "Select Chapter (Generated by AI):"; } catch(e) { statusLabel.innerText = "Select Chapter (Fetch Failed):"; chapSelect.innerHTML = '<option value="" selected disabled>-- ❌ Fetch Failed. Please type manually below --</option>'; } } // 🚨 LOCAL FORGE IMPLEMENTATION: Remember the chapter content properly window.fetchChapterContext = async function() { try { let memoryKey = `bookMemory_${selectedData.publisher}_${selectedData.class}_${selectedData.subject}_${selectedData.chapter}`; let cachedMemory = await localforage.getItem(memoryKey); if (cachedMemory) { documentMemory = cachedMemory; return; } 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.`; 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 }) }); const data = await r.json(); if(data.text) { documentMemory = data.text; await localforage.setItem(memoryKey, documentMemory); } } catch(e) {} } window.fetchRealBookCover = async function(pub, sub, cls) { if (bookRecognitionImageBase64) return; let coverDiv = document.getElementById('dynamicBookCover'); let statusSub = document.getElementById('coverSub'); if (statusSub) statusSub.innerText = "🔍 AI Scanning Cover..."; try { const promptQuery = `exact front cover of ${pub} Class ${cls.replace('Class ','')} ${sub} textbook India -pinterest`; const res = await fetch("/api/image-search-select", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt: promptQuery, isBookCover: true }) }); const data = await res.json(); if (data.bestImageUrl) { coverDiv.innerHTML = `<img src="${data.bestImageUrl}" 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;">`; } else if (statusSub) { statusSub.innerText = sub; } } catch(e) { if (statusSub) statusSub.innerText = sub; } } window.validateSendButton = function() { const inp = document.getElementById('chatInput'); const btn = document.getElementById('sendBtn'); const text = inp.value.trim(); const hasAttachment = currentImages.length > 0 || documentMemory || webUrls.length > 0; if (text.length > 2000) { btn.classList.remove('active-btn'); } else if (text.length === 0 && !hasAttachment) { btn.classList.remove('active-btn'); } else { btn.classList.add('active-btn'); } } let previousInputHeight = "40px"; window.resizeInputBox = function() { const inp = document.getElementById('chatInput'); if (inp.value.trim() === "") { inp.style.height = '40px'; previousInputHeight = '40px'; } else { inp.style.height = '40px'; inp.style.height = Math.max(40, Math.min(inp.scrollHeight, 120)) + 'px'; previousInputHeight = inp.style.height; } window.validateSendButton(); } window.openWebImport = function() { window.closePlusMenu(); document.getElementById('webImportModal').style.display = 'flex'; } window.saveWebUrls = function() { let text = document.getElementById('webUrlInput').value.trim(); let urls = text.split('\n').map(u => u.trim()).filter(u => u.length > 0); if (urls.length > 10) { window.showCustomAlert("⚠️ Maximum 10 URLs allowed!"); urls = urls.slice(0, 10); } if (urls.length > 0) { webUrls = urls; document.getElementById("attachmentChip").style.display = "flex"; document.getElementById("attachName").innerText = `${urls.length} Web URLs Attached`; } document.getElementById('webImportModal').style.display = 'none'; document.getElementById('webUrlInput').value = ''; window.validateSendButton(); } window.handleFileSelect = function(event) { window.closePlusMenu(); const files = Array.from(event.target.files || []); if(!files.length) return; const imageFiles = files.filter(f => f.type.startsWith('image/')); const pdfFile = files.find(f => f.type === 'application/pdf' || f.name.endsWith('.pdf')); if (imageFiles.length) { const room = MAX_CHAT_IMAGES - currentImages.length; if (room <= 0) { window.showCustomAlert(`⚠️ Maximum ${MAX_CHAT_IMAGES} images per message reached.`); } const toRead = imageFiles.slice(0, Math.max(0, room)); if (imageFiles.length > toRead.length) showToast(`⚠️ Only added ${toRead.length} — ${MAX_CHAT_IMAGES} image limit reached.`); let readCount = 0; toRead.forEach(file => { const reader = new FileReader(); reader.onload = function(e) { currentImages.push(e.target.result); readCount++; if (readCount === toRead.length) { window.renderImagePreviews(); window.validateSendButton(); } }; reader.readAsDataURL(file); }); } else if (pdfFile) { const reader = new FileReader(); document.getElementById("attachmentChip").style.display = "flex"; document.getElementById("attachName").innerText = "⏳ Reading PDF..."; reader.onload = async function() { try { const typedarray = new Uint8Array(this.result); const pdf = await pdfjsLib.getDocument(typedarray).promise; let text = ""; for(let i=1; i<=pdf.numPages; i++){ const p = await pdf.getPage(i); const c = await p.getTextContent(); text += c.items.map(item=>item.str).join(' '); } documentMemory = text; document.getElementById("attachName").innerText = `📄 ${pdfFile.name}`; window.validateSendButton(); } catch(err) { window.showCustomAlert("❌ Failed to read PDF."); window.clearAttachment(); } }; reader.readAsArrayBuffer(pdfFile); } else { window.showCustomAlert("Only Images and PDFs are supported right now."); } event.target.value = ''; } window.removeImage = function() { currentImages = []; window.renderImagePreviews(); window.validateSendButton(); } window.clearAttachment = function() { documentMemory = ""; webUrls = []; document.getElementById("attachmentChip").style.display = "none"; window.validateSendButton(); } let isShareMode = false; window.toggleShareMode = function() { previousInputHeight = document.getElementById('chatInput').style.height || '40px'; document.getElementById('mainInputArea').style.display = 'none'; document.getElementById('shareActionArea').style.display = 'flex'; isShareMode = true; document.getElementById('chatHistory').classList.add('share-mode-active'); document.querySelectorAll('.bubble').forEach(b => { b.onclick = function(e) { if(!isShareMode) return; this.classList.toggle('selected-for-share'); } }); } window.cancelShareMode = function() { document.getElementById('shareActionArea').style.display = 'none'; document.getElementById('mainInputArea').style.display = 'flex'; isShareMode = false; document.getElementById('chatHistory').classList.remove('share-mode-active'); setTimeout(() => { document.getElementById('chatInput').style.height = previousInputHeight; }, 10); document.querySelectorAll('.bubble').forEach(b => { b.classList.remove('selected-for-share'); b.onclick = null; }); } window.proceedToShare = function() { if(document.querySelectorAll('.bubble.selected-for-share').length === 0) return window.showCustomAlert("Please tap at least one message to share!"); document.getElementById('whatsappModal').style.display = 'flex'; } window.submitWhatsAppSelection = async function(event) { let number = document.getElementById('waNumberInput').value.trim(); if (!number) return showToast("Please enter a mobile number."); if (!number.startsWith("91") && !number.startsWith("+")) { number = "91" + number; } let fullChatText = "🔎 *DEEP STUDY - Selected Notes* 🔎\n\n"; document.querySelectorAll('.bubble.selected-for-share').forEach(node => { let clone = node.cloneNode(true); clone.querySelectorAll('.msg-menu-wrap, button, .listen-btn, .user-copy-btn').forEach(el => el.remove()); let htmlStr = clone.innerHTML.replace(/<br\s*[\/]?>/gi, '\n').replace(/<\/div>/gi, '\n').replace(/<\/p>/gi, '\n\n'); clone.innerHTML = htmlStr; let msgText = (clone.textContent || clone.innerText || "").replace(/\n\s*\n/g, '\n\n').trim(); if (msgText.length > 0) fullChatText += `${msgText}\n\n------------------------\n\n`; }); const superscripts = {'0':'⁰','1':'¹','2':'²','3':'³','4':'⁴','5':'⁵','6':'⁶','7':'⁷','8':'⁸','9':'⁹','+':'⁺','-':'⁻','=':'⁼','(':'⁽',')':'⁾','a':'ᵃ','b':'ᵇ','c':'ᶜ','n':'ⁿ','x':'ˣ','y':'ʸ'}; const toSuper = (str) => str.split('').map(c => superscripts[c] || c).join(''); fullChatText = fullChatText.replace(/\$\$/g, '').replace(/\$/g, '').replace(/\\\(/g, '').replace(/\\\)/g, '').replace(/\\frac{([^}]+)}{([^}]+)}/g, '$1/$2').replace(/\\times/g, '×').replace(/\\cdot/g, '·'); const btn = event.target; const originalText = btn.innerHTML; btn.innerHTML = "⏳ Sharing Loop Engine Process..."; btn.disabled = true; const fullHTMLPayload = document.getElementById('chatHistory').innerHTML; try { const saveResponse = await fetch('/api/pti-save', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: "save", pti: currentPti || currentSessionId, title: document.getElementById('sessionTitleDisplay').innerText, htmlPayload: fullHTMLPayload, metaSettings: selectedData }) }); const saveResult = await saveResponse.json(); if (saveResult.success) { currentPti = saveResult.pti; currentSessionId = currentPti; const newUrl = `${window.location.origin}${window.location.pathname}?pti=${currentPti}`; window.history.replaceState({ path: newUrl }, '', newUrl); } const activeTokenId = currentPti || currentSessionId; const liveChatPtiUrl = `${window.location.origin}/books.html?restore=${activeTokenId}&pti=${activeTokenId}`; const response = await fetch("/api/send-dual-share", { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ number: number, notesMessage: fullChatText.trim(), targetUrl: liveChatPtiUrl }) }); if (response.ok) { showToast("✅ Notes and live link sent successfully!"); document.getElementById('whatsappModal').style.display = 'none'; window.cancelShareMode(); } else { window.alert("Transmission failed. Verify server environment parameters."); } } catch (e) { window.alert("❌ Transmission loop failed."); } btn.innerHTML = originalText; btn.disabled = false; } window.printFullChat = function() { window.closePlusMenu(); let content = document.getElementById('chatHistory').innerHTML; if(!content.trim()) return window.showCustomAlert("Chat is empty!"); let win = window.open('', '', 'width=800,height=600'); win.document.write(`<html><head><title>Print Chat</title><style>body{font-family:sans-serif; color:#333; line-height:1.6; padding:20px;} .msg-menu-wrap, .user-copy-btn, .typing-indicator{display:none;} .bubble{background:#f3f4f6; padding:15px; border-radius:10px; margin-bottom:10px;} img{max-width:100%; border-radius:8px;} h2{color:#3b82f6; text-align:center;} hr{margin-bottom:20px; border:none; border-bottom:2px solid #3b82f6;}</style></head><body><h2>📚 Book Deep Study: ${document.getElementById('sessionTitleDisplay').innerText}</h2><hr>${content}</body></html>`); win.document.close(); win.focus(); setTimeout(() => { win.print(); win.close(); }, 500); } window.downloadSelectedAsPDF = function() { let selectedNodes = document.querySelectorAll('.bubble.selected-for-share'); if(selectedNodes.length === 0) return window.showCustomAlert("Please tap at least one message to save!"); let content = "<h2 style='text-align:center; color:#3b82f6;'>📚 Book Deep Study - Notes</h2><hr>"; selectedNodes.forEach(n => { let clone = n.cloneNode(true); clone.querySelectorAll('.msg-menu-wrap, .user-copy-btn').forEach(el => el.remove()); content += `<div style="margin-bottom:20px; padding:15px; border:1px solid #ddd; border-radius:10px; background:#f9fafb;">${clone.innerHTML}</div>`; }); let win = window.open('', '', 'width=800,height=600'); win.document.write(`<html><head><title>Saved Notes</title><style>body{font-family:sans-serif; color:#333; line-height:1.6; padding:20px;}</style></head><body>${content}</body></html>`); win.document.close(); win.focus(); setTimeout(() => { win.print(); window.cancelShareMode(); }, 500); } window.togglePlusMenu = function(e) { e.stopPropagation(); const m = document.getElementById("plusMenu"); m.style.display = m.style.display === "flex" ? "none" : "flex"; } window.closePlusMenu = function() { document.getElementById("plusMenu").style.display = "none"; } window.openSettings = function() { document.getElementById('chatPage').style.display = 'none'; document.getElementById('wizardPage').style.display = 'block'; document.getElementById('settingsBtn').style.display = 'none'; let chatContent = document.getElementById('chatHistory').innerHTML.trim(); if (chatContent !== "") { document.getElementById('closeSettingsWizardBtn').style.display = 'flex'; } else { document.getElementById('closeSettingsWizardBtn').style.display = 'none'; } window.nextStep(1); } window.closeSettingsWizard = function() { document.getElementById('wizardPage').style.display = 'none'; document.getElementById('chatPage').style.display = 'flex'; document.getElementById('settingsBtn').style.display = 'block'; } window.handleEnter = function(e) { if(e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); if (document.getElementById('sendBtn').classList.contains('active-btn')) window.sendMessage(); } } window.openVoiceLang = function(target) { voiceDictateTarget = target || 'chat'; window.closePlusMenu(); document.getElementById('voiceLangModal').style.display='flex'; } let voiceFinalCount = 0; window.selectVoiceLang = function(lang) { document.getElementById('voiceLangModal').style.display='none'; document.getElementById('voiceDictateModal').style.display='flex'; document.getElementById('voiceDictateText').value = ""; voiceText = ""; voiceFinalCount = 0; const SpeechRec = window.SpeechRecognition || window.webkitSpeechRecognition; if(!SpeechRec) return window.showCustomAlert("Voice input not supported by this browser."); voiceRec = new SpeechRec(); voiceRec.lang = lang; voiceRec.continuous = true; voiceRec.interimResults = true; voiceRec.onresult = (e) => { let interim = ""; for(let i = 0; i < e.results.length; i++) { const transcript = e.results[i][0].transcript; if (e.results[i].isFinal) { if (i >= voiceFinalCount) { voiceText += transcript + " "; voiceFinalCount = i + 1; } } else { interim += transcript; } } document.getElementById('voiceDictateText').value = voiceText + interim; }; } const holdBtn = document.getElementById('holdToSpeakBtn'); let isDictating = false; 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"; } } 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)"; } } holdBtn.addEventListener('touchstart', window.startDictation, {passive:false}); holdBtn.addEventListener('mousedown', window.startDictation); holdBtn.addEventListener('touchend', window.stopDictation); holdBtn.addEventListener('mouseup', window.stopDictation); holdBtn.addEventListener('mouseleave', window.stopDictation); window.commitVoice = function() { const targetId = voiceDictateTarget === 'chapter' ? 'manualChapter' : 'chatInput'; const targetEl = document.getElementById(targetId); const spoken = document.getElementById('voiceDictateText').value.trim(); if (spoken) targetEl.value += (targetEl.value ? " " : "") + spoken; document.getElementById('voiceDictateModal').style.display='none'; if (targetId === 'chatInput') window.resizeInputBox(); if(voiceRec) voiceRec.stop(); isDictating = false; voiceDictateTarget = 'chat'; } window.clearVoice = function() { voiceText = ""; voiceFinalCount = 0; document.getElementById('voiceDictateText').value = ""; } window.closeVoiceDictate = function() { document.getElementById('voiceDictateModal').style.display='none'; if(voiceRec) voiceRec.stop(); isDictating = false; voiceDictateTarget = 'chat'; } window.cancelAiRequest = function() { if(currentAbortController) currentAbortController.abort(); if(currentTypewriterInterval) clearInterval(currentTypewriterInterval); window.resetSendButton(); } window.resetSendButton = function() { const btn = document.getElementById('sendBtn'); btn.classList.remove('stop-btn'); btn.classList.add('send-btn'); btn.innerHTML = '➤'; btn.onclick = window.sendMessage; window.validateSendButton(); } window.toggleAudio = function() { const btn = document.getElementById("audioToggleBtn"); if (window.speechSynthesis.paused) { window.speechSynthesis.resume(); btn.innerText = "⏸"; } else { window.speechSynthesis.pause(); btn.innerText = "▶"; } } window.stopAudio = function() { window.speechSynthesis.cancel(); document.getElementById("topAudioPlayer").style.display = "none"; } window.playAudio = function(btn) { let targetId = btn.getAttribute('data-target'); let text = document.getElementById(targetId).innerText; window.speechSynthesis.cancel(); const u = new SpeechSynthesisUtterance(text); u.lang = isHindiUI ? 'hi-IN' : 'en-US'; u.onstart = () => { document.getElementById("topAudioPlayer").style.display = "flex"; document.getElementById("audioToggleBtn").innerText = "⏸"; }; u.onend = () => { document.getElementById("topAudioPlayer").style.display = "none"; }; window.activeUtterance = u; window.speechSynthesis.speak(window.activeUtterance); }; // ========================================================================= // 🧠 PTI SYNC ENGINE CODES // ========================================================================== window.silentCheckPtiUpdates = async function() { if (!currentPti || document.getElementById('sendBtn').classList.contains('stop-btn')) return; try { const response = await fetch(`/api/pti-get?pti=${currentPti}`); if (!response.ok) return; const freshSession = await response.json(); if (freshSession.error) return; if (freshSession.htmlPayload && freshSession.htmlPayload.length > localSessionHTMLSize) { localSessionHTMLSize = freshSession.htmlPayload.length; document.getElementById('chatHistory').innerHTML = freshSession.htmlPayload; currentSessionId = freshSession.id; await localforage.setItem('bookChatHistory_VUltimateAI', freshSession.htmlPayload); const c = document.getElementById('chatHistory'); c.scrollTo({top: c.scrollHeight, behavior: 'smooth'}); showToast("📲 Live session update applied!"); } } catch(e) {} } window.triggerCloudSyncEngine = async function() { const fullHTMLPayload = document.getElementById('chatHistory').innerHTML; let savedSessions = (await localforage.getItem('bookSessionsArray_VUltimateAI')) || []; let curIdx = savedSessions.findIndex(s => s.id == currentSessionId || s.id === currentPti); let sessionObj = { id: currentPti || currentSessionId, title: document.getElementById('sessionTitleDisplay').innerText, html: fullHTMLPayload, data: selectedData }; if(curIdx !== -1) savedSessions[curIdx] = sessionObj; else savedSessions.unshift(sessionObj); await localforage.setItem('bookSessionsArray_VUltimateAI', savedSessions); fetch('/api/pti-save', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: "save", pti: currentPti || currentSessionId, title: document.getElementById('sessionTitleDisplay').innerText, htmlPayload: fullHTMLPayload, metaSettings: selectedData }) }) .then(res => res.json()) .then(serverResult => { if (serverResult.success && !currentPti) { currentPti = serverResult.pti; currentSessionId = currentPti; } }) .catch(err => console.error("Cloud Sync Failed:", err)); } window.startConversation = async function(forceNew = false, forceClear = false) { let oldSettings = await localforage.getItem('bookSettings_VUltimateAI'); let oldHistory = await localforage.getItem('bookChatHistory_VUltimateAI'); let isNewChapter = false; if (oldSettings && oldHistory) { if (oldSettings.chapter !== selectedData.chapter || oldSettings.subject !== selectedData.subject) isNewChapter = true; } if (forceClear) { document.getElementById('chatHistory').innerHTML = ""; await localforage.removeItem('bookChatHistory_VUltimateAI'); currentSessionId = Date.now(); } else if (isNewChapter) { document.getElementById('chatHistory').insertAdjacentHTML('beforeend', `<div class="chapter-divider">--- Started New Session: ${selectedData.chapter} ---</div>`); } document.getElementById('wizardPage').style.display = 'none'; document.getElementById('loadingPage').style.display = 'flex'; let bar = document.getElementById('loadingBar'); let desc = document.getElementById('loadingDesc'); bar.style.width = '30%'; desc.innerText = "Connecting to AI Core..."; await new Promise(r => setTimeout(r, 400)); bar.style.width = '60%'; desc.innerText = "Analyzing Chapter Context..."; await window.fetchChapterContext(); bar.style.width = '90%'; desc.innerText = "Setting up Tutor Interface..."; await new Promise(r => setTimeout(r, 400)); bar.style.width = '100%'; setTimeout(async () => { document.getElementById('loadingPage').style.display = 'none'; document.getElementById('chatPage').style.display = 'flex'; document.getElementById('settingsBtn').style.display = 'block'; document.getElementById('clearBtn').style.display = 'block'; document.getElementById('shareBtn').style.display = 'block'; document.getElementById('sessionTitleDisplay').innerText = `${selectedData.subject} - ${selectedData.chapter}`; window.startMarquee(); await localforage.setItem('bookSettings_VUltimateAI', selectedData); if(document.getElementById('chatHistory').innerHTML.trim() === "" || isNewChapter) { let isEnglishSub = ['English', 'English Grammar', 'Computer Science', 'Information Technology'].includes(selectedData.subject); let initialMessageHTML = (isEnglishSub || !isHindiUI) ? `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> <div class="preset-chips" style="margin-top: 15px;"> <button class="preset-btn" onclick="window.runPreset('Generate detailed study notes for this chapter.')">📝 Generate Notes</button> <button class="preset-btn" onclick="window.runPreset('Create 10 important MCQs from this chapter with answers.')">✅ Objectives</button> <button class="preset-btn" onclick="window.runPreset('Analyze this chapter in simple terms.')">📊 Analyze Chapter</button> </div>` : `नमस्ते! मैं आपका एआई शिक्षक हूँ। <br><br>हम **${selectedData.class}** के **${selectedData.subject}** विषय के अध्याय **"${selectedData.chapter}"** पर चर्चा करने के लिए तैयार हैं। <br><br>**मैं आपके सभी सवालों के जवाब डिफ़ॉल्ट रूप से हिंदी में दूँगा।**<br><br> <div class="preset-chips" style="margin-top: 15px;"> <button class="preset-btn" onclick="window.runPreset('इस अध्याय के लिए विस्तृत और आसान नोट्स बनाएं।')">📝 जनरेट नोट्स</button> <button class="preset-btn" onclick="window.runPreset('इस अध्याय से 10 महत्वपूर्ण बहुविकल्पीय प्रश्न (MCQ) बनाएं और उत्तर भी दें।')">✅ ऑब्जेक्टिव प्रश्न</button> <button class="preset-btn" onclick="window.runPreset('इस अध्याय का विस्तार से और आसान भाषा में विश्लेषण करें।')">📊 अध्याय का विश्लेषण</button> </div>`; // Directly append first message securely const msgDiv = document.createElement("div"); msgDiv.className = "msg ai"; msgDiv.innerHTML = `<div class="bubble">${initialMessageHTML}${msgMenuHTML}</div>`; document.getElementById('chatHistory').appendChild(msgDiv); window.saveHistorySafe(); } }, 300); } window.sendMessage = async function() { const inputEl = document.getElementById('chatInput'); const text = inputEl.value.trim(); const imgs = currentImages.slice(); const btn = document.getElementById('sendBtn'); if(!btn.classList.contains('active-btn')) return; btn.classList.remove('active-btn', 'send-btn'); btn.classList.add('stop-btn'); btn.innerHTML = '⏹'; btn.onclick = window.cancelAiRequest; const msgDiv = document.createElement("div"); msgDiv.className = "msg user"; let imgHtml = imgs.length ? imgs.map(src => `<img src="${src}" style="max-width:100%; border-radius:10px; margin-bottom:6px;">`).join('') + "<br>" : ""; msgDiv.innerHTML = `<div class="bubble"><button onclick="window.copyUserText(this)" data-text="${encodeURIComponent(text)}" class="user-copy-btn">📋</button>${imgHtml}${text.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\n/g, "<br>")}${msgMenuHTML}</div>`; document.getElementById('chatHistory').appendChild(msgDiv); const c = document.getElementById('chatHistory'); c.scrollTo({top: c.scrollHeight, behavior: 'smooth'}); inputEl.value = ""; window.resizeInputBox(); window.removeImage(); const loadingId = "load_" + Date.now(); const loadDiv = document.createElement("div"); loadDiv.className = "msg ai"; loadDiv.id = loadingId; loadDiv.innerHTML = `<div class="bubble"><div class="typing-indicator"><div class="dots"><div class="dot"></div><div class="dot"></div><div class="dot"></div></div><span class="typing-status-text" id="${loadingId}_status"><span class="status-fade">Understanding your question…</span></span></div></div>`; document.getElementById('chatHistory').appendChild(loadDiv); c.scrollTo({top: c.scrollHeight, behavior: 'smooth'}); const thinkingStages = imgs.length ? ["Understanding your question…", "Reading the attached image" + (imgs.length > 1 ? "s…" : "…"), "Checking chapter memory…", "Drafting the answer…"] : ["Understanding your question…", "Checking chapter memory…", "Searching for the exact textbook wording…", "Drafting the answer…"]; let stageIdx = 0; const statusEl = () => document.getElementById(`${loadingId}_status`); const thinkingInterval = setInterval(() => { stageIdx = (stageIdx + 1) % thinkingStages.length; const el = statusEl(); if (el) el.innerHTML = `<span class="status-fade">${thinkingStages[stageIdx]}</span>`; }, 1300); let recentHistory = ""; let chatNodes = document.querySelectorAll('#chatHistory .msg'); let startIdx = Math.max(0, chatNodes.length - 8); for(let i = startIdx; i < chatNodes.length; i++) { let m = chatNodes[i]; if(m.id === loadingId) continue; let role = m.classList.contains('user') ? "User" : "AI"; let clone = m.cloneNode(true); let menuWrap = clone.querySelector('.msg-menu-wrap'); if(menuWrap) menuWrap.remove(); let msgText = clone.innerText.trim().replace(/\s+/g, ' '); if(msgText) recentHistory += `${role}: ${msgText}\n`; } let isEnglishSub = ['English', 'English Grammar', 'Computer Science', 'Information Technology'].includes(selectedData.subject); let targetLang = (isEnglishSub || !isHindiUI) ? 'ENGLISH' : 'HINDI (Devanagari script)'; let isMathSub = ['Mathematics', 'Physics', 'Chemistry', 'Science'].includes(selectedData.subject); 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}". STRICT RULES: 1. ALWAYS rewrite the user's core question at the very beginning of your answer in BOLD. 2. 🚫 CRITICAL MATH RULE: ZERO TEXT OR HINDI CHARACTERS INSIDE MATH BLOCKS ($ or $$). ONLY pure numbers, variables (like x, y), and operators. Write Hindi explanations strictly OUTSIDE the $$ blocks (e.g. Write "त्रिज्या $r = 5$ cm", NOT "$त्रिज्या = 5$"). MathJax will crash if Devanagari is inside. 3. Wrap crucial final facts in %%like this%%, important points in ??like this?? to add colors. You can write them multiple times. 🛑 STRICT MULTILINE WRAPPING RULE: NEVER wrap multiple lines, paragraphs, or bullet points inside a SINGLE pair of markers! Doing so breaks the UI. You MUST wrap EACH line individually! ❌ BAD: ??संविधान हमें क्यों चाहिए? मौलिक अधिकार?? ✅ GOOD: ??संविधान हमें কেন चाहिए??? ??मौलिक अधिकार?? 🚨 NEVER place these markers (!!, ??, %%) inside a $ or $$ LaTeX math block!`; if (isMathSub) { sysPrompt += `\n\n🚨 MATH TEMPLATE: For calculation questions, follow exactly: **1. [Step 1 Heading]** [Step 1 explanation in full words] $$[Equation without using \\frac]$$ **✅ Final Answer** [Final sentence in ${targetLang}]`; 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>.`; } else { sysPrompt += `\n\nIF SUBJECT IS NOT MATH OR SCIENCE, DO NOT INVENT MATH FORMULAS.`; } if(recentHistory) sysPrompt += `\n\n--- CHAT HISTORY ---\n${recentHistory}`; if (documentMemory) sysPrompt += `\n\n--- INBUILT CHAPTER MEMORY (real textbook search results — trust this over your own memory) ---\n${documentMemory.substring(0, 40000)}`; let payloadImgs = imgs; if (!payloadImgs.length && bookRecognitionImageBase64) { payloadImgs = [bookRecognitionImageBase64]; sysPrompt += `\nCRITICAL: Extract the text/questions strictly from the provided image.`; } // 🚨 LOCAL SEARCH EXCLUSION 🚨 UseSearch strictly set to false to prevent web fetching while conversing const payload = payloadImgs.length ? { imageBase64: payloadImgs[0], imageBase64Array: payloadImgs, userPrompt: text || "Please solve the questions visible in all the attached images.", systemPrompt: sysPrompt, useSearch: false } : { userPrompt: text || "Please provide the chapter exercises.", systemPrompt: sysPrompt, useSearch: false }; try { currentAbortController = new AbortController(); const endpoint = payloadImgs.length ? "/api/smart-search" : "/api/smart-search-stream"; const r = await fetch(endpoint, { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(payload), signal: currentAbortController.signal }); if(!r.ok) throw new Error("Server Connection Failed."); const bubbleHost = document.getElementById(loadingId); const ttsId = `tts_${Date.now()}_${Math.floor(Math.random()*10000)}`; let txtBox = null; const reader = r.body.getReader(); const decoder = new TextDecoder("utf-8"); let accumulatedText = ""; let sseBuffer = ""; let firstChunkReceived = false; while (true) { const { done, value } = await reader.read(); if (done) break; sseBuffer += decoder.decode(value, { stream: true }); const events = sseBuffer.split("\n\n"); sseBuffer = events.pop(); for (const ev of events) { const line = ev.trim(); if (!line.startsWith("data: ")) continue; const jsonStr = line.replace(/^data:\s*/, ""); if (!jsonStr || jsonStr === "[DONE]") continue; try { const eventData = JSON.parse(jsonStr); if (eventData.type === "error") throw new Error(eventData.message); if (eventData.type === "chunk") { if (!firstChunkReceived) { firstChunkReceived = true; clearInterval(thinkingInterval); if (bubbleHost) { bubbleHost.innerHTML = ` <div class="bubble"> <div style="font-size:10px; color:var(--primary); font-weight:900; margin-bottom:10px; text-transform:uppercase;">✨ VIA AI TUTOR</div> <div id="${ttsId}" class="markdown-body"></div> </div>`; txtBox = document.getElementById(ttsId); } } accumulatedText += eventData.text; // 🚨 IGNORING @@@URL@@@ 🚨 Cleaned the text silently before it hits the UI let cleanText = accumulatedText.replace(/\\times/g, '×').replace(/@@@.*?@@@/g, ''); cleanText = cleanText .replace(/!!([^!]+?)!!/g, '<span style="color: #ef4444; font-weight: 800;">$1</span>') .replace(/\?\?([^\?]+?)\?\?/g, '<span style="color: #3b82f6; font-weight: 800;">$1</span>') .replace(/%%([^%]+?)%%/g, '<span class="answer-highlight" style="background: rgba(59,130,246,0.20); color: #2563eb; font-weight: 800; padding: 2px 6px; border-radius: 6px;">$1</span>'); if (txtBox) txtBox.innerHTML = marked.parse(cleanText); const c = document.getElementById('chatHistory'); if (c) c.scrollTo({top: c.scrollHeight, behavior: 'instant'}); } } catch(e) { if (e.message !== "Unexpected end of JSON input") throw e; } } } if (!firstChunkReceived && bubbleHost) { clearInterval(thinkingInterval); bubbleHost.remove(); } if (bubbleHost) { const bubble = bubbleHost.querySelector('.bubble'); if (bubble) { let btnHtml = `<br><button class="listen-btn" onclick="window.playAudio(this)" data-target="${ttsId}">🔊 Listen</button>`; bubble.insertAdjacentHTML('beforeend', btnHtml + msgMenuHTML); if(window.MathJax) { MathJax.typesetClear([bubble]); MathJax.typesetPromise([bubble]); } } } window.saveHistorySafe(); window.triggerCloudSyncEngine(); window.resetSendButton(); } catch(err) { clearInterval(thinkingInterval); const loadingNode = document.getElementById(loadingId); if (loadingNode) loadingNode.remove(); let errorMsg = err.message; if(err.name === 'AbortError') errorMsg = "⚠️ Generation stopped by user."; const errDiv = document.createElement("div"); errDiv.className = "msg ai"; errDiv.innerHTML = `<div class="bubble">❌ <b style='color:#ef4444;'>Error:</b> ${errorMsg} ${msgMenuHTML}</div>`; document.getElementById('chatHistory').appendChild(errDiv); window.saveHistorySafe(); window.resetSendButton(); } } </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>Book Deep Study</title>
<link rel="manifest" href="/manifest.json">
<meta name="theme-color" content="#0f172a">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<script src="https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.min.js"></script>
<script>pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.worker.min.js';</script>
<script src="https://cdn.jsdelivr.net/npm/marked@4.3.0/marked.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.js"></script>
<script>
MathJax = {
options: { ignoreHtmlClass: 'code-box', processHtmlClass: 'markdown-body' },
tex: { inlineMath: [['$', '$'], ['\\(', '\\)']], displayMath: [['$$', '$$'], ['\\[', '\\]']] },
svg: { fontCache: 'global' }, chtml: { displayAlign: 'left' }
};
</script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<STYLE>
/* 1. AUTO LIGHT/DARK THEME SYSTEM */
:root {
/* DEFAULT LIGHT MODE */
--app-bg: #f8fafc;
--bg-base: #f8fafc;
--bg-surface: rgba(255, 255, 255, 0.85);
--input-bg: #ffffff;
--primary: #3b82f6;
--primary-glow: rgba(59, 130, 246, 0.25);
--secondary: #6366f1;
--accent: #10b981;
--text-main: #0f172a;
--text-muted: #64748b;
--border-light: rgba(0, 0, 0, 0.1);
--chat-user-bg: linear-gradient(135deg, #3b82f6, #2563eb);
--chat-user-text: #ffffff;
--chat-ai-bg: rgba(255, 255, 255, 0.9);
--chat-ai-border: rgba(0, 0, 0, 0.1);
--backdrop-blur: blur(16px);
}
@media (prefers-color-scheme: dark) {
:root {
/* OVERRIDE WITH DARK MODE */
--app-bg: #090d16;
--bg-base: #090d16;
--bg-surface: rgba(20, 29, 47, 0.85);
--input-bg: rgba(13, 20, 35, 0.6);
--text-main: #f8fafc;
--text-muted: #94a3b8;
--border-light: rgba(255, 255, 255, 0.08);
--chat-ai-bg: rgba(22, 32, 54, 0.5);
--chat-ai-border: rgba(255, 255, 255, 0.06);
}
}
/* Global Foundations */
html, body {
height: 100%; width: 100%; overflow: hidden; margin: 0; padding: 0;
font-family: 'Poppins', sans-serif; background: var(--app-bg); color: var(--text-main);
-webkit-font-smoothing: antialiased; transition: background-color 0.3s ease, color 0.3s ease;
}
/* 2. TOPBAR FIXES (Resizing & Squeezing) */
.topbar {
position: fixed; top: 0; left: 0; width: 100%; z-index: 500;
transition: transform 0.4s ease; display: flex; justify-content: space-between; align-items: center;
padding: 12px 20px; background: var(--bg-surface); border-bottom: 1px solid var(--border-light);
backdrop-filter: var(--backdrop-blur); -webkit-backdrop-filter: var(--backdrop-blur);
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05); box-sizing: border-box; gap: 10px;
}
.topbar.hidden { transform: translateY(-100%); }
.appTitle-container {
flex: 1; overflow-x: auto; white-space: nowrap; margin: 0 10px; position: relative;
border-radius: 8px; cursor: pointer; touch-action: pan-x; scrollbar-width: none;
}
.appTitle-container::-webkit-scrollbar { display: none; }
.appTitle { font-size: 16px; font-weight: 700; color: var(--text-main); display: inline-block; padding: 2px 0; }
.topbar-actions { display: flex; gap: 8px; flex-shrink: 0; align-items: center; }
/* Universal Buttons */
.btn {
padding: 10px 16px; font-weight: 600; border-radius: 12px; border: 1px solid transparent;
cursor: pointer; transition: all 0.2s ease; font-size: 14px;
display: inline-flex; align-items: center; justify-content: center; gap: 6px;
}
.btn-primary { background: linear-gradient(135deg, var(--primary), var(--secondary)); color: white; box-shadow: 0 4px 12px var(--primary-glow); }
.btn-primary:hover { transform: translateY(-2px); box-shadow: 0 6px 16px var(--primary-glow); filter: brightness(1.1); }
.btn-secondary {
background: var(--input-bg);