Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1095 lines (936 loc) · 37.4 KB
/
Copy pathscript.js
File metadata and controls
1095 lines (936 loc) · 37.4 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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function () {
"use strict";
// ======================================================
// THEME TOGGLE
// ======================================================
var savedTheme = localStorage.getItem("theme") || "dark";
document.documentElement.setAttribute("data-theme", savedTheme);
updateToggleUI(savedTheme);
document.getElementById("theme-toggle").addEventListener("click", function () {
var current = document.documentElement.getAttribute("data-theme") || "dark";
var next = current === "dark" ? "light" : "dark";
document.documentElement.setAttribute("data-theme", next);
localStorage.setItem("theme", next);
updateToggleUI(next);
});
function updateToggleUI(theme) {
var icon = document.getElementById("toggle-icon");
var label = document.getElementById("toggle-label");
if (theme === "dark") {
icon.textContent = "☀";
label.textContent = "Light";
} else {
icon.textContent = "☾";
label.textContent = "Dark";
}
}
// ======================================================
// UTILITIES
// ======================================================
var MONTHS = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var MONTH_FULL = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var DAYS = ["SUN","MON","TUE","WED","THU","FRI","SAT"];
var DAY_HEADERS = ["MON","TUE","WED","THU","FRI","SAT","SUN"];
var now = new Date();
function dateKey(d) {
var y = d.getFullYear();
var m = String(d.getMonth() + 1).padStart(2, "0");
var day = String(d.getDate()).padStart(2, "0");
return y + "-" + m + "-" + day;
}
function todayKey() { return dateKey(now); }
function uid() {
return Date.now().toString(36) + Math.random().toString(36).substr(2, 6);
}
function formatDate(iso) {
var p = iso.split("-");
return parseInt(p[2]) + " " + MONTHS[parseInt(p[1]) - 1] + " " + p[0];
}
function formatTimestamp(ts) {
var d = new Date(ts);
var h = d.getHours(), m = d.getMinutes();
var ampm = h >= 12 ? "PM" : "AM";
h = h % 12 || 12;
return h + ":" + String(m).padStart(2, "0") + " " + ampm;
}
// ======================================================
// DATE STAMP
// ======================================================
document.getElementById("today-stamp").textContent =
DAYS[now.getDay()] + " " + now.getDate() + " " + MONTHS[now.getMonth()] + " " + now.getFullYear();
// ======================================================
// LOCAL STORAGE
// ======================================================
function loadData(key, fallback) {
try {
var raw = localStorage.getItem(key);
return raw ? JSON.parse(raw) : fallback;
} catch (e) {
return fallback;
}
}
function saveData(key, data) {
try {
localStorage.setItem(key, JSON.stringify(data));
} catch (e) {
console.warn("Storage full or unavailable", e);
}
}
var lawxisNotes = loadData("lawxis_notes", []);
var jobprepTasks = loadData("jobprep_tasks", []);
function persistNotes() { saveData("lawxis_notes", lawxisNotes); }
function persistTasks() { saveData("jobprep_tasks", jobprepTasks); }
// ======================================================
// SUPABASE DATABASE & CLOUD SYNC
// ======================================================
var supabaseClient = null;
var syncStatusDot = document.getElementById("sync-status-dot");
var syncStatusLabel = document.getElementById("sync-status-label");
var syncConnBadge = document.getElementById("sync-connection-badge");
var syncConnDetail = document.getElementById("sync-connection-detail");
var inputSupabaseUrl = document.getElementById("supabase-url");
var inputSupabaseKey = document.getElementById("supabase-key");
function setSyncUIState(state, detailText) {
if (!syncStatusDot) return;
syncStatusDot.className = "sync-dot " + state;
if (state === "online") {
syncStatusLabel.textContent = "Cloud";
syncConnBadge.textContent = "CONNECTED TO SUPABASE";
syncConnBadge.className = "tag insight";
if (syncConnDetail) {
syncConnDetail.textContent = detailText || "Connected to PostgreSQL database. Changes sync automatically in real-time.";
}
} else if (state === "syncing") {
syncStatusLabel.textContent = "Syncing";
if (syncConnDetail && detailText) syncConnDetail.textContent = detailText;
} else {
syncStatusLabel.textContent = "Local";
syncConnBadge.textContent = "LOCAL STORAGE ONLY";
syncConnBadge.className = "tag";
if (syncConnDetail) {
syncConnDetail.textContent = detailText || "Connect your Supabase project to sync your notes and tasks to the cloud across all your devices.";
}
}
}
function initSupabase(url, key) {
if (!url || !key || !window.supabase) {
supabaseClient = null;
setSyncUIState("offline");
return false;
}
try {
supabaseClient = window.supabase.createClient(url.trim(), key.trim());
setSyncUIState("online");
return true;
} catch (err) {
console.warn("Supabase init error:", err);
supabaseClient = null;
setSyncUIState("offline", "Configuration error: " + (err.message || "Invalid credentials"));
return false;
}
}
// Pull notes and tasks from Supabase
async function fetchCloudData(isManual) {
if (!supabaseClient) return;
setSyncUIState("syncing", "Fetching cloud data from Supabase...");
try {
var notesRes = await supabaseClient.from("lawxis_notes").select("*").order("timestamp", { ascending: false });
var tasksRes = await supabaseClient.from("jobprep_tasks").select("*").order("timestamp", { ascending: true });
if (notesRes.error) throw notesRes.error;
if (tasksRes.error) throw tasksRes.error;
if (notesRes.data && Array.isArray(notesRes.data)) {
// Map database records
var cloudNotes = notesRes.data.map(function (n) {
return {
id: n.id,
title: n.title,
content: n.content,
category: n.category,
person: n.person || "",
date: n.date,
timestamp: Number(n.timestamp)
};
});
// Merge: cloud notes take precedence, keep any local-only notes
var cloudNoteIds = new Set(cloudNotes.map(function (n) { return n.id; }));
var localOnlyNotes = lawxisNotes.filter(function (n) { return !cloudNoteIds.has(n.id); });
lawxisNotes = cloudNotes.concat(localOnlyNotes);
persistNotes();
}
if (tasksRes.data && Array.isArray(tasksRes.data)) {
var cloudTasks = tasksRes.data.map(function (t) {
return {
id: t.id,
description: t.description,
category: t.category,
priority: t.priority,
date: t.date,
completed: Boolean(t.completed),
completedAt: t.completed_at ? Number(t.completed_at) : null,
timestamp: Number(t.timestamp)
};
});
var cloudTaskIds = new Set(cloudTasks.map(function (t) { return t.id; }));
var localOnlyTasks = jobprepTasks.filter(function (t) { return !cloudTaskIds.has(t.id); });
jobprepTasks = cloudTasks.concat(localOnlyTasks);
persistTasks();
}
// Re-render UI
renderNotes();
updateLawxisStats();
renderTasks();
updateTaskStats();
updateHero();
updateWeekStrip();
renderCalendar();
setSyncUIState("online", "Connected to Supabase PostgreSQL database. Synced just now.");
if (isManual) toast("Synced with Supabase ✓");
} catch (err) {
console.warn("Cloud sync error:", err);
setSyncUIState("offline", "Sync issue: " + (err.message || "Failed to reach database"));
if (isManual) toast("Cloud sync error: " + (err.message || "Failed"));
}
}
// Push local notes and tasks to Supabase
async function pushLocalToCloud() {
if (!supabaseClient) {
toast("Please connect to Supabase first");
return;
}
setSyncUIState("syncing", "Pushing local data to Supabase...");
try {
if (lawxisNotes.length > 0) {
var notesPayload = lawxisNotes.map(function (n) {
return {
id: n.id,
title: n.title,
content: n.content,
category: n.category,
person: n.person || "",
date: n.date,
timestamp: n.timestamp
};
});
var res1 = await supabaseClient.from("lawxis_notes").upsert(notesPayload);
if (res1.error) throw res1.error;
}
if (jobprepTasks.length > 0) {
var tasksPayload = jobprepTasks.map(function (t) {
return {
id: t.id,
description: t.description,
category: t.category,
priority: t.priority,
date: t.date,
completed: t.completed,
completed_at: t.completedAt,
timestamp: t.timestamp
};
});
var res2 = await supabaseClient.from("jobprep_tasks").upsert(tasksPayload);
if (res2.error) throw res2.error;
}
setSyncUIState("online", "Local data pushed to Supabase successfully.");
toast("Local data uploaded to Supabase ✓");
} catch (err) {
console.warn("Push error:", err);
setSyncUIState("offline", "Push error: " + (err.message || "Check schema"));
toast("Push failed: " + (err.message || "Error"));
}
}
// Async cloud mutations with fallback
function cloudInsertNote(note) {
if (!supabaseClient) return;
supabaseClient.from("lawxis_notes").insert([{
id: note.id,
title: note.title,
content: note.content,
category: note.category,
person: note.person || "",
date: note.date,
timestamp: note.timestamp
}]).then(function (res) {
if (res.error) console.warn("Supabase note insert error:", res.error);
});
}
function cloudDeleteNote(id) {
if (!supabaseClient) return;
supabaseClient.from("lawxis_notes").delete().eq("id", id).then(function (res) {
if (res.error) console.warn("Supabase note delete error:", res.error);
});
}
function cloudInsertTask(task) {
if (!supabaseClient) return;
supabaseClient.from("jobprep_tasks").insert([{
id: task.id,
description: task.description,
category: task.category,
priority: task.priority,
date: task.date,
completed: task.completed,
completed_at: task.completedAt,
timestamp: task.timestamp
}]).then(function (res) {
if (res.error) console.warn("Supabase task insert error:", res.error);
});
}
function cloudUpdateTask(task) {
if (!supabaseClient) return;
supabaseClient.from("jobprep_tasks").update({
completed: task.completed,
completed_at: task.completedAt
}).eq("id", task.id).then(function (res) {
if (res.error) console.warn("Supabase task update error:", res.error);
});
}
function cloudDeleteTask(id) {
if (!supabaseClient) return;
supabaseClient.from("jobprep_tasks").delete().eq("id", id).then(function (res) {
if (res.error) console.warn("Supabase task delete error:", res.error);
});
}
// ======================================================
// TOAST
// ======================================================
var toastEl = document.getElementById("toast");
var toastTimer = null;
function toast(msg) {
toastEl.textContent = msg;
toastEl.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(function () {
toastEl.classList.remove("show");
}, 1900);
}
// ======================================================
// TABS
// ======================================================
var tabBtns = document.querySelectorAll("#main-tabs button");
var tabIds = ["lawxis", "jobprep", "calendar"];
tabBtns.forEach(function (b) {
b.addEventListener("click", function () {
tabBtns.forEach(function (x) { x.setAttribute("aria-selected", "false"); });
b.setAttribute("aria-selected", "true");
tabIds.forEach(function (k) {
document.getElementById("p-" + k).hidden = (k !== b.dataset.tab);
});
if (b.dataset.tab === "calendar") {
renderCalendar();
}
});
});
// ======================================================
// HERO STATUS
// ======================================================
function updateHero() {
var today = todayKey();
var todayTasks = jobprepTasks.filter(function (t) { return t.date === today; });
var completedToday = todayTasks.filter(function (t) { return t.completed; }).length;
var totalToday = todayTasks.length;
var todayNotes = lawxisNotes.filter(function (n) { return n.date === today; }).length;
var totalDone = completedToday + todayNotes;
document.getElementById("hero-readout").textContent = totalDone;
var pct = totalToday > 0 ? (completedToday / totalToday) * 100 : (todayNotes > 0 ? 100 : 0);
document.getElementById("hero-gauge-fill").style.width = pct + "%";
document.getElementById("hero-gauge-needle").style.left = pct + "%";
if (totalToday === 0 && todayNotes === 0) {
document.getElementById("hero-state").textContent = "No activity yet";
} else if (totalToday > 0 && completedToday === totalToday) {
document.getElementById("hero-state").textContent = "All tasks complete ✓";
} else if (completedToday > 0 || todayNotes > 0) {
document.getElementById("hero-state").textContent = "In progress";
} else {
document.getElementById("hero-state").textContent = "Tasks pending";
}
}
// ======================================================
// LAWXIS — NOTES
// ======================================================
var currentFilter = "all";
function renderNotes() {
var container = document.getElementById("notes-list");
var emptyEl = document.getElementById("notes-empty");
var filtered = currentFilter === "all"
? lawxisNotes
: lawxisNotes.filter(function (n) { return n.category === currentFilter; });
// Sort newest first
filtered = filtered.slice().sort(function (a, b) { return b.timestamp - a.timestamp; });
// Clear existing note cards (keep empty state)
var cards = container.querySelectorAll(".note-card");
cards.forEach(function (c) { c.remove(); });
document.getElementById("notes-count").textContent = filtered.length + " note" + (filtered.length !== 1 ? "s" : "");
if (filtered.length === 0) {
emptyEl.style.display = "block";
return;
}
emptyEl.style.display = "none";
filtered.forEach(function (note) {
var card = document.createElement("div");
card.className = "note-card";
card.innerHTML =
'<div class="note-card-head">' +
'<span class="note-title">' + escapeHtml(note.title) + '</span>' +
'<span class="tag ' + note.category + '">' + note.category.toUpperCase() + '</span>' +
'</div>' +
'<div class="note-body">' + escapeHtml(note.content) + '</div>' +
'<div class="note-card-foot">' +
(note.person ? '<span class="note-person">↗ ' + escapeHtml(note.person) + '</span>' : '<span></span>') +
'<div style="display:flex;gap:8px;align-items:center">' +
'<span class="note-date">' + formatDate(note.date) + ' · ' + formatTimestamp(note.timestamp) + '</span>' +
'<button class="danger-ghost" data-delete-note="' + note.id + '">Delete</button>' +
'</div>' +
'</div>';
container.appendChild(card);
});
// Delete handlers
container.querySelectorAll("[data-delete-note]").forEach(function (btn) {
btn.addEventListener("click", function () {
var id = btn.getAttribute("data-delete-note");
lawxisNotes = lawxisNotes.filter(function (n) { return n.id !== id; });
persistNotes();
cloudDeleteNote(id);
renderNotes();
updateLawxisStats();
updateHero();
toast("Note deleted");
});
});
}
function updateLawxisStats() {
document.getElementById("stat-total-notes").textContent = lawxisNotes.length;
document.getElementById("stat-interviews").textContent = lawxisNotes.filter(function (n) { return n.category === "interview"; }).length;
document.getElementById("stat-insights").textContent = lawxisNotes.filter(function (n) { return n.category === "insight"; }).length;
}
// Save note
document.getElementById("btn-save-note").addEventListener("click", function () {
var title = document.getElementById("note-title").value.trim();
var content = document.getElementById("note-content").value.trim();
var category = document.getElementById("note-category").value;
var person = document.getElementById("note-person").value.trim();
if (!title) {
toast("Title is required");
document.getElementById("note-title").focus();
return;
}
if (!content) {
toast("Notes content is required");
document.getElementById("note-content").focus();
return;
}
var note = {
id: uid(),
title: title,
content: content,
category: category,
person: person,
date: todayKey(),
timestamp: Date.now()
};
lawxisNotes.push(note);
persistNotes();
cloudInsertNote(note);
renderNotes();
updateLawxisStats();
updateHero();
// Clear form
document.getElementById("note-title").value = "";
document.getElementById("note-content").value = "";
document.getElementById("note-person").value = "";
document.getElementById("note-category").selectedIndex = 0;
toast("Note saved");
});
// Clear form
document.getElementById("btn-clear-note").addEventListener("click", function () {
document.getElementById("note-title").value = "";
document.getElementById("note-content").value = "";
document.getElementById("note-person").value = "";
document.getElementById("note-category").selectedIndex = 0;
});
// Filters
document.getElementById("note-filters").addEventListener("click", function (e) {
var btn = e.target.closest("button[data-filter]");
if (!btn) return;
document.querySelectorAll("#note-filters button").forEach(function (b) {
b.classList.remove("active");
});
btn.classList.add("active");
currentFilter = btn.getAttribute("data-filter");
renderNotes();
});
// ======================================================
// JOB PREP — TASKS
// ======================================================
function renderTasks() {
var container = document.getElementById("tasks-list");
var emptyEl = document.getElementById("tasks-empty");
var today = todayKey();
var todayTasks = jobprepTasks.filter(function (t) { return t.date === today; });
// Sort: incomplete first, then by timestamp
todayTasks.sort(function (a, b) {
if (a.completed !== b.completed) return a.completed ? 1 : -1;
return a.timestamp - b.timestamp;
});
// Clear existing items
var items = container.querySelectorAll(".task-item");
items.forEach(function (i) { i.remove(); });
document.getElementById("tasks-today-count").textContent = todayTasks.length + " task" + (todayTasks.length !== 1 ? "s" : "");
if (todayTasks.length === 0) {
emptyEl.style.display = "block";
return;
}
emptyEl.style.display = "none";
todayTasks.forEach(function (task) {
var div = document.createElement("div");
div.className = "task-item" + (task.completed ? " completed" : "");
div.innerHTML =
'<input type="checkbox"' + (task.completed ? ' checked' : '') + ' data-task-id="' + task.id + '">' +
'<span class="task-text">' + escapeHtml(task.description) + '</span>' +
'<div class="task-meta">' +
'<span class="tag ' + getCategoryTagClass(task.category) + '">' + formatCategory(task.category) + '</span>' +
'<span class="priority-dot ' + task.priority + '" title="' + task.priority + ' priority"></span>' +
'<button class="danger-ghost" data-delete-task="' + task.id + '">✕</button>' +
'</div>';
container.appendChild(div);
});
// Checkbox handlers
container.querySelectorAll("[data-task-id]").forEach(function (cb) {
cb.addEventListener("change", function () {
var id = cb.getAttribute("data-task-id");
var task = jobprepTasks.find(function (t) { return t.id === id; });
if (task) {
task.completed = cb.checked;
task.completedAt = cb.checked ? Date.now() : null;
persistTasks();
cloudUpdateTask(task);
renderTasks();
updateTaskStats();
updateHero();
updateWeekStrip();
if (cb.checked) toast("Task completed ✓");
}
});
});
// Delete handlers
container.querySelectorAll("[data-delete-task]").forEach(function (btn) {
btn.addEventListener("click", function () {
var id = btn.getAttribute("data-delete-task");
jobprepTasks = jobprepTasks.filter(function (t) { return t.id !== id; });
persistTasks();
cloudDeleteTask(id);
renderTasks();
updateTaskStats();
updateHero();
updateWeekStrip();
toast("Task deleted");
});
});
}
function getCategoryTagClass(cat) {
var map = {
"dsa": "solid",
"system-design": "blue",
"project": "insight",
"resume": "interview",
"application": "flag",
"mock-interview": "idea",
"study": "solid",
"other": ""
};
return map[cat] || "";
}
function formatCategory(cat) {
return cat.replace(/-/g, " ").toUpperCase();
}
function updateTaskStats() {
var today = todayKey();
var todayTasks = jobprepTasks.filter(function (t) { return t.date === today; });
var done = todayTasks.filter(function (t) { return t.completed; }).length;
var pending = todayTasks.length - done;
document.getElementById("stat-tasks-total").textContent = todayTasks.length;
document.getElementById("stat-tasks-done").textContent = done;
document.getElementById("stat-tasks-pending").textContent = pending;
}
// Add task
document.getElementById("btn-add-task").addEventListener("click", function () {
var desc = document.getElementById("task-desc").value.trim();
var category = document.getElementById("task-category").value;
var priority = document.getElementById("task-priority").value;
if (!desc) {
toast("Task description is required");
document.getElementById("task-desc").focus();
return;
}
var task = {
id: uid(),
description: desc,
category: category,
priority: priority,
date: todayKey(),
completed: false,
completedAt: null,
timestamp: Date.now()
};
jobprepTasks.push(task);
persistTasks();
cloudInsertTask(task);
renderTasks();
updateTaskStats();
updateHero();
updateWeekStrip();
document.getElementById("task-desc").value = "";
toast("Task added");
});
// Enter key to add task
document.getElementById("task-desc").addEventListener("keydown", function (e) {
if (e.key === "Enter") {
e.preventDefault();
document.getElementById("btn-add-task").click();
}
});
// Enter key to save note
document.getElementById("note-title").addEventListener("keydown", function (e) {
if (e.key === "Enter") {
e.preventDefault();
document.getElementById("note-content").focus();
}
});
// Clear task form
document.getElementById("btn-clear-task").addEventListener("click", function () {
document.getElementById("task-desc").value = "";
document.getElementById("task-category").selectedIndex = 0;
document.getElementById("task-priority").selectedIndex = 0;
});
// ======================================================
// WEEK STRIP
// ======================================================
function updateWeekStrip() {
var strip = document.getElementById("week-strip");
strip.innerHTML = "";
// Get Monday of current week
var today = new Date();
var dayOfWeek = today.getDay();
var diff = dayOfWeek === 0 ? 6 : dayOfWeek - 1; // Monday = 0
var monday = new Date(today);
monday.setDate(today.getDate() - diff);
var weekTotal = 0;
for (var i = 0; i < 7; i++) {
var d = new Date(monday);
d.setDate(monday.getDate() + i);
var dk = dateKey(d);
var dayTasks = jobprepTasks.filter(function (t) { return t.date === dk && t.completed; });
var dayNotes = lawxisNotes.filter(function (n) { return n.date === dk; });
var count = dayTasks.length + dayNotes.length;
weekTotal += count;
var btn = document.createElement("button");
btn.type = "button";
btn.setAttribute("aria-pressed", count > 0 ? "true" : "false");
btn.innerHTML =
'<span class="count">' + count + '</span>' +
'<span>' + DAY_HEADERS[i] + '</span>';
if (dk === todayKey()) {
btn.style.borderColor = "var(--signal)";
btn.style.borderWidth = "2px";
}
strip.appendChild(btn);
}
document.getElementById("week-score").textContent = weekTotal;
document.getElementById("week-verdict").textContent = "Activities this week";
}
// ======================================================
// CALENDAR
// ======================================================
// Calendar range: Oct 2026 to Dec 2027
var calYear = now.getFullYear();
var calMonth = now.getMonth(); // 0-indexed
var CAL_MIN_YEAR = 2026, CAL_MIN_MONTH = 9; // Oct 2026
var CAL_MAX_YEAR = 2027, CAL_MAX_MONTH = 11; // Dec 2027
function renderCalendar() {
var grid = document.getElementById("cal-grid");
grid.innerHTML = "";
// Title
document.getElementById("cal-title").textContent = MONTH_FULL[calMonth].toUpperCase() + " " + calYear;
// Nav buttons
document.getElementById("cal-prev").disabled =
(calYear === CAL_MIN_YEAR && calMonth <= CAL_MIN_MONTH);
document.getElementById("cal-next").disabled =
(calYear === CAL_MAX_YEAR && calMonth >= CAL_MAX_MONTH);
// Day headers
DAY_HEADERS.forEach(function (d) {
var h = document.createElement("div");
h.className = "cal-header";
h.textContent = d;
grid.appendChild(h);
});
// First day of month
var firstDay = new Date(calYear, calMonth, 1);
var startDay = firstDay.getDay(); // 0=Sun
// Convert to Mon=0 format
var startOffset = startDay === 0 ? 6 : startDay - 1;
// Days in month
var daysInMonth = new Date(calYear, calMonth + 1, 0).getDate();
// Today key
var todayStr = todayKey();
// Build data lookup for this month
var monthData = {};
for (var d = 1; d <= daysInMonth; d++) {
var dk = calYear + "-" + String(calMonth + 1).padStart(2, "0") + "-" + String(d).padStart(2, "0");
var notesCount = lawxisNotes.filter(function (n) { return n.date === dk; }).length;
var tasksCount = jobprepTasks.filter(function (t) { return t.date === dk; }).length;
if (notesCount > 0 || tasksCount > 0) {
monthData[d] = { notes: notesCount, tasks: tasksCount };
}
}
// Empty cells before first day
for (var e = 0; e < startOffset; e++) {
var empty = document.createElement("div");
empty.className = "cal-cell empty";
grid.appendChild(empty);
}
// Date cells
for (var day = 1; day <= daysInMonth; day++) {
var dk2 = calYear + "-" + String(calMonth + 1).padStart(2, "0") + "-" + String(day).padStart(2, "0");
var cell = document.createElement("div");
cell.className = "cal-cell";
if (dk2 === todayStr) cell.classList.add("today");
if (monthData[day]) cell.classList.add("has-data");
var dateNum = document.createElement("div");
dateNum.className = "cal-date";
dateNum.textContent = day;
cell.appendChild(dateNum);
if (monthData[day]) {
var dots = document.createElement("div");
dots.className = "cal-dots";
if (monthData[day].notes > 0) {
var dotN = document.createElement("span");
dotN.className = "cal-dot lawxis";
dots.appendChild(dotN);
}
if (monthData[day].tasks > 0) {
var dotT = document.createElement("span");
dotT.className = "cal-dot jobprep";
dots.appendChild(dotT);
}
cell.appendChild(dots);
var countText = document.createElement("div");
countText.className = "cal-count";
var parts = [];
if (monthData[day].notes > 0) parts.push(monthData[day].notes + "N");
if (monthData[day].tasks > 0) parts.push(monthData[day].tasks + "T");
countText.textContent = parts.join(" · ");
cell.appendChild(countText);
}
// Click handler
(function (dateStr) {
cell.addEventListener("click", function () {
openDayModal(dateStr);
});
})(dk2);
grid.appendChild(cell);
}
}
// Month navigation
document.getElementById("cal-prev").addEventListener("click", function () {
calMonth--;
if (calMonth < 0) { calMonth = 11; calYear--; }
renderCalendar();
});
document.getElementById("cal-next").addEventListener("click", function () {
calMonth++;
if (calMonth > 11) { calMonth = 0; calYear++; }
renderCalendar();
});
// ======================================================
// DAY DETAIL MODAL
// ======================================================
function openDayModal(dateStr) {
var modal = document.getElementById("day-modal");
var body = document.getElementById("modal-body");
// Parse date for display
var parts = dateStr.split("-");
var dateObj = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]));
var dayName = ["SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY"][dateObj.getDay()];
document.getElementById("modal-date-title").textContent =
dayName + " · " + formatDate(dateStr);
// Get data for this date
var dayNotes = lawxisNotes.filter(function (n) { return n.date === dateStr; })
.sort(function (a, b) { return a.timestamp - b.timestamp; });
var dayTasks = jobprepTasks.filter(function (t) { return t.date === dateStr; })
.sort(function (a, b) { return a.timestamp - b.timestamp; });
var html = "";
// Lawxis section
html += '<div class="modal-section">';
html += '<h3><span class="section-dot green"></span> Lawxis — Research Notes</h3>';
if (dayNotes.length === 0) {
html += '<p class="modal-empty">No research notes on this date</p>';
} else {
dayNotes.forEach(function (note) {
html += '<div class="modal-note-item">';
html += '<div style="display:flex;justify-content:space-between;align-items:center;gap:8px;margin-bottom:6px">';
html += '<strong style="font-size:14px">' + escapeHtml(note.title) + '</strong>';
html += '<span class="tag ' + note.category + '">' + note.category.toUpperCase() + '</span>';
html += '</div>';
html += '<p style="margin:0 0 6px;font-size:14px;opacity:.85;white-space:pre-wrap">' + escapeHtml(note.content) + '</p>';
if (note.person) {
html += '<span class="tiny">↗ ' + escapeHtml(note.person) + ' · ' + formatTimestamp(note.timestamp) + '</span>';
} else {
html += '<span class="tiny">' + formatTimestamp(note.timestamp) + '</span>';
}
html += '</div>';
});
}
html += '</div>';
// Job Prep section
html += '<div class="modal-section">';
html += '<h3><span class="section-dot blue"></span> Job Prep — Tasks</h3>';
if (dayTasks.length === 0) {
html += '<p class="modal-empty">No tasks on this date</p>';
} else {
dayTasks.forEach(function (task) {
var isDone = task.completed;
html += '<div class="modal-task-item' + (isDone ? ' completed' : '') + '">';
html += '<span class="check-icon ' + (isDone ? 'done' : 'pending') + '">' + (isDone ? '☑' : '☐') + '</span>';
html += '<span style="flex:1;font-size:14px">' + escapeHtml(task.description) + '</span>';
html += '<span class="tag ' + getCategoryTagClass(task.category) + '">' + formatCategory(task.category) + '</span>';
html += '</div>';
});
var completedCount = dayTasks.filter(function (t) { return t.completed; }).length;
html += '<p class="tiny" style="margin-top:12px">' + completedCount + '/' + dayTasks.length + ' COMPLETED</p>';
}
html += '</div>';
// Summary
if (dayNotes.length === 0 && dayTasks.length === 0) {
html += '<div class="empty-state" style="padding:20px 0">';
html += '<div class="empty-icon">📅</div>';
html += '<p>No activity recorded on this date</p>';
html += '</div>';
}
body.innerHTML = html;
modal.classList.add("open");
document.body.style.overflow = "hidden";
}
// Close modal
document.getElementById("modal-close").addEventListener("click", closeModal);
document.getElementById("day-modal").addEventListener("click", function (e) {
if (e.target === this) closeModal();
});
document.addEventListener("keydown", function (e) {
if (e.key === "Escape") {
closeModal();
closeSyncModal();
}
});
function closeModal() {
document.getElementById("day-modal").classList.remove("open");
document.body.style.overflow = "";
}
// ======================================================
// SYNC MODAL CONTROLS
// ======================================================
var syncModal = document.getElementById("sync-modal");
var openSyncBtn = document.getElementById("btn-open-sync");
var closeSyncBtn = document.getElementById("sync-modal-close");
function openSyncModal() {
if (inputSupabaseUrl) inputSupabaseUrl.value = localStorage.getItem("supabase_url") || "";
if (inputSupabaseKey) inputSupabaseKey.value = localStorage.getItem("supabase_key") || "";
syncModal.classList.add("open");
document.body.style.overflow = "hidden";
}
function closeSyncModal() {
syncModal.classList.remove("open");
document.body.style.overflow = "";
}
if (openSyncBtn) openSyncBtn.addEventListener("click", openSyncModal);
if (closeSyncBtn) closeSyncBtn.addEventListener("click", closeSyncModal);
if (syncModal) {
syncModal.addEventListener("click", function (e) {
if (e.target === this) closeSyncModal();
});
}
// Connect & Save
document.getElementById("btn-save-sync").addEventListener("click", function () {
var url = (inputSupabaseUrl.value || "").trim();
var key = (inputSupabaseKey.value || "").trim();
if (!url || !key) {
toast("Please enter both Supabase URL and Anon Key");
return;
}