-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
2353 lines (2092 loc) · 121 KB
/
index.html
File metadata and controls
2353 lines (2092 loc) · 121 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flexnode Go! CMMS</title>
<script src="https://cdn.tailwindcss.com"></script>
<!-- Tone.js for audio effects -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/tone/14.7.77/Tone.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Inter', sans-serif;
}
/* Custom scrollbar */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 10px;
}
::-webkit-scrollbar-thumb {
background: #a8a8a8;
border-radius: 10px;
}
::-webkit-scrollbar-thumb:hover {
background: #888;
}
/* Simple spinner */
.spinner {
border: 4px solid rgba(0, 0, 0, 0.1);
border-left-color: #3b82f6;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
/* Profile picture */
.profile-pic {
width: 40px;
height: 40px;
border-radius: 50%;
background-color: #e0e7ff; /* indigo-100 */
color: #3730a3; /* indigo-800 */
display: flex;
align-items: center;
justify-content: center;
font-weight: 600;
font-size: 1.1rem;
object-fit: cover;
}
/* PIN dots */
.pin-dot {
width: 1rem;
height: 1rem;
border-radius: 50%;
background-color: #e5e7eb; /* gray-200 */
transition: background-color 0.2s ease;
}
.pin-dot.filled {
background-color: #3b82f6; /* blue-500 */
}
/* PIN keypad */
.keypad-btn {
width: 70px;
height: 70px;
border-radius: 50%;
background-color: #f3f4f6; /* gray-100 */
color: #1f2937; /* gray-800 */
font-size: 1.5rem;
font-weight: 500;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: background-color 0.2s ease;
}
.keypad-btn:hover {
background-color: #e5e7eb; /* gray-200 */
}
.keypad-btn:active {
background-color: #d1d5db; /* gray-300 */
}
.keypad-btn.icon-btn {
background-color: transparent;
}
.keypad-btn.icon-btn:hover {
background-color: #f3f4f6; /* gray-100 */
}
/* Video Intro */
#videoIntro {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 60;
background-color: #000;
}
#introVideo {
width: 100%;
height: 100%;
object-fit: cover;
}
#skipIntroBtn {
position: absolute;
bottom: 30px;
right: 30px;
z-index: 61;
padding: 10px 20px;
background-color: rgba(255, 255, 255, 0.2);
color: white;
border: 1px solid white;
border-radius: 8px;
font-weight: 500;
cursor: pointer;
transition: background-color 0.2s;
}
#skipIntroBtn:hover {
background-color: rgba(255, 255, 255, 0.4);
}
/* Shake animation for PIN error */
@keyframes shake {
0%, 100% { transform: translateX(0); }
10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
20%, 40%, 60%, 80% { transform: translateX(5px); }
}
.animate-shake {
animation: shake 0.5s ease-in-out;
}
</style>
</head>
<body class="bg-gray-100 h-screen flex">
<!-- Video Intro -->
<div id="videoIntro" class="hidden">
<video id="introVideo" playsinline muted>
<!-- Source will be set by JS -->
</video>
<button id="skipIntroBtn">Skip Intro</button>
</div>
<!-- Loading Overlay -->
<div id="loadingOverlay" class="fixed inset-0 bg-white z-50 flex flex-col items-center justify-center">
<div class="spinner"></div>
<p id="loadingText" class="mt-4 text-lg font-medium text-gray-700">Loading CMMS...</p>
<p id="loadingErrorDetails" class="mt-2 text-sm text-red-500 max-w-lg text-center"></p>
</div>
<!-- PIN Unlock Screen -->
<div id="pinUnlockScreen" class="fixed inset-0 bg-gray-100 z-40 hidden flex-col items-center justify-center p-4">
<div class="w-full max-w-xs mx-auto">
<div class="flex items-center justify-center space-x-2 mb-6">
<svg class="w-8 h-8 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4"></path></svg>
<h1 class="text-3xl font-bold text-gray-800">Flexnode Go!</h1>
</div>
<p class="text-center text-lg text-gray-700 font-medium mb-2">Enter your PIN</p>
<p id="pinUserEmail" class="text-center text-gray-500 mb-4 truncate"></p>
<!-- PIN Dots -->
<div id="pinDots" class="flex justify-center space-x-4 mb-6">
<div class="pin-dot"></div>
<div class="pin-dot"></div>
<div class="pin-dot"></div>
<div class="pin-dot"></div>
</div>
<p id="pinError" class="text-center text-red-500 text-sm h-5 mb-4"></p>
<!-- Keypad -->
<div id="pinKeypad" class="grid grid-cols-3 gap-4">
<button class="keypad-btn" data-key="1">1</button>
<button class="keypad-btn" data-key="2">2</button>
<button class="keypad-btn" data-key="3">3</button>
<button class="keypad-btn" data-key="4">4</button>
<button class="keypad-btn" data-key="5">5</button>
<button class="keypad-btn" data-key="6">6</button>
<button class="keypad-btn" data-key="7">7</button>
<button class="keypad-btn" data-key="8">8</button>
<button class="keypad-btn" data-key="9">9</button>
<div class="w-70 h-70"></div> <!-- Placeholder -->
<button class="keypad-btn" data-key="0">0</button>
<button class="keypad-btn icon-btn flex items-center justify-center !text-gray-500" data-key="backspace">
<svg class="w-8 h-8 pointer-events-none" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2M3 12l6.414 6.414a2 2 0 002.828 0L19 12M3 12l6.414-6.414a2 2 0 012.828 0L19 12"></path></svg>
</button>
</div>
<p class="text-sm text-center text-gray-600 mt-8">
Not you?
<button id="fullLogoutBtn" class="font-medium text-blue-600 hover:text-blue-500">
Sign out completely
</button>
</p>
</div>
</div>
<!-- Main Content Area -->
<div id="contentArea" class="hidden flex-col flex-1 h-screen">
<!-- Sidebar -->
<div id="sidebar" class="w-64 bg-white border-r border-gray-200 p-5 hidden md:flex flex-col h-full">
<div class="flex items-center space-x-2 mb-8">
<svg class="w-8 h-8 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4"></path></svg>
<h1 class="text-2xl font-bold text-gray-800">Flexnode Go!</h1>
</div>
<nav id="mainNav" class="flex flex-col space-y-2 flex-1">
<!-- Nav items will be injected by JS -->
</nav>
<div class="mt-auto">
<div id="userInfo" class="text-sm text-gray-600 mb-4 p-3 bg-gray-50 rounded-lg">
<div class="flex items-center space-x-3">
<div id="userAvatar" class="profile-pic"></div>
<div class="flex-1 min-w-0">
<span id="userEmailDisplay" class="font-medium block truncate text-gray-800"></span>
<span id="userRoleDisplay" class="text-xs text-gray-500"></span>
</div>
</div>
</div>
<button id="lockAppButton" class="w-full bg-gray-200 text-gray-800 py-2 px-4 rounded-lg hover:bg-gray-300 transition duration-200 flex items-center justify-center space-x-2 font-medium">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path></svg>
<span>Lock App</span>
</button>
</div>
</div>
<!-- Mobile Header -->
<header class="md:hidden bg-white border-b border-gray-200 p-4 flex justify-between items-center">
<h1 class="text-xl font-bold text-gray-800">Flexnode Go!</h1>
<button id="mobileMenuBtn">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16m-7 6h7"></path></svg>
</button>
</header>
<!-- Mobile Menu (overlay) -->
<div id="mobileMenu" class="fixed inset-0 bg-black bg-opacity-50 z-40 hidden md:hidden">
<div class="w-64 bg-white p-5 h-full flex flex-col">
<div class="flex items-center justify-between mb-8">
<h1 class="text-2xl font-bold text-gray-800">Menu</h1>
<button id="closeMobileMenuBtn">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
</button>
</div>
<nav id="mobileNav" class="flex flex-col space-y-2 flex-1">
<!-- Mobile nav items injected by JS -->
</nav>
<div id="mobileUserInfo" class="text-sm text-gray-600 mb-4 p-3 bg-gray-50 rounded-lg">
<div class="flex items-center space-x-3">
<div id="mobileUserAvatar" class="profile-pic"></div>
<div class="flex-1 min-w-0">
<span id="mobileUserEmailDisplay" class="font-medium block truncate text-gray-800"></span>
<span id="mobileUserRoleDisplay" class="text-xs text-gray-500"></span>
</div>
</div>
</div>
<button id="mobileLockAppButton" class="w-full bg-gray-200 text-gray-800 py-2 px-4 rounded-lg hover:bg-gray-300 transition duration-200 flex items-center justify-center space-x-2 font-medium">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path></svg>
<span>Lock App</span>
</button>
</div>
</div>
<!-- Main View -->
<main id="mainView" class="flex-1 p-4 md:p-8 overflow-y-auto bg-gray-100 h-screen">
<!-- Pages will be rendered here by JS -->
</main>
</div>
<!-- Login/Auth Page -->
<div id="authPage" class="w-full h-screen hidden items-center justify-center bg-gray-100">
<div class="w-full max-w-md bg-white p-8 rounded-2xl shadow-xl">
<div class="flex items-center justify-center space-x-2 mb-6">
<svg class="w-10 h-10 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4"></path></svg>
<h1 class="text-3xl font-bold text-gray-800">Flexnode Go!</h1>
</div>
<h2 id="authTitle" class="text-2xl font-semibold text-center text-gray-700 mb-4">Welcome Back!</h2>
<p id="authSubtitle" class="text-center text-gray-500 mb-6">Please sign in to your account.</p>
<form id="authForm" class="space-y-4">
<div>
<label for="authEmail" class="block text-sm font-medium text-gray-700 mb-1">Email Address</label>
<input type="email" id="authEmail" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500" placeholder="you@company.com">
</div>
<div>
<label for="authPassword" class="block text-sm font-medium text-gray-700 mb-1">Password</slabel>
<input type="password" id="authPassword" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500" placeholder="••••••••">
</div>
<div id="adminPasswordWrapper" class="hidden">
<label for="adminPassword" class="block text-sm font-medium text-gray-700 mb-1">Admin Password</Mlabel>
<input type="password" id="adminPassword" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500" placeholder="Admin setup password">
<p class="text-xs text-gray-500 mt-1">The first user to sign up sets the Admin Password.</p>
</div>
<p id="authError" class="text-sm text-red-500"></p>
<button type="submit" id="authButton" class="w-full bg-blue-600 text-white py-2 px-4 rounded-lg font-semibold hover:bg-blue-700 transition duration-200">
Sign In
</button>
</form>
<p class="text-sm text-center text-gray-600 mt-6">
<span id="authToggleText">Don't have an account?</span>
<button id="authToggleLink" class="font-medium text-blue-600 hover:text-blue-500">
Sign Up
</button>
</p>
</div>
</div>
<!-- Modal Container -->
<div id="modalBackdrop" class="fixed inset-0 bg-black bg-opacity-50 z-40 hidden items-center justify-center p-4">
<div id="modalContent" class="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] flex flex-col">
<!-- Modal Header -->
<div class="flex justify-between items-center p-5 border-b border-gray-200">
<h3 id="modalTitle" class="text-xl font-semibold text-gray-800">Modal Title</h3>
<button id="modalCloseBtn" class="text-gray-400 hover:text-gray-600">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
</button>
</div>
<!-- Modal Body -->
<div id="modalBody" class="p-6 overflow-y-auto">
<!-- Modal body content injected by JS -->
</div>
<!-- Modal Footer -->
<div id="modalFooter" class="p-5 border-t border-gray-200 flex justify-end space-x-3">
<button id="modalCancelBtn" class="px-5 py-2 bg-gray-100 text-gray-700 font-medium rounded-lg hover:bg-gray-200 transition duration-200">Cancel</button>
<button id="modalConfirmBtn" class="px-5 py-2 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 transition duration-200">Confirm</button>
</div>
</div>
</div>
<!-- Admin Password Modal -->
<div id="adminPasswordModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden items-center justify-center p-4">
<div class="bg-white rounded-2xl shadow-2xl w-full max-w-sm p-6">
<h3 class="text-lg font-semibold text-gray-800 mb-4">Admin Access Required</h3>
<p class="text-sm text-gray-600 mb-4">Please enter the admin password to perform this action.</p>
<div class="space-y-2">
<label for="adminPassInput" class="block text-sm font-medium text-gray-700">Admin Password</label>
<input type="password" id="adminPassInput" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-blue-500 focus:border-blue-500" placeholder="••••••••">
<p id="adminPassError" class="text-sm text-red-500"></p>
</div>
<div class="mt-6 flex justify-end space-x-3">
<button id="adminPassCancel" class="px-4 py-2 bg-gray-100 text-gray-700 font-medium rounded-lg hover:bg-gray-200 transition duration-200">Cancel</button>
<button id="adminPassConfirm" class="px-4 py-2 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 transition duration-200">Submit</button>
</div>
</div>
</div>
<!-- JavaScript -->
<script type="module">
// Import Firebase modules
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.2/firebase-app.js";
import {
getAuth,
onAuthStateChanged,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
signOut,
setPersistence,
browserLocalPersistence // Import this
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-auth.js";
import {
getFirestore,
doc,
getDoc,
setDoc,
addDoc,
updateDoc,
deleteDoc,
onSnapshot,
collection,
query,
writeBatch,
serverTimestamp
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-firestore.js";
import {
getStorage,
ref,
uploadBytes,
getDownloadURL,
deleteObject
} from "https://www.gstatic.com/firebasejs/10.12.2/firebase-storage.js";
// --- 1. YOUR FIREBASE CONFIG IS NOW EMBEDDED ---
const firebaseConfig = {
apiKey: "AIzaSyBkz9OYY_wCopkwnPp_NWvMkUR-4AHUXcw",
authDomain: "cmms-eff66.firebaseapp.com",
projectId: "cmms-eff66",
storageBucket: "cmms-eff66.firebasestorage.app",
messagingSenderId: "55720793755",
appId: "1:55720793755:web:767126122fae21ee3a183e",
measurementId: "G-CLJGZBJF5H"
};
// -------------------------------------------
// --- Global State ---
const appState = {
isLoggedIn: false,
isLocked: true, // App starts locked
isAdmin: false,
currentUser: null,
currentUserData: {}, // For profile pic URL, etc.
adminPasswordHash: null,
currentPage: 'dashboard',
data: {
assets: [],
workOrders: [],
technicians: [],
sops: [],
users: {}, // To cache user profile data
},
listeners: [],
isFirstUser: false,
currentPin: "",
pinToCompare: null,
audioReady: false,
authTimeout: null,
authCompleted: false, // Flag to track if onAuthStateChanged has run
};
// --- Audio Synths ---
let clickSynth, successSynth, errorSynth;
function initAudio() {
if (appState.audioReady || typeof Tone === 'undefined') return;
try {
// Create synths
clickSynth = new Tone.MembraneSynth().toDestination();
successSynth = new Tone.PolySynth(Tone.Synth, {
volume: -10,
oscillator: { type: "triangle" },
envelope: { attack: 0.01, decay: 0.1, sustain: 0.2, release: 0.2 }
}).toDestination();
errorSynth = new Tone.AMSynth({
volume: -5,
harmonicity: 1.2,
oscillator: { type: "fatsawtooth" },
envelope: { attack: 0.01, decay: 0.2, sustain: 0, release: 0.1 },
modulation: { type: "square" },
modulationEnvelope: { attack: 0.01, decay: 0.1, sustain: 0, release: 0.1 }
}).toDestination();
appState.audioReady = true;
console.log("Audio initialized.");
} catch (e) {
console.error("Failed to initialize Tone.js synths:", e);
}
}
// Sound playing functions
function playClick() {
if (!appState.audioReady) return;
try { clickSynth.triggerAttackRelease("C1", "8n", Tone.now()); } catch(e) {}
}
function playSuccess() {
if (!appState.audioReady) return;
try { successSynth.triggerAttackRelease(["C4", "E4", "G4"], "16n", Tone.now()); } catch(e) {}
}
function playError() {
if (!appState.audioReady) return;
try { errorSynth.triggerAttackRelease("C2", "8n", Tone.now()); } catch(e) {}
}
// --- Firebase Initialization ---
let app, auth, db, storage;
let loadingOverlay, loadingText, loadingErrorDetails, contentArea, authPage, pinUnlockScreen, videoIntro;
let mainView, mainNav, mobileNav, userInfo, mobileUserInfo;
document.addEventListener("DOMContentLoaded", () => {
// Get references to all main UI elements
loadingOverlay = document.getElementById("loadingOverlay");
loadingText = document.getElementById("loadingText");
loadingErrorDetails = document.getElementById("loadingErrorDetails");
contentArea = document.getElementById("contentArea");
authPage = document.getElementById("authPage");
pinUnlockScreen = document.getElementById("pinUnlockScreen");
videoIntro = document.getElementById("videoIntro");
mainView = document.getElementById("mainView");
mainNav = document.getElementById("mainNav");
mobileNav = document.getElementById("mobileNav");
userInfo = document.getElementById("userInfo");
mobileUserInfo = document.getElementById("mobileUserInfo");
// Universal click listener to init audio
document.body.addEventListener('click', (e) => {
if (!appState.audioReady && typeof Tone !== 'undefined') {
Tone.start();
initAudio();
}
// Check if the click was on a button or link
if (e.target.closest('button, a')) {
playClick();
}
}, true); // Use capture to ensure it runs early
try {
// Config is now hardcoded.
app = initializeApp(firebaseConfig);
auth = getAuth(app);
db = getFirestore(app);
storage = getStorage(app); // Initialize Storage
console.log("Firebase initialized.");
// Try to show video intro
showVideoIntro();
} catch (error) {
console.error("Firebase initialization error:", error);
showLoadingError("Firebase Init Error", error.message);
}
});
function showLoadingError(errorMsg, errorDetails = "") {
loadingText.textContent = errorMsg;
loadingErrorDetails.textContent = errorDetails;
loadingText.classList.add('text-red-500');
document.querySelector('#loadingOverlay .spinner').classList.add('hidden');
}
async function showVideoIntro() {
try {
const videoRef = ref(storage, "intro.mp4");
const videoURL = await getDownloadURL(videoRef);
const videoPlayer = document.getElementById("introVideo");
const skipIntroBtn = document.getElementById("skipIntroBtn");
videoPlayer.src = videoURL;
videoIntro.classList.remove("hidden");
const onVideoEnd = () => {
videoIntro.classList.add("hidden");
startAppInitialization(); // Start app auth etc.
};
videoPlayer.play().catch(e => {
// Autoplay failed, likely due to browser policy.
console.warn("Video autoplay failed, user must interact or skip.");
// We still need to show the skip button and let the user proceed.
});
videoPlayer.onended = onVideoEnd;
skipIntroBtn.onclick = () => {
playClick(); // Play click on skip
videoPlayer.pause();
onVideoEnd();
};
} catch(error) {
console.warn("Could not find 'intro.mp4'. Skipping video intro.", error.code);
startAppInitialization(); // No video found, start app
}
}
function startAppInitialization() {
console.log("Setting Firebase persistence...");
// This is the fix for sandboxed environments like the preview panel
setPersistence(auth, browserLocalPersistence)
.then(() => {
console.log("Firebase persistence set to local.");
initializeAuthListener();
})
.catch((error) => {
console.error("Error setting Firebase persistence:", error);
// Even if persistence fails, try to initialize auth
// This might be the path taken in very restrictive sandboxes
initializeAuthListener();
});
}
// --- Authentication ---
function initializeAuthListener() {
if (!auth) return;
console.log("Initializing Auth Listener...");
// ** NEW: Auth Timeout **
// If onAuthStateChanged doesn't fire in 10s, assume it's blocked
// and show the login page.
appState.authTimeout = setTimeout(() => {
if (appState.authCompleted) return; // All good, it ran
console.warn("Auth state check timed out (10s).");
console.warn("This is common in sandboxed environments (like this preview).");
console.warn("Forcing login page to display.");
appState.isLoggedIn = false;
appState.isLocked = true;
// Show auth page, hide everything else
contentArea.classList.add("hidden");
pinUnlockScreen.classList.add("hidden");
loadingOverlay.classList.add("hidden");
authPage.classList.remove("hidden");
authPage.classList.add("flex"); // Make sure it's visible
showLoadingError("Auth Check Timed Out", "Please sign in to continue. This can happen in restrictive browser environments.");
// We don't hide the loading overlay, just show the error on it
// and also show the auth page *behind* it. Let's hide it.
loadingOverlay.classList.add("hidden");
}, 10000); // 10 second timeout
onAuthStateChanged(auth, async (user) => {
console.log("onAuthStateChanged fired.");
appState.authCompleted = true; // Mark as completed
clearTimeout(appState.authTimeout); // Clear the timeout
if (user) {
// User is signed in
console.log("User is SIGNED IN:", user.uid);
appState.currentUser = user;
appState.isLoggedIn = true;
// Fetch app config (admin password hash)
const configRef = doc(db, "config", "main");
const configSnap = await getDoc(configRef);
if (!configSnap.exists()) {
console.log("No config found. This is the first user.");
appState.isFirstUser = true;
} else {
appState.isFirstUser = false;
appState.adminPasswordHash = configSnap.data().adminPasswordHash;
// Check if this user is an admin (e.g., in a roles doc)
const userRolesRef = doc(db, "roles", user.uid);
const userRolesSnap = await getDoc(userRolesRef);
appState.isAdmin = userRolesSnap.exists() && userRolesSnap.data().isAdmin;
console.log("User admin status:", appState.isAdmin);
}
// Fetch user's profile data (pic, etc.)
await fetchCurrentUserData();
// Check for a saved PIN
const pinHash = getPINHash(user.uid);
if (pinHash) {
appState.pinToCompare = pinHash;
appState.isLocked = true;
showPinUnlockScreen();
} else {
// No PIN set, unlock app immediately
playSuccess();
appState.isLocked = false;
initializeAppForUser();
}
} else {
// User is signed out
console.log("User is SIGNED OUT.");
appState.isLoggedIn = false;
appState.isLocked = true;
appState.currentUser = null;
appState.isAdmin = false;
appState.currentUserData = {};
appState.currentPin = "";
appState.pinToCompare = null;
// Unsubscribe from all data listeners
appState.listeners.forEach(unsubscribe => unsubscribe());
appState.listeners = [];
// Show auth page, hide everything else
contentArea.classList.add("hidden");
pinUnlockScreen.classList.add("hidden");
loadingOverlay.classList.add("hidden");
authPage.classList.remove("hidden");
authPage.classList.add("flex"); // Make sure it's visible
// Check if this is the first user setup
try {
const configRef = doc(db, "config", "main");
const configSnap = await getDoc(configRef);
appState.isFirstUser = !configSnap.exists();
} catch (e) {
console.error("Could not check for first user:", e);
appState.isFirstUser = false; // Fail safe
}
toggleAuthMode(true); // Show login page by default
}
}, (error) => {
// This is the error callback for onAuthStateChanged
console.error("onAuthStateChanged ERROR:", error);
appState.authCompleted = true; // Mark as completed (with error)
clearTimeout(appState.authTimeout); // Clear the timeout
showLoadingError("Authentication Error", error.message);
// Show auth page as a fallback
authPage.classList.remove("hidden");
authPage.classList.add("flex");
loadingOverlay.classList.add("hidden");
});
}
async function fetchCurrentUserData() {
if (!appState.currentUser) return;
console.log("Fetching user data for:", appState.currentUser.uid);
const userDocRef = doc(db, "users", appState.currentUser.uid);
const userDocSnap = await getDoc(userDocRef);
if (userDocSnap.exists()) {
appState.currentUserData = userDocSnap.data();
appState.data.users[appState.currentUser.uid] = appState.currentUserData;
} else {
// No profile doc yet, create a basic one
console.log("No user doc, creating one...");
appState.currentUserData = { email: appState.currentUser.email, profilePicUrl: null, initials: getInitials(appState.currentUser.email) };
try {
await setDoc(userDocRef, appState.currentUserData, { merge: true });
} catch (e) {
console.error("Failed to create user doc:", e);
}
}
console.log("Fetched user data:", appState.currentUserData);
}
async function initializeAppForUser() {
if (!appState.currentUser || appState.isLocked) return;
console.log("Initializing app for user...");
setupNavigation();
setupDataListeners();
renderPage('dashboard');
// Setup mobile menu listeners
const mobileMenuBtn = document.getElementById('mobileMenuBtn');
const mobileMenu = document.getElementById('mobileMenu');
const closeMobileMenuBtn = document.getElementById('closeMobileMenuBtn');
mobileMenuBtn.onclick = () => mobileMenu.classList.remove('hidden');
closeMobileMenuBtn.onclick = () => mobileMenu.classList.add('hidden');
mobileMenu.onclick = (e) => {
if (e.target === mobileMenu) {
mobileMenu.classList.add('hidden');
}
};
// Setup lock buttons
document.getElementById('lockAppButton').onclick = lockApp;
document.getElementById('mobileLockAppButton').onclick = lockApp;
// Setup modal close buttons
document.getElementById('modalCloseBtn').onclick = closeModal;
document.getElementById('modalCancelBtn').onclick = closeModal;
document.getElementById('modalBackdrop').onclick = (e) => {
if (e.target === document.getElementById('modalBackdrop')) {
closeModal();
}
};
// Setup admin pass modal
document.getElementById('adminPassCancel').onclick = closeAdminModal;
document.getElementById('adminPassConfirm').onclick = checkAdminPassword;
document.getElementById('adminPasswordModal').onclick = (e) => {
if (e.target === document.getElementById('adminPasswordModal')) {
closeAdminModal();
}
};
// Hide loading/auth/pin, show main app
authPage.classList.add("hidden");
authPage.classList.remove("flex");
pinUnlockScreen.classList.add("hidden");
pinUnlockScreen.classList.remove("flex");
loadingOverlay.classList.add("hidden");
contentArea.classList.remove("hidden");
contentArea.classList.add("flex"); // Use flex for layout
}
// --- Hashing Utility (for PIN and Admin Pass) ---
async function hashString(str) {
if (typeof str !== 'string' || str.length === 0) {
console.error("Invalid input to hashString");
return null;
}
try {
const buffer = new TextEncoder().encode(str);
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
} catch (e) {
console.error("Hashing failed:", e);
return null;
}
}
function getInitials(email) {
if (!email) return "?";
const parts = email.split('@')[0].split(/[._-]/);
if (parts.length > 1 && parts[0] && parts[1]) {
return (parts[0][0] + parts[1][0]).toUpperCase();
}
if (parts.length > 0 && parts[0] && parts[0].length > 1) {
return parts[0].substring(0, 2).toUpperCase();
}
if (email.length > 1) {
return email.substring(0, 2).toUpperCase();
}
return "?";
}
function updateUserAvatar(user, userData) {
const avatar = document.getElementById('userAvatar');
const mobileAvatar = document.getElementById('mobileUserAvatar');
const emailDisplay = document.getElementById('userEmailDisplay');
const mobileEmailDisplay = document.getElementById('mobileUserEmailDisplay');
const roleDisplay = document.getElementById('userRoleDisplay');
const mobileRoleDisplay = document.getElementById('mobileUserRoleDisplay');
if (!avatar || !mobileAvatar) {
console.warn("Avatar elements not found, skipping update.");
return; // In case elements aren't rendered yet
}
const email = user.email;
const picUrl = userData?.profilePicUrl;
const initials = userData?.initials || getInitials(email);
if (picUrl) {
avatar.innerHTML = `<img src="${picUrl}" alt="Profile" class="profile-pic">`;
mobileAvatar.innerHTML = `<img src="${picUrl}" alt="Profile" class="profile-pic">`;
} else {
avatar.innerHTML = `<span>${initials}</span>`;
mobileAvatar.innerHTML = `<span>${initials}</span>`;
}
emailDisplay.textContent = email;
emailDisplay.title = email;
mobileEmailDisplay.textContent = email;
mobileEmailDisplay.title = email;
const role = appState.isAdmin ? 'Admin' : 'Technician';
roleDisplay.textContent = role;
mobileRoleDisplay.textContent = role;
}
// --- Auth UI Logic ---
const authForm = document.getElementById("authForm");
const authEmail = document.getElementById("authEmail");
const authPassword = document.getElementById("authPassword");
const authButton = document.getElementById("authButton");
const authToggleLink = document.getElementById("authToggleLink");
const authTitle = document.getElementById("authTitle");
const authSubtitle = document.getElementById("authSubtitle");
const authToggleText = document.getElementById("authToggleText");
const authError = document.getElementById("authError");
const adminPasswordWrapper = document.getElementById("adminPasswordWrapper");
const adminPasswordInput = document.getElementById("adminPassword");
let isLoginMode = true;
function toggleAuthMode(forceLogin = null) {
isLoginMode = (forceLogin !== null) ? forceLogin : !isLoginMode;
authError.textContent = "";
if (authForm) authForm.reset();
if (isLoginMode) {
// Switched to Login Mode
authTitle.textContent = "Welcome Back!";
authSubtitle.textContent = "Please sign in to your account.";
authButton.textContent = "Sign In";
authToggleText.textContent = "Don't have an account?";
authToggleLink.textContent = "Sign Up";
adminPasswordWrapper.classList.add("hidden");
} else {
// Switched to Sign Up Mode
authTitle.textContent = "Create an Account";
authSubtitle.textContent = "Get started with your new CMMS.";
authButton.textContent = "Sign Up";
authToggleText.textContent = "Already have an account?";
authToggleLink.textContent = "Sign In";
// Show admin password field ONLY if this is the first user
if (appState.isFirstUser) {
adminPasswordWrapper.classList.remove("hidden");
if (adminPasswordInput) adminPasswordInput.required = true;
} else {
adminPasswordWrapper.classList.add("hidden");
if (adminPasswordInput) adminPasswordInput.required = false;
}
}
}
if (authToggleLink) {
authToggleLink.onclick = () => toggleAuthMode();
}
if (authForm) {
authForm.onsubmit = async (e) => {
e.preventDefault();
authButton.disabled = true;
authButton.textContent = "Processing...";
authError.textContent = "";
const email = authEmail.value;
const password = authPassword.value;
try {
if (isLoginMode) {
// --- Login Logic ---
await signInWithEmailAndPassword(auth, email, password);
// onAuthStateChanged will handle the rest (plays success sound)
} else {
// --- Sign Up Logic ---
if (appState.isFirstUser) {
// First user MUST set an admin password
const adminPassword = adminPasswordInput.value;
if (adminPassword.length < 6) {
throw new Error("Admin password must be at least 6 characters.");
}
// 1. Create the user
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
const user = userCredential.user;
// 2. Hash and save the admin password
const adminPasswordHash = await hashString(adminPassword);
if (!adminPasswordHash) throw new Error("Could not hash admin password.");
const configRef = doc(db, "config", "main");
await setDoc(configRef, { adminPasswordHash });
// 3. Make this user an admin
const userRolesRef = doc(db, "roles", user.uid);
await setDoc(userRolesRef, { isAdmin: true });
// 4. Create their user profile doc
const userDocRef = doc(db, "users", user.uid);
await setDoc(userDocRef, { email: user.email, profilePicUrl: null, initials: getInitials(user.email) });
appState.adminPasswordHash = adminPasswordHash;
appState.isAdmin = true; // First user is admin
appState.isFirstUser = false; // No longer the first user
} else {
// Regular user sign up
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
const user = userCredential.user;
// 2. Create their user profile doc
const userDocRef = doc(db, "users", user.uid);
await setDoc(userDocRef, { email: user.email, profilePicUrl: null, initials: getInitials(user.email) });
// 3. (Optional) Create a default role (non-admin)
const userRolesRef = doc(db, "roles", user.uid);
await setDoc(userRolesRef, { isAdmin: false });
}
// onAuthStateChanged will handle the rest
}
} catch (error) {
console.error("Auth error:", error);
authError.textContent = error.message;
playError();
authButton.disabled = false;
toggleAuthMode(isLoginMode); // Reset form state
}
};
}
// --- PIN Unlock Logic ---
const pinKeypad = document.getElementById("pinKeypad");
const pinDotsContainer = document.getElementById("pinDots");
const pinError = document.getElementById("pinError");
const pinUserEmail = document.getElementById("pinUserEmail");
const fullLogoutBtn = document.getElementById("fullLogoutBtn");
function showPinUnlockScreen() {
console.log("Showing PIN unlock screen.");
appState.currentPin = "";
updatePinDots();
pinError.textContent = "";
pinUserEmail.textContent = appState.currentUser.email;
authPage.classList.add("hidden");
authPage.classList.remove("flex");
contentArea.classList.add("hidden");
contentArea.classList.remove("flex");
loadingOverlay.classList.add("hidden");
pinUnlockScreen.classList.remove("hidden");
pinUnlockScreen.classList.add("flex"); // Use flex to center
}
if (pinKeypad) {
pinKeypad.onclick = (e) => {
const key = e.target.dataset.key;
if (!key) return;
playClick(); // Play click sound
pinError.textContent = "";