-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
910 lines (809 loc) · 39.6 KB
/
Copy pathindex.html
File metadata and controls
910 lines (809 loc) · 39.6 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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
<!DOCTYPE html>
<html lang="en">
<head>
<base target="_self">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>StudyBuddy Enhanced - AI-Powered Academic Assistant</title>
<meta name="description" content="AI-powered goal planning and task management for students">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script src="https://cdn.tailwindcss.com"></script>
<!-- Clerk Authentication -->
<script src="https://incredible-wallaby-69.clerk.accounts.dev/npm/@clerk/clerk-js@latest/dist/clerk.browser.js"></script>
<!-- Supabase Client -->
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
<!-- Google APIs -->
<script src="https://apis.google.com/js/api.js"></script>
<script src="https://accounts.google.com/gsi/client"></script>
<!-- Configuration Files -->
<script src="api-keys.js"></script>
<script src="config.js"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
primary: "#4F46E5",
secondary: "#10B981",
accent: "#F59E0B"
},
fontFamily: {
sans: ['Inter', 'sans-serif']
}
}
}
}
</script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
body {
font-family: 'Inter', sans-serif;
}
.task-card:hover {
transform: translateY(-2px);
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
}
.loading {
animation: spin 1s linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.hidden { display: none; }
.notification {
position: fixed;
top: 20px;
right: 20px;
z-index: 1000;
padding: 12px 20px;
border-radius: 8px;
color: white;
font-weight: 500;
transform: translateX(100%);
transition: transform 0.3s ease;
}
.notification.show {
transform: translateX(0);
}
.notification.success { background-color: #10B981; }
.notification.error { background-color: #EF4444; }
.notification.info { background-color: #3B82F6; }
</style>
</head>
<body class="bg-gray-50 min-h-screen">
<!-- Notification Container -->
<div id="notification-container"></div>
<!-- Authentication Loading Screen -->
<div id="auth-loading" class="fixed inset-0 bg-white flex items-center justify-center z-50">
<div class="text-center">
<i class="fas fa-graduation-cap text-primary text-6xl mb-4 loading"></i>
<h2 class="text-2xl font-bold text-gray-800 mb-2">StudyBuddy Enhanced</h2>
<p class="text-gray-600">Initializing your AI study assistant...</p>
</div>
</div>
<!-- Main Application -->
<div id="app" class="hidden">
<header class="bg-white shadow-sm">
<nav class="container mx-auto px-4 py-4 flex justify-between items-center">
<div class="flex items-center space-x-2">
<i class="fas fa-graduation-cap text-primary text-2xl"></i>
<h1 class="text-xl font-bold text-gray-800">StudyBuddy Enhanced</h1>
</div>
<div class="flex items-center space-x-4">
<span id="user-greeting" class="text-gray-600"></span>
<button id="sign-out-btn" class="px-4 py-2 bg-gray-500 text-white rounded-md hover:bg-gray-600 transition">
Sign Out
</button>
</div>
</nav>
</header>
<main class="container mx-auto px-4 py-8">
<!-- Goal Setting Section -->
<section class="bg-white rounded-lg shadow-md p-6 mb-8">
<h2 class="text-2xl font-bold text-gray-900 mb-6">Set Your Academic Goals</h2>
<div class="flex flex-col md:flex-row gap-4">
<div class="flex-1">
<label for="goal-input" class="block text-sm font-medium text-gray-700 mb-1">What's your main goal?</label>
<input type="text" id="goal-input" placeholder="e.g. Pass Calculus with an A"
class="w-full px-4 py-2 border border-gray-300 rounded-md focus:ring-primary focus:border-primary">
</div>
<div class="flex items-end">
<button id="set-goal-btn" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-indigo-700 transition flex items-center space-x-2">
<span>Set Goal</span>
<i id="goal-loading" class="fas fa-spinner loading hidden"></i>
</button>
</div>
</div>
</section>
<!-- AI Task Generation Section -->
<section id="task-section" class="hidden bg-white rounded-lg shadow-md p-6 mb-8">
<div class="flex justify-between items-center mb-6">
<div>
<h2 class="text-2xl font-bold text-gray-900">Your AI-Generated Study Plan</h2>
<p class="text-gray-600 mt-1">Powered by artificial intelligence</p>
</div>
<button id="breakdown-btn" class="px-4 py-2 bg-secondary text-white rounded-md hover:bg-emerald-700 transition flex items-center space-x-2">
<i class="fas fa-magic"></i>
<span>Generate AI Tasks</span>
<i id="ai-loading" class="fas fa-spinner loading hidden"></i>
</button>
</div>
<div id="task-list" class="space-y-3">
<!-- AI-generated tasks will be inserted here -->
</div>
<div id="task-stats" class="hidden mt-6 grid grid-cols-1 md:grid-cols-3 gap-4">
<div class="bg-blue-50 p-4 rounded-lg text-center">
<div class="text-2xl font-bold text-blue-600" id="total-tasks">0</div>
<div class="text-sm text-blue-600">Total Tasks</div>
</div>
<div class="bg-green-50 p-4 rounded-lg text-center">
<div class="text-2xl font-bold text-green-600" id="completed-tasks">0</div>
<div class="text-sm text-green-600">Completed</div>
</div>
<div class="bg-amber-50 p-4 rounded-lg text-center">
<div class="text-2xl font-bold text-amber-600" id="total-time">0</div>
<div class="text-sm text-amber-600">Total Hours</div>
</div>
</div>
</section>
<!-- Calendar Integration Section -->
<section id="calendar-section" class="hidden bg-white rounded-lg shadow-md p-6 mb-8">
<div class="flex justify-between items-center mb-6">
<h2 class="text-2xl font-bold text-gray-900">Schedule Study Sessions</h2>
<div class="flex space-x-2">
<button id="google-auth-btn" class="px-4 py-2 bg-red-500 text-white rounded-md hover:bg-red-600 transition">
<i class="fab fa-google mr-2"></i>Connect Google Calendar
</button>
<button id="schedule-btn" class="px-4 py-2 bg-accent text-white rounded-md hover:bg-amber-600 transition">
Add to Calendar
</button>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-4 gap-4">
<div>
<label for="study-date" class="block text-sm font-medium text-gray-700 mb-1">Date</label>
<input type="date" id="study-date" class="w-full px-4 py-2 border border-gray-300 rounded-md">
</div>
<div>
<label for="start-time" class="block text-sm font-medium text-gray-700 mb-1">Start Time</label>
<input type="time" id="start-time" class="w-full px-4 py-2 border border-gray-300 rounded-md">
</div>
<div>
<label for="duration" class="block text-sm font-medium text-gray-700 mb-1">Duration (minutes)</label>
<select id="duration" class="w-full px-4 py-2 border border-gray-300 rounded-md">
<option value="30">30 minutes</option>
<option value="45">45 minutes</option>
<option value="60" selected>1 hour</option>
<option value="90">1.5 hours</option>
<option value="120">2 hours</option>
</select>
</div>
<div>
<label for="task-select" class="block text-sm font-medium text-gray-700 mb-1">Select Task</label>
<select id="task-select" class="w-full px-4 py-2 border border-gray-300 rounded-md">
<option value="">Choose a task...</option>
</select>
</div>
</div>
</section>
<!-- WhatsApp Integration Section -->
<section id="whatsapp-section" class="hidden bg-white rounded-lg shadow-md p-6 mb-8">
<div class="flex justify-between items-center mb-6">
<div>
<h2 class="text-2xl font-bold text-gray-900">WhatsApp Notifications</h2>
<p class="text-gray-600 mt-1">Get study reminders and motivational messages</p>
</div>
<button id="whatsapp-setup-btn" class="px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600 transition">
<i class="fab fa-whatsapp mr-2"></i>Setup WhatsApp
</button>
</div>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<h3 class="font-semibold text-gray-800 mb-3">Notification Settings</h3>
<div class="space-y-3">
<label class="flex items-center">
<input type="checkbox" id="reminder-30" checked class="mr-2">
<span>30 minutes before session</span>
</label>
<label class="flex items-center">
<input type="checkbox" id="reminder-15" checked class="mr-2">
<span>15 minutes before session</span>
</label>
<label class="flex items-center">
<input type="checkbox" id="reminder-5" checked class="mr-2">
<span>5 minutes before session</span>
</label>
<label class="flex items-center">
<input type="checkbox" id="completion-msg" checked class="mr-2">
<span>Completion congratulations</span>
</label>
</div>
</div>
<div>
<h3 class="font-semibold text-gray-800 mb-3">Test Notifications</h3>
<div class="space-y-2">
<button id="test-reminder" class="w-full px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition">
Send Test Reminder
</button>
<button id="test-motivation" class="w-full px-4 py-2 bg-purple-500 text-white rounded-md hover:bg-purple-600 transition">
Send Motivation Message
</button>
</div>
</div>
</div>
</section>
<!-- Dynamic Replanning Section -->
<section id="replan-section" class="hidden bg-white rounded-lg shadow-md p-6">
<h2 class="text-2xl font-bold text-gray-900 mb-4">Need to Adjust Your Plan?</h2>
<p class="text-gray-600 mb-6">AI can help reorganize your schedule when life gets in the way.</p>
<div class="flex space-x-4">
<button id="replan-btn" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-indigo-700 transition">
<i class="fas fa-magic mr-2"></i>AI Replan Schedule
</button>
<button id="export-data" class="px-4 py-2 bg-gray-500 text-white rounded-md hover:bg-gray-600 transition">
<i class="fas fa-download mr-2"></i>Export Data
</button>
</div>
</section>
</main>
</div>
<footer class="bg-gray-100 mt-12">
<div class="container mx-auto px-4 py-8">
<div class="flex flex-col md:flex-row justify-between items-center">
<div class="flex items-center space-x-2 mb-4 md:mb-0">
<i class="fas fa-graduation-cap text-primary text-xl"></i>
<span class="font-medium text-gray-800">StudyBuddy Enhanced</span>
<span class="text-sm text-gray-500">v2.0.0</span>
</div>
<div class="flex space-x-6">
<a href="#" class="text-gray-600 hover:text-primary transition">
<i class="fab fa-whatsapp text-xl"></i>
</a>
<a href="#" class="text-gray-600 hover:text-primary transition">
<i class="fas fa-envelope text-xl"></i>
</a>
<a href="#" class="text-gray-600 hover:text-primary transition">
<i class="fab fa-github text-xl"></i>
</a>
</div>
</div>
<div class="mt-6 text-center text-sm text-gray-500">
© 2024 StudyBuddy Enhanced. Powered by AI. All rights reserved.
</div>
</div>
</footer>
<script>
// Application State
let currentUser = null;
let supabase = null;
let clerk = null;
let currentGoal = '';
let currentTasks = [];
let isGoogleCalendarConnected = false;
// Initialize Application
document.addEventListener('DOMContentLoaded', async function() {
try {
await initializeApp();
} catch (error) {
console.error('Failed to initialize app:', error);
showNotification('Failed to initialize application', 'error');
hideLoadingScreen();
}
});
// Initialize all services
async function initializeApp() {
showNotification('Initializing StudyBuddy Enhanced...', 'info');
// Initialize Supabase
if (window.API_KEYS && window.API_KEYS.SUPABASE_URL) {
supabase = window.supabase.createClient(
window.API_KEYS.SUPABASE_URL,
window.API_KEYS.SUPABASE_ANON_KEY
);
console.log('Supabase initialized');
}
// Initialize Clerk Authentication
if (window.API_KEYS && window.API_KEYS.CLERK_PUBLISHABLE_KEY) {
clerk = new window.Clerk(window.API_KEYS.CLERK_PUBLISHABLE_KEY);
await clerk.load();
if (clerk.user) {
currentUser = clerk.user;
showUserGreeting();
hideLoadingScreen();
} else {
await showSignIn();
}
} else {
// Demo mode without authentication
currentUser = { firstName: 'Demo', lastName: 'User' };
showUserGreeting();
hideLoadingScreen();
}
// Initialize Google APIs
await initializeGoogleAPIs();
showNotification('StudyBuddy Enhanced ready!', 'success');
}
// Authentication Functions
async function showSignIn() {
if (clerk) {
await clerk.openSignIn();
} else {
// Demo mode
hideLoadingScreen();
}
}
function showUserGreeting() {
const greeting = document.getElementById('user-greeting');
if (currentUser) {
greeting.textContent = `Welcome, ${currentUser.firstName || 'Student'}!`;
}
}
function hideLoadingScreen() {
document.getElementById('auth-loading').classList.add('hidden');
document.getElementById('app').classList.remove('hidden');
}
// Google APIs Initialization
async function initializeGoogleAPIs() {
if (window.API_KEYS && window.API_KEYS.GOOGLE_API_KEY) {
try {
await new Promise((resolve) => {
window.gapi.load('client:auth2', resolve);
});
await window.gapi.client.init({
apiKey: window.API_KEYS.GOOGLE_API_KEY,
clientId: window.API_KEYS.GOOGLE_CLIENT_ID,
discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest'],
scope: 'https://www.googleapis.com/auth/calendar.events'
});
console.log('Google APIs initialized');
} catch (error) {
console.error('Failed to initialize Google APIs:', error);
}
}
}
// AI Task Generation
async function generateAITasks(goal) {
showLoading('ai-loading');
try {
const prompt = window.CONFIG.ai.taskGenerationPrompt.replace('{goal}', goal);
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${window.API_KEYS.OPENAI_API_KEY}`
},
body: JSON.stringify({
model: window.CONFIG.ai.model,
messages: [{
role: 'user',
content: prompt
}],
max_tokens: window.CONFIG.ai.maxTokens,
temperature: window.CONFIG.ai.temperature
})
});
if (!response.ok) {
throw new Error(`AI API Error: ${response.status}`);
}
const data = await response.json();
const tasksText = data.choices[0].message.content;
// Parse JSON response
let tasks;
try {
tasks = JSON.parse(tasksText);
} catch (e) {
// Fallback if AI doesn't return proper JSON
tasks = parseTasksFromText(tasksText);
}
hideLoading('ai-loading');
showNotification('AI tasks generated successfully!', 'success');
return tasks;
} catch (error) {
console.error('Failed to generate AI tasks:', error);
hideLoading('ai-loading');
showNotification('Failed to generate AI tasks. Using fallback.', 'error');
// Fallback to sample tasks
return getFallbackTasks(goal);
}
}
// Fallback task parsing
function parseTasksFromText(text) {
const lines = text.split('\n').filter(line => line.trim());
return lines.slice(0, 5).map((line, index) => ({
id: index + 1,
name: line.replace(/^\d+\.?\s*/, '').trim(),
duration: 60,
description: line.trim(),
priority: 'medium',
completed: false
}));
}
// Fallback tasks for demo
function getFallbackTasks(goal) {
const taskTemplates = {
'calculus': [
{ name: 'Review fundamental concepts and definitions', duration: 45, priority: 'high' },
{ name: 'Practice derivative problems', duration: 60, priority: 'high' },
{ name: 'Study integration techniques', duration: 75, priority: 'medium' },
{ name: 'Work on application problems', duration: 90, priority: 'medium' },
{ name: 'Take practice exam', duration: 120, priority: 'high' }
],
'default': [
{ name: 'Break down the goal into smaller components', duration: 30, priority: 'high' },
{ name: 'Research key concepts and materials', duration: 60, priority: 'medium' },
{ name: 'Create a detailed study schedule', duration: 45, priority: 'high' },
{ name: 'Practice with sample problems/exercises', duration: 90, priority: 'medium' },
{ name: 'Review and test your understanding', duration: 60, priority: 'high' }
]
};
const key = goal.toLowerCase().includes('calculus') ? 'calculus' : 'default';
return taskTemplates[key].map((task, index) => ({
id: index + 1,
...task,
description: `${task.name} - Focus on achieving: ${goal}`,
completed: false
}));
}
// Supabase Data Management
async function saveGoalToDatabase(goal) {
if (!supabase || !currentUser) return;
try {
const { data, error } = await supabase
.from('goals')
.insert([{
user_id: currentUser.id,
title: goal,
created_at: new Date().toISOString(),
status: 'active'
}]);
if (error) throw error;
console.log('Goal saved to database:', data);
} catch (error) {
console.error('Failed to save goal:', error);
}
}
async function saveTasksToDatabase(tasks, goalId) {
if (!supabase || !currentUser) return;
try {
const tasksData = tasks.map(task => ({
user_id: currentUser.id,
goal_id: goalId,
title: task.name,
description: task.description,
estimated_duration: task.duration,
priority: task.priority,
completed: task.completed,
created_at: new Date().toISOString()
}));
const { data, error } = await supabase
.from('tasks')
.insert(tasksData);
if (error) throw error;
console.log('Tasks saved to database:', data);
} catch (error) {
console.error('Failed to save tasks:', error);
}
}
// Google Calendar Integration
async function connectGoogleCalendar() {
try {
const authInstance = window.gapi.auth2.getAuthInstance();
const user = await authInstance.signIn();
if (user.isSignedIn()) {
isGoogleCalendarConnected = true;
document.getElementById('google-auth-btn').innerHTML =
'<i class="fas fa-check mr-2"></i>Connected';
document.getElementById('google-auth-btn').classList.remove('bg-red-500', 'hover:bg-red-600');
document.getElementById('google-auth-btn').classList.add('bg-green-500', 'hover:bg-green-600');
showNotification('Google Calendar connected!', 'success');
}
} catch (error) {
console.error('Failed to connect Google Calendar:', error);
showNotification('Failed to connect Google Calendar', 'error');
}
}
async function addToGoogleCalendar(eventDetails) {
if (!isGoogleCalendarConnected) {
showNotification('Please connect Google Calendar first', 'error');
return;
}
try {
const event = {
summary: `Study Session: ${eventDetails.task}`,
description: `StudyBuddy study session for: ${eventDetails.task}\nGoal: ${currentGoal}`,
start: {
dateTime: eventDetails.startDateTime,
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
},
end: {
dateTime: eventDetails.endDateTime,
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone
},
reminders: {
useDefault: false,
overrides: [
{ method: 'popup', minutes: 30 },
{ method: 'popup', minutes: 15 }
]
}
};
const response = await window.gapi.client.calendar.events.insert({
calendarId: 'primary',
resource: event
});
showNotification('Event added to Google Calendar!', 'success');
return response;
} catch (error) {
console.error('Failed to add event to calendar:', error);
showNotification('Failed to add event to calendar', 'error');
}
}
// WhatsApp Integration
function setupWhatsAppNotifications() {
if (window.CONFIG.features.whatsappNotifications) {
// For demo, we'll show a setup dialog
const phone = prompt('Enter your WhatsApp number (with country code):');
if (phone) {
localStorage.setItem('whatsapp_number', phone);
showNotification('WhatsApp notifications enabled!', 'success');
document.getElementById('whatsapp-setup-btn').innerHTML =
'<i class="fab fa-whatsapp mr-2"></i>Connected';
document.getElementById('whatsapp-setup-btn').classList.remove('bg-green-500', 'hover:bg-green-600');
document.getElementById('whatsapp-setup-btn').classList.add('bg-green-600');
}
}
}
// Simulate WhatsApp message sending
function sendWhatsAppMessage(message, phone) {
// In a real implementation, this would use WhatsApp Business API
console.log(`WhatsApp message to ${phone}: ${message}`);
// For demo, we'll show a notification
showNotification(`WhatsApp sent: ${message.substring(0, 30)}...`, 'info');
}
// DOM Element References
const goalInput = document.getElementById('goal-input');
const setGoalBtn = document.getElementById('set-goal-btn');
const taskSection = document.getElementById('task-section');
const breakdownBtn = document.getElementById('breakdown-btn');
const taskList = document.getElementById('task-list');
const calendarSection = document.getElementById('calendar-section');
const whatsappSection = document.getElementById('whatsapp-section');
const replanSection = document.getElementById('replan-section');
const scheduleBtn = document.getElementById('schedule-btn');
const replanBtn = document.getElementById('replan-btn');
const signOutBtn = document.getElementById('sign-out-btn');
const googleAuthBtn = document.getElementById('google-auth-btn');
const whatsappSetupBtn = document.getElementById('whatsapp-setup-btn');
const testReminderBtn = document.getElementById('test-reminder');
const testMotivationBtn = document.getElementById('test-motivation');
// Event Listeners
setGoalBtn.addEventListener('click', setGoal);
breakdownBtn.addEventListener('click', generateTasks);
scheduleBtn.addEventListener('click', scheduleStudyTime);
replanBtn.addEventListener('click', replanSchedule);
signOutBtn.addEventListener('click', signOut);
googleAuthBtn.addEventListener('click', connectGoogleCalendar);
whatsappSetupBtn.addEventListener('click', setupWhatsAppNotifications);
testReminderBtn.addEventListener('click', () => sendTestNotification('reminder'));
testMotivationBtn.addEventListener('click', () => sendTestNotification('motivation'));
document.getElementById('export-data').addEventListener('click', exportData);
// Main Functions
async function setGoal() {
const goal = goalInput.value.trim();
if (!goal) {
showNotification('Please enter a goal', 'error');
return;
}
showLoading('goal-loading');
currentGoal = goal;
// Save to database
await saveGoalToDatabase(goal);
// Show sections
taskSection.classList.remove('hidden');
calendarSection.classList.remove('hidden');
whatsappSection.classList.remove('hidden');
replanSection.classList.remove('hidden');
hideLoading('goal-loading');
showNotification('Goal set successfully!', 'success');
}
async function generateTasks() {
if (!currentGoal) {
showNotification('Please set a goal first', 'error');
return;
}
// Generate tasks using AI
const tasks = await generateAITasks(currentGoal);
currentTasks = tasks;
// Save tasks to database
await saveTasksToDatabase(tasks, 1); // Assuming goal ID 1 for demo
// Render tasks
renderTasks(tasks);
updateTaskStats();
populateTaskSelect();
showNotification('AI tasks generated!', 'success');
}
function renderTasks(tasks) {
taskList.innerHTML = '';
tasks.forEach(task => {
const taskElement = document.createElement('div');
taskElement.className = 'task-card flex items-center justify-between p-4 border border-gray-200 rounded-md hover:shadow-md transition cursor-pointer';
taskElement.innerHTML = `
<div class="flex items-center space-x-3">
<input type="checkbox" id="task-${task.id}" class="h-5 w-5 text-primary rounded"
${task.completed ? 'checked' : ''} onchange="toggleTask(${task.id})">
<div>
<label for="task-${task.id}" class="text-gray-800 font-medium">${task.name}</label>
<p class="text-sm text-gray-600">${task.description}</p>
</div>
</div>
<div class="text-right">
<span class="text-sm text-gray-500">${task.duration} min</span>
<span class="block text-xs text-${task.priority === 'high' ? 'red' : task.priority === 'medium' ? 'yellow' : 'green'}-600 font-medium">
${task.priority} priority
</span>
</div>
`;
taskList.appendChild(taskElement);
});
document.getElementById('task-stats').classList.remove('hidden');
}
function toggleTask(taskId) {
const task = currentTasks.find(t => t.id === taskId);
if (task) {
task.completed = !task.completed;
updateTaskStats();
if (task.completed) {
showNotification(`Great job completing: ${task.name}`, 'success');
// Send WhatsApp completion message
const phone = localStorage.getItem('whatsapp_number');
if (phone) {
sendWhatsAppMessage(
window.CONFIG.whatsapp.messageTemplates.completion
.replace('{subject}', task.name),
phone
);
}
}
}
}
function updateTaskStats() {
const total = currentTasks.length;
const completed = currentTasks.filter(t => t.completed).length;
const totalTime = Math.round(currentTasks.reduce((sum, t) => sum + t.duration, 0) / 60 * 10) / 10;
document.getElementById('total-tasks').textContent = total;
document.getElementById('completed-tasks').textContent = completed;
document.getElementById('total-time').textContent = totalTime;
}
function populateTaskSelect() {
const taskSelect = document.getElementById('task-select');
taskSelect.innerHTML = '<option value="">Choose a task...</option>';
currentTasks.forEach(task => {
if (!task.completed) {
const option = document.createElement('option');
option.value = task.id;
option.textContent = task.name;
taskSelect.appendChild(option);
}
});
}
async function scheduleStudyTime() {
const date = document.getElementById('study-date').value;
const startTime = document.getElementById('start-time').value;
const duration = parseInt(document.getElementById('duration').value);
const taskId = document.getElementById('task-select').value;
if (!date || !startTime || !taskId) {
showNotification('Please fill in all fields', 'error');
return;
}
const task = currentTasks.find(t => t.id == taskId);
if (!task) {
showNotification('Invalid task selected', 'error');
return;
}
// Create datetime objects
const startDateTime = new Date(`${date}T${startTime}`);
const endDateTime = new Date(startDateTime.getTime() + duration * 60000);
const eventDetails = {
task: task.name,
startDateTime: startDateTime.toISOString(),
endDateTime: endDateTime.toISOString(),
duration: duration
};
// Add to Google Calendar if connected
if (isGoogleCalendarConnected) {
await addToGoogleCalendar(eventDetails);
}
// Schedule WhatsApp reminders
const phone = localStorage.getItem('whatsapp_number');
if (phone) {
scheduleWhatsAppReminders(task, startDateTime, phone);
}
showNotification('Study session scheduled!', 'success');
}
function scheduleWhatsAppReminders(task, startTime, phone) {
const reminderTimes = window.CONFIG.whatsapp.reminderTimes;
reminderTimes.forEach(minutes => {
const reminderTime = new Date(startTime.getTime() - minutes * 60000);
const now = new Date();
if (reminderTime > now) {
const delay = reminderTime.getTime() - now.getTime();
setTimeout(() => {
const message = window.CONFIG.whatsapp.messageTemplates.reminder
.replace('{subject}', task.name)
.replace('{minutes}', minutes);
sendWhatsAppMessage(message, phone);
}, delay);
}
});
}
function sendTestNotification(type) {
const phone = localStorage.getItem('whatsapp_number');
if (!phone) {
showNotification('Please setup WhatsApp first', 'error');
return;
}
let message;
if (type === 'reminder') {
message = '🎓 Test Reminder: This is a sample study reminder from StudyBuddy!';
} else {
message = '💪 Keep going! You\'re doing amazing work with your studies!';
}
sendWhatsAppMessage(message, phone);
}
async function replanSchedule() {
showNotification('AI is replanning your schedule...', 'info');
// Simulate AI replanning
setTimeout(() => {
showNotification('Schedule replanned! Check your updated plan.', 'success');
}, 2000);
}
function exportData() {
const data = {
goal: currentGoal,
tasks: currentTasks,
timestamp: new Date().toISOString()
};
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `studybuddy-data-${new Date().toISOString().split('T')[0]}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showNotification('Data exported successfully!', 'success');
}
function signOut() {
if (clerk) {
clerk.signOut();
}
// Reset application state
currentUser = null;
currentGoal = '';
currentTasks = [];
localStorage.removeItem('whatsapp_number');
location.reload();
}
// Utility Functions
function showLoading(elementId) {
document.getElementById(elementId).classList.remove('hidden');
}
function hideLoading(elementId) {
document.getElementById(elementId).classList.add('hidden');
}
function showNotification(message, type = 'info') {
const notification = document.createElement('div');
notification.className = `notification ${type} show`;
notification.textContent = message;
document.getElementById('notification-container').appendChild(notification);
setTimeout(() => {
notification.classList.remove('show');
setTimeout(() => notification.remove(), 300);
}, 3000);
}
// Make toggleTask globally available
window.toggleTask = toggleTask;
</script>
</body>
</html>