var LS=localStorage;
var FS = JSON.parse(LS.getItem('fs') || 'null') || {
decks:[],cards:[],notes:[],vocab:[],deckOrder:[],stats:{cs:0,sc:0,tt:0,sk:0},
pr:1500,prR:false,prT:null,sq:[],si:0,ss:0,st:0,exS:null,vi:0,exR:[],solH:[],
lang:'en',theme:'dark',au:false,mi:0,profilePic:null,currentStudy:null,
pomodoro:null,examResults:[],musicPlaying:false,studyPlans:[],calendarEvents:[],achievements:{},
currentMonth:new Date().getMonth(),currentYear:new Date().getFullYear(),
totalCardsCreated:0,totalExamsPassed:0,totalStudyMinutes:0,lastStudyDate:null,
studyStreak:0,flashcardsCreated:0,studyTopics:{},videoHistory:[],focusHistory:[]
};
// Global synchronization utility
const FlashcardSync = {
dbKey: 'flashsync_enterprise_cards',
// Get all cards currently in memory
getAllCards: function() {
return JSON.parse(localStorage.getItem(this.dbKey) || '[]');
},
// Clear memory
clearAll: function() {
localStorage.removeItem(this.dbKey);
location.reload();
}
};
function sv(){try{LS.setItem('fs',JSON.stringify(FS))}catch(e){}}
function showToast(m,t){
var e=document.getElementById('toast');if(!e)return;
e.textContent=m;e.className='toast show '+(t||'');
clearTimeout(e._h);e._h=setTimeout(function(){e.classList.remove('show')},3500);
}
function closeModal(e){
if(e&&e.target!==document.getElementById('modalOverlay'))return;
document.getElementById('modalOverlay').classList.remove('show');
}
function openModal(t,h){
document.getElementById('modalOverlay').classList.add('show');
document.getElementById('modalTitle').textContent=t;
document.getElementById('modalBody').innerHTML=h;
}
function escapeHtml(t){
var d=document.createElement('div');d.textContent=t;return d.innerHTML;
}
function confetti(){
var c=document.createElement('div');c.className='confetti';
document.body.appendChild(c);
for(var i=0;i<40;i++){
var p=document.createElement('div');p.className='confetti-piece';
p.style.left=Math.random()*100+'%';
p.style.background=['#00f2ff','#bc13fe','#ff006e','#00ff00','#ffaa00','#fff'][~~(Math.random()*6)];
p.style.animationDuration=(Math.random()*2+2)+'s';c.appendChild(p);
}
setTimeout(function(){c.remove()},4000);
}
function trackAction(action){
if(action=='card_created'){FS.flashcardsCreated=(FS.flashcardsCreated||0)+1;FS.totalCardsCreated=(FS.totalCardsCreated||0)+1;}
if(action=='exam_passed'){FS.totalExamsPassed=(FS.totalExamsPassed||0)+1;}
if(action=='study_minute'){FS.totalStudyMinutes=(FS.totalStudyMinutes||0)+1;}
if(action=='study_session'){
var today=new Date().toDateString();
if(FS.lastStudyDate!=today){FS.lastStudyDate=today;FS.studyStreak=(FS.studyStreak||0)+1;}
}
updateAchievements();sv();
}
function updateAchievements(){
var a=FS.achievements||{};
if(FS.totalCardsCreated>=1)a.firstCard=true;
if(FS.totalCardsCreated>=50)a.brainiac=true;
if(FS.studyStreak>=7)a.onFire=true;
if(FS.totalExamsPassed>=1)a.firstExam=true;
if(FS.totalExamsPassed>=10)a.examMaster=true;
if(FS.totalStudyMinutes>=6000)a.scholar=true;
if(FS.totalStudyMinutes>=600)a.dedicated=true;
FS.achievements=a;sv();
}
// REAL MUSIC - Web Audio API synthesizer AND MP3 player
var audioCtx = null;
var ambientAudio = null;
function getAudioCtx() {
if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
return audioCtx;
}
var musicTracks = [
{ name: 'Leberch Chill Ambient', type: 'file', src: 'http://localhost:8000/leberch-chill-ambient-music-248016.mp3' },
{ name: 'Lo-Fi Study', freq: 261.63, type: 'sine' },
{ name: 'Classical Focus', freq: 330, type: 'triangle' },
{ name: 'Nature Calm', freq: 392, type: 'sine' },
{ name: 'Acoustic Chill', freq: 440, type: 'triangle' },
{ name: 'Piano Study', freq: 523.25, type: 'triangle' },
{ name: 'Jazz Vibes', freq: 293.66, type: 'sawtooth' },
{ name: 'Electronic', freq: 349.23, type: 'square' }
];
var currentTrack = 0;
var musicIntervalId = null;
var noteTimeoutId = null;
var mp3TrackAudio = null;
function toggleMusic() {
var btn = document.querySelector('.music-btn') || document.getElementById('musicBtn');
if (!FS.musicPlaying) {
startMusic();
if (btn) {
btn.innerHTML = 'Playing: ' + musicTracks[currentTrack].name;
btn.className = 'accent-button compact-btn music-btn';
}
showToast('Playing: ' + musicTracks[currentTrack].name, 'success');
FS.stats.mi = (FS.stats.mi || 0) + 1; sv();
} else {
// Cycles to the next track on click instead of turning completely off!
currentTrack = (currentTrack + 1) % musicTracks.length;
playTrack();
if (btn) {
btn.innerHTML = 'Playing: ' + musicTracks[currentTrack].name;
}
showToast('Switched to: ' + musicTracks[currentTrack].name, 'success');
}
}
function stopMusic() {
FS.musicPlaying = false; sv();
if (noteTimeoutId) { clearInterval(noteTimeoutId); noteTimeoutId = null; }
if (musicIntervalId) { clearInterval(musicIntervalId); musicIntervalId = null; }
// Kill MP3 file playback if it's currently running
if (mp3TrackAudio) {
mp3TrackAudio.pause();
mp3TrackAudio.currentTime = 0;
mp3TrackAudio = null;
}
}
function startMusic() {
FS.musicPlaying = true; sv();
playTrack();
if (musicIntervalId) clearInterval(musicIntervalId);
// Auto-advance song every 25 seconds
musicIntervalId = setInterval(function () {
if (!FS.musicPlaying) { clearInterval(musicIntervalId); return; }
currentTrack = (currentTrack + 1) % musicTracks.length;
var btn = document.querySelector('.music-btn') || document.getElementById('musicBtn');
if (btn) btn.innerHTML = 'Playing: ' + musicTracks[currentTrack].name;
playTrack();
}, 25000);
}
function toggleAmbientMusic() {
var btn = document.getElementById('ambientBtn');
if (ambientAudio && !ambientAudio.paused) {
ambientAudio.pause();
ambientAudio.currentTime = 0;
ambientAudio = null;
if (btn) {
btn.innerHTML = ' Play Ambient';
btn.className = 'accent-button compact-btn';
}
showToast('Ambient music stopped', 'error');
} else {
if (!ambientAudio) {
ambientAudio = new Audio('/leberch-chill-ambient-music-248016.mp3');
ambientAudio.loop = true;
ambientAudio.volume = 0.5;
}
ambientAudio.play().then(function () {
if (btn) {
btn.innerHTML = 'Playing: Leberch Chill Ambient';
btn.className = 'success-button compact-btn';
}
showToast('Playing: Leberch Chill Ambient', 'success');
FS.stats.mi = (FS.stats.mi || 0) + 1; sv();
}).catch(function (e) {
showToast('Error playing music: ' + e.message, 'error');
});
}
}
function playTrack() {
try {
// 1. ALWAYS clean up previous music processes first
if (noteTimeoutId) { clearInterval(noteTimeoutId); noteTimeoutId = null; }
if (mp3TrackAudio) { mp3TrackAudio.pause(); mp3TrackAudio.currentTime = 0; mp3TrackAudio = null; }
if (!FS.musicPlaying) return;
var track = musicTracks[currentTrack];
// 2. CHECK: Is this an MP3 file track or Synth track?
if (track.type === 'file') {
// Create empty audio element first to attach cross-origin rules safely
mp3TrackAudio = new Audio();
// ๐ FIX: Tells the browser it's safe to read the file across localhost ports (CORS)
mp3TrackAudio.crossOrigin = "anonymous";
mp3TrackAudio.src = track.src;
mp3TrackAudio.volume = 0.4;
mp3TrackAudio.play().catch(function(e) {
console.log("Audio block context waiting: " + e.message);
});
} else {
// It's a normal synthesizer note sequence track!
var ctx = getAudioCtx();
var playNote = function () {
if (!FS.musicPlaying || musicTracks[currentTrack].type === 'file') return;
var currentSynth = musicTracks[currentTrack];
var osc = ctx.createOscillator();
var gain = ctx.createGain();
osc.type = currentSynth.type;
osc.frequency.setValueAtTime(currentSynth.freq * (0.5 + Math.random() * 0.5), ctx.currentTime);
gain.gain.setValueAtTime(0.06, ctx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.3);
osc.connect(gain);
gain.connect(ctx.destination);
osc.start();
osc.stop(ctx.currentTime + 0.3);
};
playNote();
noteTimeoutId = setInterval(playNote, 450);
}
} catch (e) {
showToast('Click to enable audio channel', 'error');
}
}
// ACHIEVEMENTS
function checkAndUpdateAchievements(type,value){
var a=FS.achievements||{};
if(type=='cards'&&FS.flashcardsCreated>=1&&!a.firstCard){a.firstCard=true;showToast('Achievement: First Card!','success');confetti();}
if(type=='cards'&&FS.flashcardsCreated>=50&&!a.brainiac){a.brainiac=true;showToast('Achievement: Brainiac (50 cards)!','success');confetti();}
if(type=='streak'&&FS.studyStreak>=7&&!a.onFire){a.onFire=true;showToast('Achievement: On Fire (7-day)!','success');confetti();}
if(type=='exam'&&FS.totalExamsPassed>=1&&!a.firstExam){a.firstExam=true;showToast('Achievement: First Exam!','success');confetti();}
if(type=='exam'&&FS.totalExamsPassed>=10&&!a.examMaster){a.examMaster=true;showToast('Achievement: Exam Master!','success');confetti();}
if(type=='minutes'&&FS.totalStudyMinutes>=600&&!a.dedicated){a.dedicated=true;showToast('Achievement: Dedicated (10h)!','success');confetti();}
if(type=='minutes'&&FS.totalStudyMinutes>=6000&&!a.scholar){a.scholar=true;showToast('Achievement: Scholar (100h)!','success');confetti();}
FS.achievements=a;sv();
}
// AUTH
function login(){
var n=document.getElementById('user');
FS.stats.cs++;sv();
showToast('Welcome '+(n?n.value:'Student')+'!','success');
setTimeout(function(){location.href='/hub'},500);
}
// DECK MANAGEMENT
function addDeck(){
var f=document.getElementById('newDeckName'),n=f&&f.value.trim();
if(!n){showToast('Enter a deck name!','error');return;}
FS.decks.push({id:Date.now()+'',name:n,cc:0,ca:new Date().toISOString(),my:0});
sv();confetti();showToast('Deck '+n+' created!','success');
setTimeout(function(){location.href='/flashcards?refresh='+Date.now()},600);
}
function openDeck(t){
if(t==='biology'||t==='chemistry') location.href='/flashcards/'+t;
else location.href='/flashcards?deck='+encodeURIComponent(t);
}
function importCards(){
var i=document.createElement('input');i.type='file';i.accept='.json,.csv,.txt';
i.onchange=function(e){
var f=e.target.files[0];if(!f)return;
var r=new FileReader();
r.onload=function(ev){
try{
var d=JSON.parse(ev.target.result);
if(d&&d.cards){
if(Array.isArray(d.cards))FS.cards=FS.cards.concat(d.cards);
if(d.decks)FS.decks=FS.decks.concat(d.decks);
sv();confetti();showToast('Imported!','success');
setTimeout(function(){location.reload()},800);return;
}
}catch(e){}
var txt=ev.target.result,lines=txt.split(/\r?\n/),c=0;
for(var i=0;i=2){FS.cards.push({id:Date.now()+'-'+i,question:p[0].trim(),answer:p.slice(1).join(',').trim(),deckId:'imp',ca:new Date().toISOString(),my:0});c++;}
}
if(c>0){sv();confetti();showToast('Imported '+c+' cards!','success');setTimeout(function(){location.reload()},800);}
else showToast('Could not parse file','error');
};r.readAsText(f);
};i.click();
}
function exportPDF(){
if(!FS.cards.length){showToast('No cards to export!','error');return;}
var h='FlashSync Study Cards
FlashSync Study Cards
Total: '+FS.cards.length+' cards
';
for(var i=0;i
'+(i+1)+'. '+escapeHtml(c.question)+'
'+(c.answer||'No answer')+'
';
}
h+='';
var b=new Blob([h],{type:'text/html'});var l=document.createElement('a');
l.href=URL.createObjectURL(b);l.download='flashsync-cards-'+Date.now()+'.html';
l.click();URL.revokeObjectURL(l.href);confetti();showToast('PDF exported!','success');
}
function exportDeckData(){
var p=JSON.stringify({decks:FS.decks,cards:FS.cards,exportedAt:new Date().toISOString()},null,2);
var b=new Blob([p],{type:'application/json'}),l=document.createElement('a');
l.href=URL.createObjectURL(b);l.download='flashsync-export.json';
l.click();URL.revokeObjectURL(l.href);confetti();showToast('Deck data exported!','success');
}
function preparePrintMode(){
if(!FS.cards.length){showToast('No cards to print!','error');return;}
var h='FlashSync Print Pack
FlashSync Print Pack
Cut along dotted lines
';
for(var i=0;i
Card '+(i+1)+': '+escapeHtml(c.question)+'
Answer: '+(c.answer||'No answer')+'
--- CUT HERE ---
';
}
h+='';var b=new Blob([h],{type:'text/html'});var l=document.createElement('a');
l.href=URL.createObjectURL(b);l.download='flashsync-print-pack-'+Date.now()+'.html';
l.click();URL.revokeObjectURL(l.href);confetti();showToast('Print pack downloaded!','success');
}
// STUDY SESSION
function startStudySession(){
if(!FS.currentStudy||!FS.currentStudy.cards.length){showToast('No cards to study!','error');return;}
var card=FS.currentStudy.cards[FS.currentStudy.index];
var h='
Question
'+escapeHtml(card.question)+'
';
h+='
Answer
'+escapeHtml(card.answer)+'
';
h+='
Card '+(FS.currentStudy.index+1)+' of '+FS.currentStudy.cards.length+'
';
openModal('Study Session',h);
}
function showAnswer(id){var box=document.getElementById('answerBox');if(box)box.style.display='block';}
function rateCard(quality,id){
var card=FS.cards.find(function(c){return c.id===id;});
if(card){card.my=quality;sv();showToast('Rated: '+['Easy','Medium','Hard'][quality-1],'success');nextCard();}
}
function nextCard(){
if(FS.currentStudy.index0){FS.currentStudy.index--;sv();startStudySession();}}
function startReviewSession(){
if(!FS.currentStudy||!FS.currentStudy.cards.length){showToast('No cards to review!','error');return;}
var dueCards=FS.currentStudy.cards.filter(function(c){return c.my<3;});
if(!dueCards.length){showToast('All cards reviewed!','success');return;}
FS.currentStudy.cards=dueCards;FS.currentStudy.index=0;startStudySession();
}
function studyDeckByTopic(t){
var deck=FS.decks.find(function(d){return d.id===t||d.name.toLowerCase().includes(t.toLowerCase());});
if(deck){
FS.currentStudy={deckId:t,cards:FS.cards.filter(function(c){return c.deckId===t;}),index:0,mode:'study'};sv();
openModal('Study: '+t,'
Study Mode
Cards: '+FS.currentStudy.cards.length+'
');
} else showToast('Deck not found!','error');
}
function reviewDeckByTopic(t){
var deck=FS.decks.find(function(d){return d.id===t||d.name.toLowerCase().includes(t.toLowerCase());});
if(deck){
FS.currentStudy={deckId:t,cards:FS.cards.filter(function(c){return c.deckId===t;}),index:0,mode:'review'};sv();
openModal('Review: '+t,'
Review Mode
Cards: '+FS.currentStudy.cards.length+'
');
} else showToast('Deck not found!','error');
}
// SOLVER
function generateSolution(p){
var l=p.toLowerCase();
var s='
Analysis: '+escapeHtml(p)+' Explanation: Break down fundamentals, define clearly, give examples.
';
} else {s+='
Analysis: 1. Identify key concepts 2. Break into parts 3. Apply principles 4. Work step by step
';}
return s+'
';
}
async function solveProblem(){
var f=document.getElementById('problemText'),r=document.getElementById('solverResult');
var q=f?f.value.trim():'';if(!q||!r){showToast('Enter a problem!','error');return;}
r.style.display='block';r.innerHTML='
Analyzing...
';
try{
var resp=await fetch('/api/solver?q='+encodeURIComponent(q),{headers:{accept:'text/html'}});
if(!resp.ok)throw Error();
r.innerHTML=await resp.text();FS.solH.push({p:q,s:'Server',d:new Date().toISOString()});sv();confetti();
}catch(e){r.innerHTML=generateSolution(q);FS.solH.push({p:q,s:'Local',d:new Date().toISOString()});sv();confetti();}
}
function handleFileUpload(){
var f=document.getElementById('problemFile');
if(!f||!f.files||!f.files[0])return;
var img=document.getElementById('previewImg');var prev=document.getElementById('imagePreview');
if(img&&prev){
var reader=new FileReader();
reader.onload=function(e){img.src=e.target.result;prev.style.display='block';showToast('Image loaded!','success');};
reader.readAsDataURL(f.files[0]);
}
}
// ========== ENHANCED IMAGE ANALYSIS ==========
function analyzeImageWithAI(imageDataUrl){
// Extract image properties and metadata for analysis
return new Promise(function(resolve){
var img=new Image();
img.onload=function(){
var canvas=document.createElement('canvas');
canvas.width=img.width;canvas.height=img.height;
var ctx=canvas.getContext('2d');
ctx.drawImage(img,0,0);
// Analyze image characteristics
var imageData=ctx.getImageData(0,0,canvas.width,canvas.height);
var pixels=imageData.data;
var totalPixels=pixels.length/4;
var brightness=0,rCount=0,gCount=0,bCount=0;
var colorMap={};
// Sample pixels for color analysis
for(var i=0;i200&&g<100&&b<100) rCount++;
if(g>200&&r<100&&b<100) gCount++;
if(b>200&&r<100&&g<100) bCount++;
// Quantize colors to detect major color regions
var key=Math.round(r/64)+','+Math.round(g/64)+','+Math.round(b/64);
colorMap[key]=(colorMap[key]||0)+1;
}
var avgBrightness=brightness/(totalPixels/16);
var isDark=avgBrightness<100;
var isBright=avgBrightness>180;
var hasRed=rCount>totalPixels/200;
var hasGreen=gCount>totalPixels/200;
var hasBlue=bCount>totalPixels/200;
// Detect if image appears to be text/document
var aspectRatio=img.width/img.height;
var isDocument=aspectRatio>0.7&&aspectRatio<1.5&&isBright;
var isDiagram=hasRed||hasBlue||hasGreen;
var isPhoto=!isDocument&&!isDiagram;
// Generate analysis report
var analysis={
width:img.width,
height:img.height,
aspectRatio:aspectRatio.toFixed(2),
brightness:avgBrightness.toFixed(0),
isDark:isDark,
isDocument:isDocument,
isDiagram:isDiagram,
isPhoto:isPhoto,
hasText:isDocument,
dominantColors:findDominantColors(colorMap)
};
resolve(analysis);
};
img.src=imageDataUrl;
});
}
function findDominantColors(colorMap){
var sorted=Object.keys(colorMap).sort(function(a,b){return colorMap[b]-colorMap[a];});
var colorNames={
'0,0,0':'Black','3,3,3':'Dark Gray','2,2,2':'Gray','1,1,1':'Light Gray',
'0,0,3':'Dark Blue','0,0,2':'Blue','0,0,1':'Light Blue',
'0,3,0':'Dark Green','0,2,0':'Green','0,1,0':'Light Green',
'3,0,0':'Dark Red','2,0,0':'Red','1,0,0':'Light Red',
'3,3,0':'Yellow','0,3,3':'Cyan','3,0,3':'Magenta',
'3,3,3':'White','2,3,3':'Light Cyan','3,2,3':'Light Magenta','3,3,2':'Light Yellow'
};
var top= sorted.slice(0,3).map(function(k){return colorNames[k]||'Color#'+k;});
return top;
}
async function solveFromImage(){
var img=document.getElementById('previewImg');
if(!img||!img.src){showToast('No image loaded!','error');return;}
var r=document.getElementById('solverResult');
if(!r){showToast('Not found','error');return;}
r.style.display='block';r.innerHTML='
๐ Analyzing image with AI...
';
try{
var analysis=await analyzeImageWithAI(img.src);
var html='
';
html+='๐จ Visual Analysis: ';
html+='Type: '+(analysis.isDocument?'๐ Document/Text':analysis.isDiagram?'๐ Diagram/Graph':'๐ผ๏ธ Photo/Image')+' ';
html+='Dominant Colors: '+analysis.dominantColors.join(', ')+' ';
if(analysis.isDocument) html+='โ High probability of containing readable text ';
html+='
';
html+='
';
html+='๐ก Interpretation: ';
if(analysis.isDocument){
html+='This appears to be a document or text-based image. The content likely contains written information that can be extracted and studied. Try typing the text manually into the text solver below for a detailed solution.';
} else if(analysis.isDiagram){
html+='This appears to be a diagram, chart, or graph. '+(analysis.dominantColors.includes('Red')?'Red elements suggest important data points. ':'')+(analysis.dominantColors.includes('Blue')?'Blue elements may indicate water/background. ':'');
} else {
html+='This is a photograph or complex image. The AI has analyzed its visual properties. For specific content extraction, please describe what you see and I can help explain the related concepts.';
}
html+='
Image processed successfully. To solve specific problems from this image, please type the question in the text field below.
';
FS.solH.push({p:'Image processed',s:'Local',d:new Date().toISOString()});sv();showToast('Processed!','success');
}
}
function solveQuickProblem(){
var f=document.getElementById('quickSolverInput'),r=document.getElementById('quickSolverResult');
var q=f?f.value.trim():'';if(!q||!r){showToast('Enter problem!','error');return;}
r.style.display='block';r.innerHTML=generateSolution(q);confetti();showToast('Done!','success');
}
// FLASHCARDS
function createFlashcard(q,a){
a=a||'';FS.cards.push({id:Date.now()+'',question:q,answer:a,deckId:'study',ca:new Date().toISOString(),my:0});
FS.flashcardsCreated=(FS.flashcardsCreated||0)+1;FS.totalCardsCreated=(FS.totalCardsCreated||0)+1;
sv();confetti();showToast('Flashcard created!','success');
trackAction('card_created');checkAndUpdateAchievements('cards',FS.flashcardsCreated);
setTimeout(function(){location.href='/flashcards?refresh='+Date.now()},600);
}
function generateStudyQuestions(){
var t=document.getElementById('studyTopic'),topic=t?t.value.trim()||'General':'General';
var o=document.getElementById('studyGenerated');if(!o)return;
o.style.display='block';o.innerHTML='
Generating for '+topic+'...
';
setTimeout(function(){
var qs=['Define '+topic,'How does '+topic+' work?','Real-world use of '+topic,'Compare '+topic+' to related topics','Why is '+topic+' important?'];
var html='
Questions Generated
';
for(var i=0;i
Q'+(i+1)+': '+qs[i]+'
';}
html+='';o.innerHTML=html;confetti();
},1000);
}
// AI TUTOR
async function sendTutorMessage(){
var inp=document.getElementById('tutorInput'),msg=document.getElementById('chatMessages');
if(!inp||!msg)return;var q=inp.value.trim();if(!q)return;
inp.value='';
var u=document.createElement('div');u.className='message user';
u.innerHTML='You:
'+escapeHtml(q)+'
';
msg.appendChild(u);msg.scrollTop=msg.scrollHeight;
var a=document.createElement('div');a.className='message ai';
a.innerHTML='AI:
';
msg.appendChild(a);msg.scrollTop=msg.scrollHeight;
try{
var r=await fetch('/api/tutor?q='+encodeURIComponent(q),{headers:{accept:'text/html'}});
if(!r.ok)throw Error();
a.innerHTML='AI:
'+await r.text()+'
';
}catch(e){a.innerHTML='AI:
'+localResponse(q)+'
';}
msg.scrollTop=msg.scrollHeight;
}
function askTutor(q){
var inp=document.getElementById('tutorInput');
if(inp){inp.value=q;sendTutorMessage();}else location.href='/tutor?q='+encodeURIComponent(q);
}
function clearChat(){
var msg=document.getElementById('chatMessages');
if(msg){msg.innerHTML='
AI: Chat cleared!
';showToast('Cleared','success');}
}
function localResponse(q){
q=q.toLowerCase();
if(q.includes('photosynthesis'))return'
Photosynthesis: Plants convert light energy to glucose.
';
}
// ========== ENHANCED EDUCATION PORTAL ==========
function selectGrade(grade){
var labels={elementary:'Elementary (Ages 5-11)',middle:'Middle School (Ages 11-14)',hs:'High School (Ages 14-18)',college:'College/University',professional:'Professional/Adult Learning'};
var insights={
elementary:'
Elementary Mode Active
Using simple vocabulary, concrete examples, and everyday analogies. Focus on building foundational understanding with visual aids and step-by-step explanations.
Balancing abstract concepts with concrete examples. Introducing diagrams, structured note-taking, and guided problem-solving.
๐ฏ Recommended For: Grades 6-8, building study habits
',
hs:'
High School Mode Active
Detailed explanations with analytical thinking, exam-style questions, and comprehensive summaries. Preparing for standardized tests and college readiness.
Critical analysis, research-level depth, scholarly perspectives, and advanced problem-solving. Emphasis on independent thinking and academic writing.
๐ฏ Recommended For: University students, self-directed learners
',
professional:'
Professional Mode Active
Industry applications, case studies, advanced material with real-world relevance. Focus on practical implementation and professional development.
๐ฏ Recommended For: Working professionals, lifelong learners
'
};
var s=document.getElementById('gradeStatus'),i=document.getElementById('gradeInsights');
if(s)s.textContent='Selected: '+(labels[grade]||grade);
if(i)i.innerHTML=(insights[grade]||'
Custom Path
Personalized learning journey.
');
FS.currentGrade=grade;sv();showToast('Grade set to '+(labels[grade]||grade),'success');
}
// ========== ENHANCED YOUTUBE VIDEO PROCESSING ==========
function processYouTubeVideo(){
var url=document.getElementById('youtubeUrl');
var result=document.getElementById('youtubeProcessResult');
if(!url||!url.value.trim()){showToast('Enter URL!','error');return;}
if(result){
result.style.display='block';result.innerHTML='
๐ฌ Analyzing video content...
';
// Extract video ID and detect topic
var videoUrl=url.value.trim();
var videoId=extractVideoId(videoUrl);
var topic=detectVideoTopicFromUrl(videoUrl);
var grade=FS.currentGrade||'elementary';
var gradeLabel={elementary:'Elementary',middle:'Middle School',hs:'High School',college:'College',professional:'Professional'}[grade]||grade;
setTimeout(function(){
var studyContent=generateVideoStudyContent(videoId,topic,grade);
result.innerHTML=studyContent;
FS.videoHistory=FS.videoHistory||[];
FS.videoHistory.push({url:videoUrl,topic:topic,grade:grade,date:new Date().toISOString()});
sv();
confetti();
showToast('Video processed! Study materials ready.','success');
},2000);
}
}
function extractVideoId(url){
var match=url.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]{11})/);
return match?match[1]:'unknown';
}
function detectVideoTopicFromUrl(url){
var lower=url.toLowerCase();
var keywords=[
['biology','๐งฌ Biology'],['chemistry','โ๏ธ Chemistry'],['physics','๐ญ Physics'],
['math','๐ Mathematics'],['calculus','โซ Calculus'],['algebra','โ๏ธ Algebra'],
['quantum','โ๏ธ Quantum Mechanics'],['thermodynamics','๐ฅ Thermodynamics'],
['dna','๐งช DNA & Genetics'],['photosynthesis','๐ฟ Photosynthesis'],
['programming','๐ป Programming'],['coding','๐จโ๐ป Coding'],
['history','๐ History'],['philosophy','๐ค Philosophy'],
['economics','๐ฐ Economics'],['psychology','๐ง Psychology'],
['literature','๐ Literature'],['engineering','โ๏ธ Engineering'],
['machine learning','๐ค Machine Learning'],['ai','๐ง Artificial Intelligence'],
['tutorial','๐ Tutorial'],['lecture','๐ Lecture'],['lesson','๐ Lesson'],
['science','๐ฌ Science'],['education','๐ Education']
];
for(var i=0;i Video Processed Successfully!';
html+='
Format: Complete Study Pack with Notes, Questions & Summaries
';
pdf+='
85% Complete Study Pack
';
pdf+='
';
// Section 1: Overview
pdf+='
';
pdf+='
๐ 1. Topic Overview
';
pdf+='
This study guide provides a comprehensive breakdown of '+topic+', adapted for '+gradeLabel+' level understanding. The material has been structured to promote active learning and long-term retention.
';
pdf+='
๐ก Core Understanding: '+topic+' is a fundamental concept that builds upon foundational knowledge. Mastery of this topic enables deeper exploration of related subjects and practical applications.
';
pdf+='
๐ Key Definition: '+topic+' encompasses the essential principles, theories, and applications that form the basis of understanding in this field of study.
';
pdf+='
';
// Section 2: Key Points
pdf+='
';
pdf+='
๐ฏ 2. Key Learning Points
';
pdf+='
';
pdf+='
#
Topic Area
Importance
Study Focus
';
pdf+='
1
Fundamental Principles
โญโญโญโญโญ
Master definitions and core concepts
';
pdf+='
2
Mechanisms & Processes
โญโญโญโญ
Understand how components interact
';
pdf+='
3
Real-World Applications
โญโญโญโญโญ
Connect theory to practice
';
pdf+='
4
Common Misconceptions
โญโญโญ
Identify and avoid frequent errors
';
pdf+='
5
Advanced Connections
โญโญโญโญ
Relate to broader knowledge framework
';
pdf+='
';
pdf+='
';
// Section 3: Vocabulary
pdf+='
';
pdf+='
๐ 3. Key Vocabulary & Terms
';
pdf+='
Core Concept: The central idea or principle that defines the topic.
';
pdf+='
Mechanism: The process or system through which the concept operates.
';
pdf+='
Application: A practical use or real-world implementation of the concept.
';
pdf+='
Variable: An element that can change and affect outcomes.
';
pdf+='
Framework: A structured approach to understanding or analyzing the topic.
';
pdf+='
Hypothesis: A proposed explanation that can be tested.
';
pdf+='
Analysis: Detailed examination of elements and their relationships.
';
pdf+='
';
// Section 4: Study Questions
pdf+='
';
pdf+='
๐ 4. Review Questions
';
pdf+='
Q1: Define '+topic+' in your own words and explain why it is important.
';
pdf+='
Q2: Describe how '+topic+' works. What are the key components or steps?
';
pdf+='
Q3: Provide three real-world examples of '+topic+' in action.
';
pdf+='
Q4: Compare '+topic+' to a related concept. What are the similarities and differences?
';
pdf+='
Q5: What are common mistakes people make when learning about '+topic+'? How can they be avoided?
';
pdf+='
';
// Section 5: Study Tips
pdf+='
';
pdf+='
๐ก 5. Study Strategies & Tips
';
pdf+='
Active Recall: After studying, close your notes and try to recall the main points from memory. This strengthens neural pathways.
';
pdf+='
Spaced Repetition: Review this material after 1 day, then 3 days, 1 week, 2 weeks, and 1 month. FlashSync automates this!
';
pdf+='
Feynman Technique: Explain this topic to someone else in simple terms. If you struggle, revisit the material.
';
pdf+='
Dual Coding: Draw diagrams or mind maps alongside your notes to engage visual memory.
';
pdf+='
Practice Testing: Use the review questions above to test your understanding. Aim for 80%+ before moving on.
';
pdf+='
';
// Section 6: Checklist
pdf+='
';
pdf+='
โ 6. Mastery Checklist
';
pdf+='
Track your progress as you study:
';
pdf+='
';
pdf+='
I can define '+topic+' in one sentence
';
pdf+='
I understand the key mechanisms and processes
';
pdf+='
I can provide at least two real-world examples
';
pdf+='
I can explain this to someone else
';
pdf+='
I have created flashcards for the key terms
';
pdf+='
I can answer the review questions correctly
';
pdf+='
I understand how this connects to other topics I know
';
pdf+='
I have practiced with related problems or questions
';
pdf+='
';
pdf+='
Start Studying!
';
pdf+='
';
// Footer
pdf+='';
pdf+='';
var b=new Blob([pdf],{type:'text/html'});var l=document.createElement('a');
l.href=URL.createObjectURL(b);l.download='FlashSync-StudyGuide-'+topic.replace(/\s+/g,'-')+'.html';
l.click();URL.revokeObjectURL(l.href);confetti();showToast('PDF Study Guide downloaded!','success');
}
// ========== DOWNLOAD PDF BUTTON FIX (Education Portal) ==========
function downloadPDFStudyGuide(topic){
var date=new Date().toLocaleDateString('en-US',{year:'numeric',month:'long',day:'numeric'});
var content=typeof topic==='string'?topic:'Study Material';
var pdf='Study Guide - '+content+'';
pdf+='
';
pdf+='
๐ '+content+'
';
pdf+='
Comprehensive Study Guide & Learning Materials
';
pdf+='
Generated: '+date+' | FlashSync Pro
';
pdf+='
Premium Study Pack
';
pdf+='
';
pdf+='
๐ Topic Summary
';
pdf+='
This comprehensive guide covers '+content+' with structured notes, key vocabulary, review questions, and study strategies designed for optimal learning and retention.
';
pdf+='
๐ก Key Insight: '+content+' is a fundamental area of study that builds critical thinking skills and provides a foundation for advanced learning. Understanding this topic opens doors to deeper knowledge and practical applications.
';
pdf+='
';
pdf+='
๐ฏ Learning Objectives
';
pdf+='
Objective
Mastery Level
';
pdf+='
Understand core concepts and definitions
โญโญโญโญโญ
';
pdf+='
Explain mechanisms and processes
โญโญโญโญ
';
pdf+='
Apply knowledge to real-world scenarios
โญโญโญโญโญ
';
pdf+='
Analyze and evaluate related ideas
โญโญโญโญ
';
pdf+='
Synthesize information across topics
โญโญโญ
';
pdf+='
';
pdf+='
๐ Key Terminology
';
pdf+='
Core Principle: The fundamental law or concept that governs this topic.
';
pdf+='
Mechanism: The process or system through which the concept operates.
';
pdf+='
Variable: An element that can change and influence outcomes.
';
pdf+='
Framework: A structured approach for analysis and understanding.
';
pdf+='
';
pdf+='
๐ Review Questions
';
pdf+='
Q1: Define '+content+' and explain its significance.
';
pdf+='
Q2: How does '+content+' work? Describe the key process.
';
pdf+='
Q3: Provide examples of '+content+' in real-world contexts.
';
pdf+='
Q4: What are common misconceptions about '+content+'?
';
pdf+='
Q5: How does '+content+' connect to other topics you have studied?
';
pdf+='
';
pdf+='
๐ก Study Tips
';
pdf+='
Active Recall: Test yourself regularly instead of passive re-reading.
';
pdf+='
Spaced Repetition: Review at increasing intervals for long-term retention.
';
pdf+='
Feynman Technique: Teach the concept to someone else in simple terms.
';
pdf+='
Practice Problems: Apply what you learn through exercises and questions.
';
pdf+='
';
pdf+='
โ Mastery Checklist
';
pdf+='
';
pdf+='
I can define the topic in my own words
';
pdf+='
I understand the key mechanisms
';
pdf+='
I can provide real-world examples
';
pdf+='
I have tested my knowledge with questions
';
pdf+='
I have created study flashcards
';
pdf+='
I can teach this to someone else
';
pdf+='
';
pdf+='';
var b=new Blob([pdf],{type:'text/html'});var l=document.createElement('a');
l.href=URL.createObjectURL(b);l.download='FlashSync-Study-Guide-'+content.replace(/\s+/g,'-')+'.html';
l.click();URL.revokeObjectURL(l.href);confetti();showToast('Study Guide downloaded!','success');
}
// POMODORO
function startPomodoro(){
var btn=document.getElementById('pomodoroBtn'),display=document.getElementById('pomodoroDisplay'),label=document.getElementById('pomodoroLabel');
if(!display||!label)return;
if(FS.pomodoro&&FS.pomodoro.running){showToast('Already running!','error');return;}
if(btn)btn.innerHTML='Pause';
var total=FS.pomodoro&&FS.pomodoro.remaining?FS.pomodoro.remaining:1500;
FS.pomodoro={running:true,remaining:total,isBreak:false,interval:null};
if(label)label.textContent='Focus Session';
if(FS.pomodoro.interval)clearInterval(FS.pomodoro.interval);
FS.pomodoro.interval=setInterval(function(){
if(!FS.pomodoro||!FS.pomodoro.running)return;
FS.pomodoro.remaining--;var min=Math.floor(FS.pomodoro.remaining/60),sec=FS.pomodoro.remaining%60;
display.textContent=(min<10?'0':'')+min+':'+(sec<10?'0':'')+sec;
if(FS.pomodoro.remaining<=0){
clearInterval(FS.pomodoro.interval);
if(!FS.pomodoro.isBreak){
FS.pomodoro.remaining=300;FS.pomodoro.isBreak=true;display.textContent='05:00';
if(label)label.textContent='Break!';showToast('Focus done! Take a break!','success');
if(btn)setTimeout(function(){startPomodoro();},1000);
} else {
if(label)label.textContent='Ready!';display.textContent='25:00';FS.pomodoro=null;
showToast('Break over!','success');confetti();
if(btn)btn.innerHTML='Start';FS.stats.tt=(FS.stats.tt||0)+25;trackAction('study_minute');sv();
}
}
if(FS.pomodoro.remaining<=60&&FS.pomodoro.remaining>0)display.style.color='var(--accent)';
else display.style.color='var(--primary)';
},1000);sv();
}
function stopPomodoro(){
if(FS.pomodoro&&FS.pomodoro.interval)clearInterval(FS.pomodoro.interval);
FS.pomodoro=null;
var d=document.getElementById('pomodoroDisplay'),l=document.getElementById('pomodoroLabel'),b=document.getElementById('pomodoroBtn');
if(d){d.textContent='25:00';d.style.color='var(--primary)';}if(l)l.textContent='Ready';if(b)b.innerHTML='Start';
showToast('Reset','error');
}
function logTime(){ window.incrementStat('pomo', 1); window.incrementStat('hours', 0.1);
FS.stats.tt=(FS.stats.tt||0)+5;trackAction('study_minute');sv();
var display=document.getElementById('pomodoroDisplay');
window.incrementStat('pomo', 1);
if(display){
var p=FS.pomodoro||{remaining:1500};p.remaining=Math.max(0,p.remaining-300);
if(FS.pomodoro)FS.pomodoro.remaining=p.remaining;
var min=Math.floor(p.remaining/60),sec=p.remaining%60;
display.textContent=(min<10?'0':'')+min+':'+(sec<10?'0':'')+sec;
window.incrementStat('hours', 0.4);
}
showToast('+5 min logged!','success');
}
// VOCABULARY
// Ensure global FlashSync state exists safely so it never crashes
if (typeof FS === 'undefined') {
var FS = { vocab: [], stats: {} };
}
if (typeof FS.vocab === 'undefined') {
FS.vocab = [];
}
// 1. ADDED MISSING HELPER: Safe HTML Escaping utility to prevent injection crashes
function escapeHtml(string) {
if (!string) return '';
return String(string).replace(/[&<>"']/g, function (s) {
return {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}[s];
});
}
// Fallback for save function if sv() isn't globally available
if (typeof sv !== 'function') {
var sv = function() { console.log("State auto-saved locally:", FS); };
}
function learnNewWord(){
var words=[
{word:'Ephemeral',meaning:'Lasting for a very short time',example:'The beauty of cherry blossoms is ephemeral.'},
{word:'Ubiquitous',meaning:'Present, appearing, or found everywhere',example:'Smartphones have become ubiquitous in modern society.'},
{word:'Pragmatic',meaning:'Dealing with things sensibly and realistically',example:'We need a pragmatic approach to solve this problem.'},
{word:'Resilient',meaning:'Able to recover quickly from difficulties',example:'Children are often more resilient than adults think.'},
{word:'Ambiguous',meaning:'Open to more than one interpretation',example:'The instructions were ambiguous and confusing.'},
{word:'Paradigm',meaning:'A typical example or pattern of something',example:'This discovery represents a paradigm shift in physics.'},
{word:'Mitigate',meaning:'Make less severe, serious, or painful',example:'Planting trees can help mitigate climate change.'},
{word:'Eloquent',meaning:'Fluent or persuasive in speaking or writing',example:'She gave an eloquent speech about education.'},
{word:'Innovative',meaning:'Featuring new methods; advanced and original',example:'The company is known for its innovative products.'},
{word:'Persevere',meaning:'Continue in a course of action despite difficulty',example:'Students must persevere through challenging exams.'},
{word:'Comprehensive',meaning:'Complete; including all or nearly all elements',example:'The textbook provides a comprehensive overview.'},
{word:'Analyze',meaning:'Examine methodically and in detail',example:'Scientists analyze data to draw conclusions.'},
{word:'Hypothesis',meaning:'A proposed explanation made on limited evidence',example:'The hypothesis was tested through experiments.'},
{word:'Empirical',meaning:'Based on observation or experience rather than theory',example:'Empirical evidence supports the scientific claim.'},
{word:'Synthesize',meaning:'Combine components to form a connected whole',example:'Researchers synthesize information from multiple sources.'},
{word:'Cognitive',meaning:'Relating to mental processes of perception, memory, judgment',example:'Cognitive development is crucial in early childhood.'},
{word:'Dichotomy',meaning:'A division or contrast between two things',example:'There is a clear dichotomy between theory and practice.'},
{word:'Nuance',meaning:'A subtle difference in meaning or opinion',example:'Understanding the nuances of language is important.'},
{word:'Conundrum',meaning:'A confusing and difficult problem or question',example:'The ethical conundrum puzzled the committee.'},
{word:'Catalyst',meaning:'A substance that increases the rate of a chemical reaction',example:'The enzyme acted as a catalyst in the reaction.'},
];
var word=words[Math.floor(Math.random()*words.length)];
FS.vocab.push({word:word.word,meaning:word.meaning,example:word.example,date:new Date().toISOString()});
sv();
var display=document.getElementById('vocabDisplay');
if(display){
display.innerHTML='
โจ New Word Learned!
'+word.word+'
Meaning: '+word.meaning+'
"'+word.example+'"
Added to your vocabulary!
';
if (typeof confetti === 'function') confetti();
} else {
if (typeof openModal === 'function') {
openModal('New Word','
'+word.word+'
Meaning: '+word.meaning+'
"'+word.example+'"
');
} else {
alert('New Word Learned: ' + word.word + '\nMeaning: ' + word.meaning);
}
}
loadVocabularyList();
if (typeof showToast === 'function') showToast('Learned: '+word.word+'!','success');
}
function exportVocabulary(){
if(!FS.vocab || !FS.vocab.length){
if (typeof showToast === 'function') showToast('No vocabulary to export!','error');
else alert('No vocabulary to export!');
return;
}
var t='FlashSync Vocabulary Builder\n========================\n\nTotal Words: '+FS.vocab.length+'\n\n';
for(var i=0;i=0;i--){
var v=FS.vocab[i];
var div=document.createElement('div');
div.className='stat-card';
div.innerHTML='
'+escapeHtml(v.word)+'
Meaning: '+escapeHtml(v.meaning)+'
'+(v.example?'
"'+escapeHtml(v.example)+'"
':'')+'
Added: '+new Date(v.date).toLocaleDateString()+'
';
list.appendChild(div);
}
}
// Auto-run on start up to display existing words cleanly
document.addEventListener("DOMContentLoaded", function() {
loadVocabularyList();
});
// NOTES
function saveNote(){
var inp=document.getElementById('noteInput')||document.getElementById('quickNote');
if(!inp)return;var text=inp.value.trim();if(!text){showToast('Write something!','error');return;}
var note={id:Date.now()+'',text:text,date:new Date().toISOString()};
FS.notes.unshift(note);sv();inp.value='';confetti();showToast('Note saved!','success');
var saved=document.getElementById('savedNotes');
if(saved){
var div=document.createElement('div');div.className='stat-card';
var preview=text.length>100?text.substring(0,100)+'...':text;
div.innerHTML='
Note #'+FS.notes.length+'
'+escapeHtml(preview)+'
';
saved.insertBefore(div,saved.firstChild);
} else setTimeout(function(){location.reload();},800);
}
function deleteNote(id){FS.notes=FS.notes.filter(function(n){return n.id!==id;});sv();showToast('Deleted','error');location.reload();}
function exportNotes(){
if(!FS.notes.length){showToast('No notes!','error');return;}
var t='FlashSync Notes\n';for(var i=0;i
'+topic+'
'+sets.length+' Questions
');
}
function beginExam(topic){
var sets=examQuestions[topic]||examQuestions.biology;
currentExam.topic=topic;currentExam.questions=sets.slice();currentExam.index=0;currentExam.answers=[];currentExam.score=0;
currentExam.remaining=sets.length*3*60;shuffleArray(currentExam.questions);closeModal();renderExamQuestion();
if(currentExam.timer)clearInterval(currentExam.timer);
currentExam.timer=setInterval(function(){
if(currentExam.remaining>0){
currentExam.remaining--;var te=document.getElementById('examTimer');
if(te){var m=Math.floor(currentExam.remaining/60),s=currentExam.remaining%60;te.textContent=(m<10?'0':'')+m+':'+(s<10?'0':'')+s;te.className='exam-timer'+(currentExam.remaining<120?' critical':currentExam.remaining<300?' warning':'');}
} else finishExam();
},1000);
}
function renderExamQuestion(){
if(currentExam.index>=currentExam.questions.length){finishExam();return;}
var q=currentExam.questions[currentExam.index],main=document.querySelector('main-content');if(!main)return;
var pct=(currentExam.index/currentExam.questions.length*100).toFixed(0);
var m=Math.floor(currentExam.remaining/60),s=currentExam.remaining%60;
var html='
Question '+(currentExam.index+1)+' of '+currentExam.questions.length+'
'+(m<10?'0':'')+m+':'+(s<10?'0':'')+s+'
';
html+='
'+escapeHtml(q.q)+'
';
for(var i=0;i'+letter+'. '+escapeHtml(q.o[i])+'';}
main.innerHTML=html;
}
function selectAnswer(idx){
var q=currentExam.questions[currentExam.index];currentExam.answers.push(idx);
if(idx===q.a)currentExam.score++;
setTimeout(function(){currentExam.index++;renderExamQuestion();},600);
}
function finishExam(){
if(currentExam.timer)clearInterval(currentExam.timer);
var total=currentExam.questions.length,score=currentExam.score,pct=Math.round(score/total*100);
var grade=pct>=90?'A':pct>=80?'B':pct>=70?'C':pct>=60?'D':'F';
var result={topic:currentExam.topic,score:score,total:total,pct:pct,date:new Date().toISOString()};
FS.examResults=FS.examResults||[];FS.examResults.push(result);
if(pct>=60){FS.totalExamsPassed=(FS.totalExamsPassed||0)+1;trackAction('exam_passed');checkAndUpdateAchievements('exam',FS.totalExamsPassed);}
sv();var main=document.querySelector('main-content');if(!main)return;
main.innerHTML='
Results
'+currentExam.topic+'
=70?'var(--success)':'var(--accent)')+'>'+pct+'%
Grade: '+grade+'
'+score+'/'+total+' correct
';
confetti();currentExam={topic:null,questions:[],index:0,answers:[],score:0,timer:null,remaining:0};
}
function launchExamSession(topic){startExam(topic);}
function shuffleArray(arr){for(var i=arr.length-1;i>0;i--){var j=Math.floor(Math.random()*(i+1));var t=arr[i];arr[i]=arr[j];arr[j]=t;}return arr;}
// ========== ENHANCED FOCUS TRACKING WITH VISION ENGINEERING ==========
var videoStream=null,focusIntervalId=null,focusCanvas=null,focusCtx=null;
var faceTrackingData={eyesOpen:true,headPosition:'center',blinkCount:0,lastBlinkTime:0,movementScore:0,sessionFrames:0};
function startFocusTracking(){
if(FS.focusTracking&&FS.focusTracking.running){showToast('Already tracking!','error');return;}
FS.focusTracking={running:true,startTime:Date.now(),focusHistory:[],realTimeData:[]};sv();
var status=document.getElementById('focusStatus');if(status)status.textContent='๐ข LIVE - Active';
showToast('๐ง Vision-based focus tracking starting...','success');
// Create hidden canvas for frame analysis
focusCanvas=document.createElement('canvas');
focusCtx=focusCanvas.getContext('2d');
if(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia){
navigator.mediaDevices.getUserMedia({video:{width:320,height:240,framerate:15}}).then(function(stream){
videoStream=stream;
var v=document.getElementById('cameraFeed');
if(v){
v.srcObject=stream;
v.style.display='block';
// Add face overlay canvas
addFaceDetectionOverlay(v);
}
showToast('๐ฅ Camera active - analyzing biometrics!','success');
// Add focus analytics panel
addFocusAnalyticsPanel();
}).catch(function(){
showToast('๐ Camera unavailable - using smart simulation','error');
addFocusAnalyticsPanel();
});
} else {
showToast('๐ Camera unavailable - using smart simulation','error');
addFocusAnalyticsPanel();
}
if(focusIntervalId)clearInterval(focusIntervalId);
focusIntervalId=setInterval(function(){
if(!FS.focusTracking||!FS.focusTracking.running){clearInterval(focusIntervalId);return;}
processVisionFrame();
},2000);
}
function addFaceDetectionOverlay(videoElement){
var container=videoElement.parentElement;
if(!container) return;
var overlay=document.createElement('canvas');
overlay.id='faceOverlay';
overlay.style.position='absolute';
overlay.style.top='0';
overlay.style.left='0';
overlay.style.width='100%';
overlay.style.height='100%';
overlay.style.pointerEvents='none';
if(container.style.position!='relative'&&container.style.position!='absolute'){
container.style.position='relative';
}
container.appendChild(overlay);
// Start real-time face tracking simulation
setInterval(function(){
if(!videoStream||!FS.focusTracking||!FS.focusTracking.running) return;
var v=document.getElementById('cameraFeed');
var o=document.getElementById('faceOverlay');
if(!v||!o) return;
o.width=v.videoWidth||320;
o.height=v.videoHeight||240;
var ctx=o.getContext('2d');
if(!ctx) return;
ctx.clearRect(0,0,o.width,o.height);
// Draw simulated face tracking box
var cx=o.width/2+Math.sin(Date.now()/3000)*20;
var cy=o.height/2+Math.cos(Date.now()/4000)*15;
var faceW=80+Math.sin(Date.now()/5000)*10;
var faceH=100+Math.cos(Date.now()/5000)*8;
// Face boundary box
ctx.strokeStyle='rgba(0,242,255,0.7)';
ctx.lineWidth=2;
ctx.strokeRect(cx-faceW/2,cy-faceH/2,faceW,faceH);
// Eyes detection points
var eyeY=cy-faceH*0.15;
ctx.fillStyle='rgba(0,255,0,0.8)';
ctx.beginPath();ctx.arc(cx-faceW*0.2,eyeY,4,0,Math.PI*2);ctx.fill();
ctx.beginPath();ctx.arc(cx+faceW*0.2,eyeY,4,0,Math.PI*2);ctx.fill();
// Nose
ctx.fillStyle='rgba(0,242,255,0.6)';
ctx.beginPath();ctx.arc(cx,cy+faceH*0.05,3,0,Math.PI*2);ctx.fill();
// Mouth
ctx.strokeStyle='rgba(255,100,200,0.7)';
ctx.lineWidth=2;
ctx.beginPath();
ctx.ellipse(cx,cy+faceH*0.3,faceW*0.2,faceH*0.08,0,0,Math.PI);
ctx.stroke();
// Attention score
var attentionScore=Math.round(75+Math.random()*20);
ctx.fillStyle='rgba(0,255,0,0.5)';
ctx.font='10px monospace';
ctx.fillText('๐ง Focus: '+attentionScore+'%',10,20);
// Tracking quality indicator
ctx.fillStyle='rgba(0,242,255,0.4)';
ctx.fillText('๐ก Face Tracking Active',10,o.height-10);
},200);
}
function addFocusAnalyticsPanel(){
var panel=document.getElementById('focusAnalytics');
if(!panel){
var container=document.querySelector('.feature-box.mt-20');
if(container){
panel=document.createElement('div');
panel.id='focusAnalytics';
panel.innerHTML='
๐ง Live Vision Analytics
Eye State
๐ Open
Head Position
๐ฏ Centered
Movement
๐ Normal
';
container.appendChild(panel);
}
}
}
function processVisionFrame(){
var focus=Math.round(70+Math.random()*25);
var blink=(15+Math.random()*8).toFixed(1);
var tempo=Math.round(120+Math.random()*40);
// Simulate real vision analysis
faceTrackingData.sessionFrames++;
var isBlinking=Math.random()>0.92;
if(isBlinking){
faceTrackingData.blinkCount++;
faceTrackingData.lastBlinkTime=Date.now();
faceTrackingData.eyesOpen=false;
setTimeout(function(){faceTrackingData.eyesOpen=true;},150);
}
// Simulate head position tracking
var headPositions=['Centered','Slightly Left','Slightly Right','Centered','Centered'];
faceTrackingData.headPosition=headPositions[Math.floor(Math.random()*headPositions.length)];
// Simulate movement score
faceTrackingData.movementScore=Math.round(Math.random()*100);
// Update UI
var fl=document.getElementById('focusLevel'),br=document.getElementById('blinkRate');
var mt=document.getElementById('musicTempo'),ps=document.getElementById('postureStatus');
var sd=document.getElementById('sessionDuration');
if(fl)fl.textContent=focus+'%';
if(br)br.textContent=blink;
if(mt)mt.textContent=tempo;
// Enhanced posture detection
if(ps){
var postures=['Upright โ','Good Posture โ','Slightly Slouched','Upright โ','Perfect โ'];
ps.textContent=postures[Math.floor(Math.random()*postures.length)];
}
if(sd)sd.textContent=Math.round((Date.now()-FS.focusTracking.startTime)/60000);
// Update vision analytics
var es=document.getElementById('eyeState');
if(es)es.textContent=faceTrackingData.eyesOpen?'๐ Open':'๐ด Blink Detected';
var hp=document.getElementById('headPosition');
if(hp)hp.textContent='๐ฏ '+faceTrackingData.headPosition;
var ms=document.getElementById('movementScore');
if(ms){
var moveLabel=faceTrackingData.movementScore<30?'๐ Minimal':faceTrackingData.movementScore<70?'๐ Normal':'๐ Active';
ms.textContent=moveLabel;
}
// Get real pixel data from camera feed for analysis
var video=document.getElementById('cameraFeed');
if(video&&video.readyState>=2&&focusCanvas&&focusCtx){
try{
focusCanvas.width=video.videoWidth||320;
focusCanvas.height=video.videoHeight||240;
focusCtx.drawImage(video,0,0,focusCanvas.width,focusCanvas.height);
var imageData=focusCtx.getImageData(0,0,focusCanvas.width,focusCanvas.height);
// Analyze brightness changes for movement detection
var brightness=0;
for(var i=0;i';
summary+='
Average head position: '+faceTrackingData.headPosition+'
';
summary+='
Session quality: Good
';
summary+='
';
openModal('Session Complete',summary);
}
// STUDY PLANS
function createStudyPlan(topic){
var plans={
default:{title:'Custom Plan',duration:'7 days',sessions:['Day 1-2: Fundamentals','Day 3-4: Deep Dive','Day 5-6: Practice','Day 7: Review']},
Thermodynamics:{title:'Thermodynamics Mastery',duration:'10 days',sessions:['Day 1: Basic Concepts & Definitions','Day 2: Laws of Thermodynamics (Zeroth, First)','Day 3: Second Law & Entropy','Day 4: Heat Engines & Refrigerators','Day 5: Carnot Cycle & Efficiency','Day 6: Thermodynamic Potentials','Day 7: Phase Transitions','Day 8: Practice Problems Set 1','Day 9: Practice Problems Set 2','Day 10: Full Review & Self-Assessment']}
};
var plan=plans[topic]||plans.default;plan.topic=topic;plan.created=new Date().toISOString();
FS.studyPlans=FS.studyPlans||[];FS.studyPlans.push(plan);sv();
var html='
๐ Study Plan Created!
'+plan.title+'
๐ Duration: '+plan.duration+'
๐ฏ Mastery Goal: 85%+ by completion
';
for(var i=0;i
';
html+='
';
html+='๐ก Pro Tip: Use the Pomodoro timer for each session. 25min focus + 5min break. Review flashcards after each session.';
html+='
๐ "Success is the sum of small efforts, repeated day in and day out."
';
openModal('Study Plan',html);confetti();showToast('Plan created!','success');
}
// ========== ENHANCED REVIEW SOON SECTION ==========
function startReview(topic){
var cards=FS.cards.filter(function(c){
return c.question.toLowerCase().includes(topic.toLowerCase())||c.answer.toLowerCase().includes(topic.toLowerCase());
});
if(!cards.length){
// Generate intelligent review cards based on topic
var reviewTopics={
'Thermodynamics':[
'What is the First Law of Thermodynamics?',
'Define entropy and its significance.',
'What is a Carnot engine?',
'Explain the Second Law of Thermodynamics.',
'What is enthalpy?',
'How do heat engines work?',
'What is the difference between isothermal and adiabatic processes?',
'Define thermodynamic equilibrium.'
],
'Physics':[
'What is Newton\'s Second Law?',
'Define kinetic energy and potential energy.',
'What is conservation of momentum?',
'Explain electromagnetic induction.',
'What is wave-particle duality?'
],
'Biology':[
'What is the cell theory?',
'Explain the process of mitosis.',
'What is DNA replication?',
'Define natural selection.',
'How does photosynthesis work?'
],
'Chemistry':[
'What is the periodic law?',
'Define chemical bonding.',
'Explain the ideal gas law.',
'What is stoichiometry?',
'Define acid-base reactions.'
]
};
var defaultTopics=['Core concepts','Key definitions','Important principles','Practical applications','Common questions'];
var topicCards=reviewTopics[topic]||defaultTopics.map(function(t){return 'Review: '+t+' of '+topic;});
for(var i=0;i๐ Review: '+topic+'';
html+='
';
['Sun','Mon','Tue','Wed','Thu','Fri','Sat'].forEach(function(d){
html += '
'+d+'
';
});
html += '
';
html += '
';
for(var i=0; i
'; }
for(var day=1; day<=daysInMonth; day++){
// Generate standard reference string for this specific cell loop
var ds = FS.currentYear + '-' + String(FS.currentMonth + 1).padStart(2, '0') + '-' + String(day).padStart(2, '0');
var targetKey = normalizeDateString(ds);
// ๐ CRITICAL CHANGE: Both elements pass through the custom normalizer to force a perfect string match match!
var evts = FS.calendarEvents.filter(function(e){
return normalizeDateString(e.date) === targetKey;
});
var today = new Date();
var isToday = (today.getFullYear() == FS.currentYear && today.getMonth() == FS.currentMonth && today.getDate() == day);
var dayStyle = "background:rgba(255,255,255,0.02); border:1px solid rgba(255,255,255,0.05); border-radius:8px; padding:6px; min-height:95px; cursor:pointer; display:flex; flex-direction:column; gap:4px; overflow:hidden; transition:all 0.15s ease;";
if (isToday) {
dayStyle += "border:2px solid var(--primary); background:rgba(0,242,255,0.08); box-shadow:0 0 10px rgba(0,242,255,0.2);";
}
html += '
' +
''+day+'';
if(evts.length > 0) {
html += '
';
evts.forEach(function(ev) {
var color = "#00f2ff";
var bg = "rgba(0,242,255,0.15)";
if(ev.cat === 'exam') { bg = "rgba(255,74,74,0.15)"; color = "#ff7373"; }
if(ev.cat === 'assign') { bg = "rgba(255,183,0,0.15)"; color = "#ffd066"; }
if(ev.cat === 'study') { bg = "rgba(16,227,83,0.15)"; color = "#66ff99"; }
var strike = ev.completed ? 'text-decoration:line-through; opacity:0.4;' : '';
html += '
' +
escapeHtml(ev.title) +
'
';
});
html += '
';
}
html += '
';
}
html += '
';
html += '';
c.innerHTML = html;
}
function showDayEvents(ds){
var targetKey = normalizeDateString(ds);
var evts = FS.calendarEvents.filter(function(e){ return normalizeDateString(e.date) === targetKey; });
var h = '