-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
831 lines (737 loc) · 33.8 KB
/
Copy pathscript.js
File metadata and controls
831 lines (737 loc) · 33.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
/**
* SkillForge AI
* ============================================================================
* 1. STATE & CONSTANTS
* ============================================================================
*/
const chatState = {
step: 0,
targetRole: '',
experienceLevel: '',
currentSkills: [],
gaps: []
};
const roleRequirements = {
'data scientist': ['Python', 'SQL', 'Machine Learning', 'Statistics', 'Data Visualization', 'Pandas', 'Deep Learning'],
'frontend developer': ['HTML', 'CSS', 'JavaScript', 'React', 'TypeScript', 'Web Performance', 'Accessibility'],
'backend developer': ['Node.js', 'Python', 'Databases', 'API Design', 'System Architecture', 'Docker', 'AWS'],
'full stack developer': ['JavaScript', 'React', 'Node.js', 'Databases', 'API Design', 'CSS', 'Docker'],
'ui/ux designer': ['Figma', 'User Research', 'Wireframing', 'Prototyping', 'Color Theory', 'HTML/CSS basics', 'Accessibility'],
'product manager': ['Agile', 'Jira', 'User Research', 'Data Analysis', 'Roadmapping', 'Communication', 'Stakeholder Management'],
'devops engineer': ['Linux', 'Docker', 'Kubernetes', 'CI/CD', 'AWS', 'Terraform', 'Python/Bash'],
'cybersecurity analyst': ['Network Security', 'Linux', 'Cryptography', 'Risk Assessment', 'Ethical Hacking', 'Python', 'SIEM']
};
const resourceLinks = {
'python': 'Python for Everybody (Coursera)',
'sql': 'SQL Tutorial (Mode Analytics)',
'machine learning': 'Machine Learning by Andrew Ng',
'react': 'React Official Docs (react.dev)',
'javascript': 'JavaScript.info',
'node.js': 'Node.js Crash Course (Traversy Media)',
'docker': 'Docker for Beginners (TechWorld with Nana)',
'aws': 'AWS Cloud Practitioner Essentials',
'figma': 'Figma Crash Course 2024',
'typescript': 'TypeScript Handbook',
'kubernetes': 'Kubernetes Tutorial for Beginners',
'linux': 'Linux Command Line Basics',
'css': 'CSS Tricks / MDN Web Docs'
};
/**
* ============================================================================
* 2. DOM ELEMENTS
* ============================================================================
*/
// Chat Elements
const chatContainer = document.getElementById('chatContainer');
const chatForm = document.getElementById('chatForm');
const userInput = document.getElementById('userInput');
const fileUpload = document.getElementById('fileUpload');
// Sidebar Elements
const sidebar = document.getElementById('sidebar');
const toggleSidebarBtn = document.getElementById('toggleSidebarBtn');
const newChatBtn = document.getElementById('newChatBtn');
const profileSummary = document.getElementById('profileSummary');
const historyList = document.getElementById('historyList');
// New Feature Elements
const exportBtn = document.getElementById('exportBtn');
const clearChatBtn = document.getElementById('clearChatBtn');
const settingsBtn = document.getElementById('settingsBtn');
const micBtn = document.getElementById('micBtn');
const settingsModal = document.getElementById('settingsModal');
const closeSettingsBtn = document.getElementById('closeSettingsBtn');
const themeToggle = document.getElementById('themeToggle');
const animToggle = document.getElementById('animToggle');
let currentRadarChart = null;
/**
* ============================================================================
* 3. UTILITY FUNCTIONS
* ============================================================================
*/
function getResourceForSkill(skill) {
const key = skill.toLowerCase();
for (let r in resourceLinks) {
if (key.includes(r)) return resourceLinks[r];
}
return `Search for "${skill} course" on Udemy or Coursera`;
}
function scrollToBottom() {
chatContainer.scrollTop = chatContainer.scrollHeight;
}
/**
* ============================================================================
* 4. UI COMPONENTS (CHAT INTERFACE)
* ============================================================================
*/
function addMessage(text, sender, isHtml = false) {
const messageDiv = document.createElement('div');
messageDiv.classList.add('message', sender);
const contentDiv = document.createElement('div');
contentDiv.classList.add('message-content');
let formattedText = text;
if (!isHtml) {
formattedText = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
}
messageDiv.appendChild(contentDiv);
chatContainer.appendChild(messageDiv);
if (sender === 'bot' && !document.body.classList.contains('no-animations') && !isHtml) {
let i = 0;
let isTag = false;
let currentHTML = '';
function type() {
if (i < formattedText.length) {
if (formattedText.charAt(i) === '<') isTag = true;
currentHTML += formattedText.charAt(i);
if (formattedText.charAt(i) === '>') isTag = false;
if (isTag) {
i++;
type();
} else {
contentDiv.innerHTML = currentHTML;
i++;
scrollToBottom();
setTimeout(type, 15);
}
} else {
contentDiv.innerHTML = formattedText;
scrollToBottom();
}
}
type();
} else {
contentDiv.innerHTML = formattedText;
scrollToBottom();
}
}
function addQuickReplies(replies) {
const repliesDiv = document.createElement('div');
repliesDiv.classList.add('quick-replies');
replies.forEach(reply => {
const btn = document.createElement('button');
btn.classList.add('quick-reply-btn');
btn.textContent = reply;
btn.type = 'button';
btn.onclick = () => {
userInput.value = reply;
chatForm.dispatchEvent(new Event('submit', { cancelable: true }));
};
repliesDiv.appendChild(btn);
});
chatContainer.appendChild(repliesDiv);
scrollToBottom();
}
function removeQuickReplies() {
const existingReplies = document.querySelectorAll('.quick-replies');
existingReplies.forEach(r => r.remove());
}
function showTypingIndicator() {
const indicatorDiv = document.createElement('div');
indicatorDiv.classList.add('typing-indicator');
indicatorDiv.id = 'typingIndicator';
for (let i = 0; i < 3; i++) {
const dot = document.createElement('div');
dot.classList.add('typing-dot');
indicatorDiv.appendChild(dot);
}
chatContainer.appendChild(indicatorDiv);
scrollToBottom();
}
function removeTypingIndicator() {
const indicator = document.getElementById('typingIndicator');
if (indicator) indicator.remove();
}
function simulateBotResponse(callback, delay = 1500) {
showTypingIndicator();
setTimeout(() => {
removeTypingIndicator();
callback();
}, delay);
}
/**
* ============================================================================
* 5. CORE LOGIC (ANALYZER & STATE MACHINE)
* ============================================================================
*/
function generateSkillGapAnalysis() {
// Determine Requirements
const roleKey = chatState.targetRole.toLowerCase();
let matchedKey = Object.keys(roleRequirements).find(k => roleKey.includes(k));
let requiredSkills = roleRequirements[matchedKey] ? [...roleRequirements[matchedKey]] : ['Communication', 'Problem Solving', 'Domain Knowledge', 'Project Management', 'Technical Skills'];
if (chatState.experienceLevel.toLowerCase().includes('senior')) {
requiredSkills.push('System Design', 'Mentoring', 'Leadership');
} else if (chatState.experienceLevel.toLowerCase().includes('mid')) {
requiredSkills.push('Code Review', 'Best Practices');
}
// Calculate Matches
const userSkillsLower = chatState.currentSkills.map(s => s.toLowerCase());
let gaps = [];
let strengths = [];
let totalScore = 0;
const skillResults = requiredSkills.map(req => {
const reqLower = req.toLowerCase();
let matchScore = 0;
if (userSkillsLower.some(us => us.includes(reqLower) || reqLower.includes(us))) {
matchScore = Math.floor(Math.random() * 20) + 80; // 80-100%
strengths.push(req);
} else {
matchScore = 0; // 0% for missing skills
gaps.push(req);
}
totalScore += matchScore;
return { req, matchScore, isGap: matchScore < 50 };
});
// Finalize State
const overallMatch = Math.round(totalScore / requiredSkills.length);
chatState.gaps = gaps;
saveToProfileAndHistory(chatState.targetRole, chatState.experienceLevel, overallMatch, chatState.currentSkills);
window.lastChartData = {
labels: skillResults.map(s => s.req),
data: skillResults.map(s => s.matchScore)
};
window.lastMatchScore = overallMatch;
// Generate HTML Output
let matchColor = overallMatch >= 80 ? 'var(--success-color)' : (overallMatch >= 50 ? '#fb923c' : 'var(--error-color)');
let analysisHtml = `<h3>Analysis Complete</h3>
<div class="analysis-container">
<span class="analysis-label">Overall Match for ${chatState.experienceLevel} ${chatState.targetRole}</span>
<div class="analysis-score" style="color: ${matchColor}; text-shadow: 0 0 20px ${matchColor}40;">${overallMatch}%</div>
</div>`;
if (strengths.length > 0) {
analysisHtml += `<h3 style="margin-bottom: 8px; font-size: 1.1rem; color: var(--success-color);">✓ Your Strengths</h3>
<p class="strengths-container">
You have a solid foundation in: <strong>${strengths.join(', ')}</strong>.
</p>`;
}
analysisHtml += `<h3 style="margin-bottom: 12px; font-size: 1.1rem;">Detailed Breakdown</h3><div class="skill-bar-container">`;
skillResults.forEach(skill => {
const fillClass = skill.isGap ? 'progress-fill gap-fill' : 'progress-fill';
analysisHtml += `
<div class="skill-row">
<div class="skill-info">
<span class="skill-name">${skill.req}</span>
<span class="skill-percentage">${skill.matchScore}%</span>
</div>
<div class="progress-track">
<div class="${fillClass}" style="width: 0%" data-target="${skill.matchScore}%"></div>
</div>
</div>
`;
});
analysisHtml += `</div>
<div class="radar-chart-container">
<canvas id="skillsRadarChart"></canvas>
</div>`;
if (gaps.length > 0) {
let estimatedMonths = Math.max(1, Math.round(gaps.length * 0.75));
analysisHtml += `<div class="timeline-container">
<div class="timeline-header">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#06b6d4" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>
<span>Estimated Learning Timeline (~${estimatedMonths} months)</span>
</div>
<div class="visual-timeline">`;
let steps = Math.min(4, gaps.length);
for(let i=0; i<steps; i++) {
analysisHtml += `
<div class="timeline-step">
<div class="timeline-dot">${i+1}</div>
<div class="timeline-step-label">${gaps[i]}</div>
</div>`;
}
analysisHtml += `</div></div>`;
let baseSalary = chatState.experienceLevel === 'Senior' ? '$130k' : (chatState.experienceLevel === 'Mid-Level' ? '$95k' : '$65k');
let topSalary = chatState.experienceLevel === 'Senior' ? '$180k+' : (chatState.experienceLevel === 'Mid-Level' ? '$130k' : '$90k');
analysisHtml += `<div style="background: rgba(16, 185, 129, 0.1); border-left: 3px solid var(--success-color); padding: 12px; margin-bottom: 20px; border-radius: 4px;">
<strong style="color: var(--success-color);">Estimated ${chatState.experienceLevel} Salary:</strong> ${baseSalary} - ${topSalary}
</div>`;
analysisHtml += `<h3 style="margin-top: 20px; font-size: 1.1rem;">Recommended Action Plan</h3><ul class="learning-path-list">`;
gaps.forEach(gap => {
const resource = getResourceForSkill(gap);
analysisHtml += `<li><strong>${gap}</strong>: ${resource}</li>`;
});
analysisHtml += `</ul>`;
} else {
analysisHtml += `<p class="highly-qualified-msg">You are highly qualified for this role! Your skill profile is excellent. Consider applying for senior positions or expanding into niche specializations.</p>`;
}
return analysisHtml;
}
function handleBotLogic(userText) {
const lowerText = userText.toLowerCase();
// Global restart command
if (lowerText === 'restart') {
chatState.step = 0;
chatState.targetRole = '';
chatState.experienceLevel = '';
chatState.currentSkills = [];
chatState.gaps = [];
simulateBotResponse(() => {
addMessage("Let's start over! What specific role or career are you aiming for?", 'bot');
addQuickReplies(['Data Scientist', 'Frontend Developer', 'Product Manager']);
}, 500);
return;
}
// Step 0: Identify Role
if (chatState.step === 0) {
const matchedRole = Object.keys(roleRequirements).find(k => lowerText.includes(k));
if (!matchedRole) {
simulateBotResponse(() => {
addMessage(`I don't have enough data to analyze the role "**${userText}**" right now. Please choose one from the list below:`, 'bot');
addQuickReplies(['Data Scientist', 'Frontend Developer', 'Backend Developer', 'Full Stack Developer', 'UI/UX Designer', 'Product Manager', 'DevOps Engineer', 'Cybersecurity Analyst']);
});
return;
}
chatState.targetRole = matchedRole;
chatState.step = 1;
simulateBotResponse(() => {
let displayRole = matchedRole.replace(/\b\w/g, l => l.toUpperCase());
addMessage(`Great! A **${displayRole}**. What is your target experience level?`, 'bot');
addQuickReplies(['Junior', 'Mid-Level', 'Senior']);
});
// Step 1: Identify Experience Level
} else if (chatState.step === 1) {
if (!['junior', 'mid', 'senior'].some(l => lowerText.includes(l))) {
simulateBotResponse(() => {
addMessage("Please select a valid experience level (Junior, Mid-Level, or Senior).", 'bot');
addQuickReplies(['Junior', 'Mid-Level', 'Senior']);
});
return;
}
chatState.experienceLevel = lowerText.includes('senior') ? 'Senior' : (lowerText.includes('mid') ? 'Mid-Level' : 'Junior');
chatState.step = 2;
simulateBotResponse(() => {
addMessage(`Got it, aiming for a **${chatState.experienceLevel}** role. Now, please list your current skills separated by commas, **or upload your Resume/CV** using the paperclip icon!`, 'bot', true);
});
// Step 2: Accept Skills and Analyze
} else if (chatState.step === 2) {
chatState.currentSkills = userText.split(',').map(s => s.trim()).filter(s => s.length > 0);
chatState.step = 3;
simulateBotResponse(() => {
addMessage("Analyzing your profile against industry standards...", 'bot');
simulateBotResponse(() => {
const analysisHtml = generateSkillGapAnalysis();
addMessage(analysisHtml, 'bot', true);
setTimeout(() => {
document.querySelectorAll('.progress-fill').forEach(bar => bar.style.width = bar.getAttribute('data-target'));
renderRadarChart();
if(exportBtn) exportBtn.style.display = 'flex';
if (window.lastMatchScore >= 80 && window.confetti) {
confetti({ particleCount: 150, spread: 70, origin: { y: 0.6 } });
}
}, 100);
setTimeout(() => {
simulateBotResponse(() => {
addMessage("You can ask me for a **project idea** to practice a missing skill, ask how to **improve**, or type **restart** to begin again.", 'bot');
if (chatState.gaps.length > 0) {
addQuickReplies([`Project idea for ${chatState.gaps[0]}`, 'Restart']);
} else {
addQuickReplies(['Restart']);
}
}, 1000);
}, 2000);
}, 2000);
});
// Step 3: Open-Ended Follow-up
} else if (chatState.step === 3) {
simulateBotResponse(() => {
if (lowerText.includes('project') || lowerText.includes('idea')) {
let skill = chatState.gaps.find(g => lowerText.includes(g.toLowerCase())) || chatState.gaps[0] || 'your skills';
addMessage(`**Project Idea for ${skill}:**<br/>Build a real-world application that incorporates ${skill}. For example, if it's a backend skill, create a RESTful API with authentication. Document your process on GitHub!`, 'bot', true);
addQuickReplies(['Another idea', 'How to improve?', 'Restart']);
} else if (lowerText.includes('improve') || lowerText.includes('learn')) {
let skill = chatState.gaps.find(g => lowerText.includes(g.toLowerCase())) || 'new skills';
addMessage(`To improve at **${skill}**, I highly recommend setting aside 30 minutes a day for focused learning. Hands-on practice and teaching the concept to others are proven ways to master it!`, 'bot');
addQuickReplies([`Project idea for ${skill}`, 'Restart']);
} else {
addMessage(`I see you're interested in discussing "${userText}". To truly master your gaps, hands-on practice is key! You can ask for specific project ideas, or type **restart**.`, 'bot');
}
});
}
}
/**
* ============================================================================
* 6. PROFILE & HISTORY STORAGE
* ============================================================================
*/
function saveToProfileAndHistory(role, experience, matchScore, skills) {
const profile = { skills: skills, lastRole: `${experience} ${role}` };
localStorage.setItem('skillGapProfile', JSON.stringify(profile));
let history = JSON.parse(localStorage.getItem('skillGapHistory') || '[]');
const newEntry = {
role: role.replace(/\b\w/g, l => l.toUpperCase()),
experience: experience,
score: matchScore,
date: new Date().toLocaleDateString()
};
history.unshift(newEntry);
if (history.length > 10) history = history.slice(0, 10);
localStorage.setItem('skillGapHistory', JSON.stringify(history));
renderProfileAndHistory();
}
function renderProfileAndHistory() {
let profileData = JSON.parse(localStorage.getItem('skillGapProfile'));
if (!profileData || !profileData.skills || profileData.skills.length === 0) {
profileData = {
name: "John Doe",
lastRole: "Senior Backend Developer",
skills: ["Python", "Docker", "AWS", "SQL", "System Design"]
};
}
const userName = profileData.name || "Your Profile";
profileSummary.innerHTML = `
<h4 style="color: var(--text-primary); margin-bottom: 5px; font-size: 1.1rem;">${userName}</h4>
<strong>Last target:</strong> ${profileData.lastRole}<br/>
<strong style="display:inline-block; margin-top:4px;">Skills:</strong> ${profileData.skills.join(', ')}
`;
profileSummary.style.color = 'var(--text-secondary)';
let historyData = JSON.parse(localStorage.getItem('skillGapHistory') || '[]');
historyList.innerHTML = '';
if (historyData.length === 0) {
historyData = [
{ role: "Backend Developer", experience: "Senior", score: 85, date: new Date().toLocaleDateString() },
{ role: "Backend Developer", experience: "Mid-Level", score: 62, date: new Date(Date.now() - 86400000 * 30).toLocaleDateString() }
];
}
historyData.forEach(item => {
const li = document.createElement('li');
li.classList.add('history-item');
let color = item.score >= 80 ? 'var(--success-color)' : (item.score >= 50 ? '#fb923c' : 'var(--error-color)');
li.innerHTML = `
<div>
<div class="role-info">${item.experience} ${item.role}</div>
<div class="date-info">${item.date}</div>
</div>
<div class="score-info" style="color: ${color};">${item.score}%</div>
`;
historyList.appendChild(li);
});
}
/**
* ============================================================================
* 7. EVENT LISTENERS
* ============================================================================
*/
// Handle text submission
chatForm.addEventListener('submit', (e) => {
e.preventDefault();
const text = userInput.value.trim();
if (!text) return;
removeQuickReplies();
addMessage(text, 'user');
userInput.value = '';
handleBotLogic(text);
});
// Handle file upload
if (fileUpload) {
fileUpload.addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
fileUpload.value = '';
removeQuickReplies();
addMessage(`Uploaded: ${file.name}`, 'user');
showToast(`Resume uploaded successfully!`);
if (chatState.step === 2) {
simulateBotResponse(() => {
addMessage(`I am analyzing **${file.name}** and extracting your skills...`, 'bot', true);
setTimeout(() => {
let roleSkills = roleRequirements[chatState.targetRole] || [];
let numSkillsToExtract = Math.floor(Math.random() * 3) + 2;
let shuffledSkills = [...roleSkills].sort(() => 0.5 - Math.random());
let extractedSkills = shuffledSkills.slice(0, numSkillsToExtract);
extractedSkills.push('Communication', 'Teamwork', 'Problem Solving');
chatState.currentSkills = extractedSkills;
chatState.step = 3;
simulateBotResponse(() => {
addMessage(`Extracted skills: **${extractedSkills.join(', ')}**. Analyzing your profile...`, 'bot', true);
simulateBotResponse(() => {
const analysisHtml = generateSkillGapAnalysis();
addMessage(analysisHtml, 'bot', true);
setTimeout(() => {
document.querySelectorAll('.progress-fill').forEach(bar => bar.style.width = bar.getAttribute('data-target'));
renderRadarChart();
if(exportBtn) exportBtn.style.display = 'flex';
if (window.lastMatchScore >= 80 && window.confetti) {
confetti({ particleCount: 150, spread: 70, origin: { y: 0.6 } });
}
}, 100);
setTimeout(() => {
simulateBotResponse(() => {
addMessage("You can ask me for a **project idea** to practice a missing skill, ask how to **improve**, or type **restart** to begin again.", 'bot', true);
if (chatState.gaps.length > 0) {
addQuickReplies([`Project idea for ${chatState.gaps[0]}`, 'Restart']);
} else {
addQuickReplies(['Restart']);
}
}, 1000);
}, 2000);
}, 2000);
});
}, 2500);
});
} else {
simulateBotResponse(() => {
addMessage(`Thanks for uploading **${file.name}**. I'll keep this on file, but please answer my previous question first!`, 'bot', true);
});
}
});
}
// Sidebar handling
if (toggleSidebarBtn) {
toggleSidebarBtn.addEventListener('click', () => {
sidebar.classList.toggle('hidden');
// Handle mobile visibility class if needed
sidebar.classList.toggle('visible');
});
}
// New Chat button
if (newChatBtn) {
newChatBtn.addEventListener('click', () => {
// Same logic as typing 'restart'
chatState.step = 0;
chatState.targetRole = '';
chatState.experienceLevel = '';
chatState.currentSkills = [];
chatState.gaps = [];
removeQuickReplies();
simulateBotResponse(() => {
addMessage("Let's start over! What specific role or career are you aiming for?", 'bot');
addQuickReplies(['Data Scientist', 'Frontend Developer', 'Product Manager']);
}, 500);
// On mobile, automatically hide the sidebar when starting a new chat
if (window.innerWidth <= 768) {
sidebar.classList.remove('visible');
sidebar.classList.add('hidden');
}
});
}
// Initialization
window.addEventListener('load', () => {
renderProfileAndHistory();
simulateBotResponse(() => {
addMessage("Hello! I am SkillForge AI. To get started, what specific role or career are you aiming for?", 'bot');
addQuickReplies(['Data Scientist', 'Frontend Developer', 'Product Manager']);
}, 1000);
});
/**
* ============================================================================
* 8. NEW FEATURES (TOAST, SETTINGS, EXPORT, VOICE, CHART)
* ============================================================================
*/
// Toast Notifications
function showToast(message) {
const toastContainer = document.getElementById('toastContainer');
if (!toastContainer) return;
const toast = document.createElement('div');
toast.className = 'toast';
toast.innerHTML = `<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="var(--success-color)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg> ${message}`;
toastContainer.appendChild(toast);
setTimeout(() => toast.classList.add('show'), 10);
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => toast.remove(), 300);
}, 3000);
}
// Clear Chat
if (clearChatBtn) {
clearChatBtn.addEventListener('click', () => {
chatContainer.innerHTML = '';
chatState.step = 0;
chatState.targetRole = '';
chatState.experienceLevel = '';
chatState.currentSkills = [];
chatState.gaps = [];
if(exportBtn) exportBtn.style.display = 'none';
showToast("Chat history cleared.");
simulateBotResponse(() => {
addMessage("Let's start over! What specific role or career are you aiming for?", 'bot');
addQuickReplies(['Data Scientist', 'Frontend Developer', 'Product Manager']);
}, 500);
});
}
// Export Report
if (exportBtn) {
exportBtn.addEventListener('click', () => {
let content = `SkillForge AI Report\n`;
content += `=============================\n`;
content += `Target Role: ${chatState.experienceLevel} ${chatState.targetRole.toUpperCase()}\n`;
content += `\nCurrent Skills: ${chatState.currentSkills.join(', ')}\n`;
content += `Identified Gaps: ${chatState.gaps.join(', ')}\n\n`;
content += `Recommended Action Plan:\n`;
chatState.gaps.forEach(gap => {
content += `- ${gap}: ${getResourceForSkill(gap)}\n`;
});
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `Skill_Gap_Report_${chatState.targetRole.replace(/\s+/g, '_')}.txt`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showToast("Report exported successfully!");
});
}
// Settings Modal
if (settingsBtn && settingsModal && closeSettingsBtn) {
settingsBtn.addEventListener('click', () => settingsModal.classList.remove('hidden'));
closeSettingsBtn.addEventListener('click', () => settingsModal.classList.add('hidden'));
settingsModal.addEventListener('click', (e) => {
if(e.target === settingsModal) settingsModal.classList.add('hidden');
});
}
if (themeToggle) {
themeToggle.addEventListener('change', (e) => {
if(e.target.checked) {
document.documentElement.setAttribute('data-theme', 'light');
showToast("Light theme enabled");
} else {
document.documentElement.removeAttribute('data-theme');
showToast("Dark theme enabled");
}
if(window.lastChartData && currentRadarChart) renderRadarChart(); // re-render chart for colors
});
}
if (animToggle) {
animToggle.addEventListener('change', (e) => {
if(!e.target.checked) {
document.body.classList.add('no-animations');
showToast("Animations disabled");
} else {
document.body.classList.remove('no-animations');
showToast("Animations enabled");
}
});
}
// Voice Input (Web Speech API)
if (micBtn) {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
if (SpeechRecognition) {
const recognition = new SpeechRecognition();
recognition.continuous = false;
recognition.interimResults = false;
recognition.onstart = () => {
micBtn.classList.add('recording');
};
recognition.onresult = (event) => {
const transcript = event.results[0][0].transcript;
userInput.value = transcript;
showToast("Voice recognized!");
};
recognition.onerror = (event) => {
console.error('Speech recognition error', event.error);
if (event.error === 'not-allowed') {
showToast("Microphone access denied or requires a local server.");
} else {
showToast(`Voice error: ${event.error}`);
}
micBtn.classList.remove('recording');
};
recognition.onend = () => {
micBtn.classList.remove('recording');
};
micBtn.addEventListener('click', () => {
if (micBtn.classList.contains('recording')) {
recognition.stop();
} else {
recognition.start();
}
});
} else {
micBtn.addEventListener('click', () => {
showToast("Voice input is not supported in this browser.");
});
}
}
// Radar Chart Rendering
function renderRadarChart() {
const canvas = document.getElementById('skillsRadarChart');
if (!canvas || !window.lastChartData || !window.Chart) return;
if (currentRadarChart) {
currentRadarChart.destroy();
}
const ctx = canvas.getContext('2d');
const isLightMode = document.documentElement.getAttribute('data-theme') === 'light';
const textColor = isLightMode ? '#1e293b' : '#e2e8f0';
const gridColor = isLightMode ? 'rgba(0,0,0,0.1)' : 'rgba(255,255,255,0.1)';
currentRadarChart = new Chart(ctx, {
type: 'radar',
data: {
labels: window.lastChartData.labels,
datasets: [{
label: 'Skill Proficiency Match',
data: window.lastChartData.data,
backgroundColor: 'rgba(16, 185, 129, 0.2)',
borderColor: '#10b981',
pointBackgroundColor: '#06b6d4',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: '#06b6d4',
borderWidth: 2
}]
},
options: {
scales: {
r: {
angleLines: { color: gridColor },
grid: { color: gridColor },
pointLabels: {
color: textColor,
font: { family: "'Outfit', sans-serif", size: 12 }
},
ticks: { display: false, min: 0, max: 100 }
}
},
plugins: {
legend: { display: false }
},
maintainAspectRatio: false
}
});
}
// Skill Picker Modal
const pickSkillsBtn = document.getElementById('pickSkillsBtn');
const skillPickerModal = document.getElementById('skillPickerModal');
const closeSkillPickerBtn = document.getElementById('closeSkillPickerBtn');
const applySkillsBtn = document.getElementById('applySkillsBtn');
if (pickSkillsBtn) {
pickSkillsBtn.addEventListener('click', () => {
skillPickerModal.classList.remove('hidden');
});
}
if (closeSkillPickerBtn) {
closeSkillPickerBtn.addEventListener('click', () => {
skillPickerModal.classList.add('hidden');
});
}
if (applySkillsBtn) {
applySkillsBtn.addEventListener('click', () => {
const checkedBoxes = document.querySelectorAll('.skill-chip input:checked');
const selectedSkills = Array.from(checkedBoxes).map(box => box.value);
if (selectedSkills.length > 0) {
userInput.value = selectedSkills.join(', ');
skillPickerModal.classList.add('hidden');
checkedBoxes.forEach(box => box.checked = false);
showToast("Skills applied!");
} else {
showToast("Please select at least one skill.");
}
});
}