-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
1226 lines (1156 loc) Β· 63.1 KB
/
Copy pathapi.js
File metadata and controls
1226 lines (1156 loc) Β· 63.1 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
// ββ MediFlow Main App ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ββ FOLLOW-UP QUESTIONS per specialty βββββββββββββββββββββββββββββββββββββββββ
const FOLLOWUP = {
"Cardiologist": ["How long have you had this chest pain?", "Does the pain radiate to your arm or jaw?", "Any history of heart disease?"],
"Neurologist": ["Is the headache sudden and severe?", "Any vision changes or weakness?", "How often do these symptoms occur?"],
"Pulmonologist": ["Do you have difficulty breathing at rest or only during activity?", "Any history of smoking or asthma?", "Any fever or cough with sputum?"],
"Gastroenterologist":["When did the abdominal pain start?", "Any blood in stool or vomiting?", "Any recent change in diet?"],
"Orthopedic Surgeon":["Which part of your body is affected?", "Is there any swelling or stiffness?", "Did you have any recent injury or fall?"],
"Urologist": ["Any burning sensation during urination?", "Any blood in urine?", "How long have you had these symptoms?"],
"Dermatologist": ["Where on your body is the rash/skin issue?", "Is it itchy or painful?", "Any new soaps, foods, or medications recently?"],
"Endocrinologist": ["Do you experience excessive thirst or fatigue?", "Any unexplained weight changes?", "Any family history of diabetes or thyroid problems?"],
"Rheumatologist": ["Which joints are affected?", "Is the pain worse in the morning?", "Any family history of arthritis?"],
"Gynecologist": ["Are your periods irregular?", "Any pelvic pain?", "Any recent pregnancy or hormonal changes?"],
"Ophthalmologist": ["Any blurred or double vision?", "Any eye pain or redness?", "How long have you had this issue?"],
"Hematologist": ["Do you bruise easily?", "Any fatigue or pale skin?", "Any history of blood disorders?"],
"Oncologist": ["How long have you noticed this lump/symptom?", "Any unexplained weight loss?", "Any family history of cancer?"],
"ENT Specialist": ["Any hearing loss or ringing in ears?", "Any difficulty swallowing?", "How long have you had this issue?"],
"Nephrologist": ["Any changes in urination frequency?", "Any swelling in legs or face?", "Any known kidney disease?"],
"Infectious Disease Specialist": ["Any recent travel abroad?", "Any fever or chills?", "Have you been in contact with anyone who was sick?"],
"Allergist": ["What triggers your symptoms?", "Any known allergies?", "Do symptoms improve with antihistamines?"],
"Psychiatrist": ["How long have you been experiencing this?", "Are you sleeping and eating normally?", "Any stressful life events recently?"],
"Pediatrician": ["How old is the child?", "Any fever or change in behavior?", "Have they been vaccinated?"],
"General Surgeon": ["Is the pain constant or intermittent?", "Any nausea or vomiting?", "Any visible lump or swelling?"],
};
// ββ APP ROUTER βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const App = {
init() {
if (Session.valid()) {
const role = Session.role();
if (role === "patient") PatientApp.init();
else if (role === "doctor") DoctorApp.init();
else if (role === "admin") AdminApp.init();
else LoginApp.init();
} else {
LoginApp.init();
}
}
};
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// VALIDATION HELPERS
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const Validate = {
name: v => v.trim().length >= 2,
age: v => {const n=parseInt(v); return n>=1 && n<=120;},
phone: v => /^[6-9]\d{9}$/.test(v.trim()), // Indian 10-digit mobile
email: v => v.trim() === "" || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.trim()),
password: v => v.length >= 8 && /[A-Za-z]/.test(v) && /\d/.test(v), // min 8, letter+digit
blood: v => v.trim() === "" || /^(A|B|AB|O)[+-]$/i.test(v.trim()),
rules: {
"r-name": { fn: v => Validate.name(v), ok: "Looks good!", err: "Enter at least 2 characters" },
"r-age": { fn: v => Validate.age(v), ok: "Valid age", err: "Age must be between 1 and 120" },
"r-phone": { fn: v => Validate.phone(v), ok: "Valid Indian mobile number", err: "Must be 10 digits starting with 6-9" },
"r-email": { fn: v => Validate.email(v), ok: "Valid email", err: "Enter a valid email address" },
"r-pw": { fn: v => Validate.password(v), ok: "Strong password β", err: "Min 8 chars, include a letter and number" },
"r-blood": { fn: v => Validate.blood(v), ok: "Valid blood group", err: "Use format: A+, B-, AB+, O-, etc." },
},
attachLive(ids) {
ids.forEach(id => {
const el = document.getElementById(id);
const rule = this.rules[id];
if (!el || !rule) return;
const hint = document.getElementById(`hint-${id}`);
el.addEventListener("input", () => {
const val = el.value;
if (!val.trim()) {
el.classList.remove("valid","invalid");
if (hint) { hint.className="field-hint"; hint.textContent=""; }
return;
}
const pass = rule.fn(val);
el.classList.toggle("valid", pass);
el.classList.toggle("invalid", !pass);
if (hint) {
hint.className = `field-hint show ${pass ? "ok" : "err"}`;
hint.textContent = pass ? `β ${rule.ok}` : `β ${rule.err}`;
}
});
el.addEventListener("blur", () => {
if (!el.value.trim()) {
el.classList.remove("valid","invalid");
if (hint) { hint.className="field-hint"; hint.textContent=""; }
}
});
});
},
checkAll(ids) {
let valid = true;
ids.forEach(id => {
const el = document.getElementById(id);
const rule = this.rules[id];
if (!el || !rule) return;
if (!el.value.trim() && id !== "r-email" && id !== "r-blood") {
el.classList.add("invalid"); valid = false;
const hint = document.getElementById(`hint-${id}`);
if (hint) { hint.className = "field-hint show err"; hint.textContent = `β This field is required`; }
} else if (el.value.trim() && !rule.fn(el.value)) {
el.classList.add("invalid"); valid = false;
const hint = document.getElementById(`hint-${id}`);
if (hint) { hint.className = "field-hint show err"; hint.textContent = `β ${rule.err}`; }
}
});
return valid;
}
};
function fGroup(id, label, inputHtml, required = false) {
return `
<div class="form-group">
<label class="form-label">${label}${required ? ' <span style="color:var(--red)">*</span>' : ''}</label>
${inputHtml}
<div class="field-hint" id="hint-${id}"></div>
</div>`;
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// LOGIN APP
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const LoginApp = {
role: null,
tab: "login",
init() {
document.body.innerHTML = this.renderRoot();
this.bindRole();
},
renderRoot() {
return `
<div class="login-wrap fade-in">
<div class="login-logo">
<div class="logo-icon">βοΈ</div>
<h1 style="font-size:1.8rem;letter-spacing:-1px">MediFlow</h1>
<p style="margin-top:6px;font-size:0.9rem">Smart Patient Inflow & Triage System</p>
</div>
<div id="login-panel" style="width:100%;max-width:460px"></div>
</div>`;
},
renderRoleSelect() {
const panel = document.getElementById("login-panel");
panel.innerHTML = `
<div class="card slide-up">
<h2 style="margin-bottom:6px">Welcome</h2>
<p style="margin-bottom:24px">Select your role to continue</p>
<button class="role-card" data-role="patient">
<span class="ri">π§ββοΈ</span>
<div><div class="rl">Patient</div><div class="rd">Register or access your records</div></div>
<span style="margin-left:auto;color:var(--muted)">βΊ</span>
</button>
<button class="role-card" data-role="doctor">
<span class="ri">π¨ββοΈ</span>
<div><div class="rl">Doctor</div><div class="rd">View your patient queue</div></div>
<span style="margin-left:auto;color:var(--muted)">βΊ</span>
</button>
<button class="role-card" data-role="admin">
<span class="ri">π‘οΈ</span>
<div><div class="rl">Administrator</div><div class="rd">Manage hospital operations</div></div>
<span style="margin-left:auto;color:var(--muted)">βΊ</span>
</button>
</div>`;
},
bindRole() {
this.renderRoleSelect();
document.getElementById("login-panel").addEventListener("click", e => {
const rc = e.target.closest("[data-role]");
if (rc) { this.role = rc.dataset.role; this.renderForm(); }
});
},
renderForm() {
const panel = document.getElementById("login-panel");
const isAdmin = this.role === "admin";
panel.innerHTML = `
<div class="card slide-up">
<div style="display:flex;align-items:center;gap:10px;margin-bottom:22px">
<button id="back-btn" class="btn btn-ghost btn-sm">β Back</button>
<h2>${this.role.charAt(0).toUpperCase() + this.role.slice(1)} Portal</h2>
</div>
${!isAdmin ? `
<div class="tab-row">
<button class="tab-btn ${this.tab==='login'?'active':'inactive'}" data-tab="login">Sign In</button>
<button class="tab-btn ${this.tab==='register'?'active':'inactive'}" data-tab="register">Register</button>
</div>` : ""}
<div id="form-body"></div>
</div>`;
document.getElementById("back-btn").onclick = () => { this.role = null; this.bindRole(); };
if (!isAdmin) {
panel.querySelectorAll(".tab-btn").forEach(b => b.addEventListener("click", () => {
this.tab = b.dataset.tab;
this.renderForm();
}));
}
this.renderFormBody();
},
renderFormBody() {
const body = document.getElementById("form-body");
const isAdmin = this.role === "admin";
if (isAdmin || this.tab === "login") {
const isPatient = this.role === "patient";
const isDoctor = this.role === "doctor";
body.innerHTML = `
<div class="form-group">
<label class="form-label">
${isAdmin ? "Username" : isPatient ? "Registered Phone Number" : "Doctor ID"}
</label>
<input id="f-id" class="form-input"
type="${isPatient ? "tel" : "text"}"
placeholder="${isAdmin ? "admin" : isPatient ? "e.g. 9876543210" : "e.g. D001"}"
maxlength="${isPatient ? "10" : "20"}">
${isPatient ? `<div style="font-size:0.72rem;color:var(--muted2);margin-top:5px">Use the phone number you registered with</div>` : ""}
</div>
<div class="form-group">
<label class="form-label">Password</label>
<input id="f-pw" class="form-input" type="password" placeholder="Enter your password">
</div>
<div style="background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:10px 14px;margin-bottom:14px;font-size:0.75rem;color:var(--muted2)">
${isAdmin
? `π Demo: <strong style="color:var(--text)">admin</strong> / <strong style="color:var(--text)">admin123</strong>`
: isPatient
? `π Demo phone: <strong style="color:var(--text)">9876543210</strong> / <strong style="color:var(--text)">pass123</strong>`
: `π Demo: <strong style="color:var(--text)">D001</strong> / <strong style="color:var(--text)">doc123</strong>`}
</div>
<div id="f-err"></div>
<button id="f-submit" class="btn btn-primary btn-full">Sign In β</button>`;
document.getElementById("f-submit").onclick = () => this.doLogin();
document.getElementById("f-pw").addEventListener("keydown", e => { if (e.key === "Enter") this.doLogin(); });
} else {
body.innerHTML = this.role === "patient" ? this.patientRegisterForm() : this.doctorRegisterForm();
document.getElementById("f-submit").onclick = () => this.doRegister();
if (this.role === "patient") {
Validate.attachLive(["r-name","r-age","r-phone","r-email","r-pw","r-blood"]);
} else {
Validate.attachLive(["r-name","r-phone","r-email","r-pw"]);
}
}
},
patientRegisterForm() {
return `
<div class="form-grid">
<div class="form-full">
${fGroup("r-name","Full Name",`<input id="r-name" class="form-input" placeholder="e.g. Rahul Verma">`,true)}
</div>
${fGroup("r-age","Age",`<input id="r-age" class="form-input" type="number" min="1" max="120" placeholder="25">`,true)}
<div class="form-group">
<label class="form-label">Gender <span style="color:var(--red)">*</span></label>
<select id="r-gender" class="form-select">
<option>Male</option><option>Female</option><option>Other</option>
</select>
</div>
${fGroup("r-phone","Phone Number (used to log in)",`<input id="r-phone" class="form-input" type="tel" placeholder="9XXXXXXXXX" maxlength="10">`,true)}
${fGroup("r-email","Email (optional)",`<input id="r-email" class="form-input" type="email" placeholder="you@email.com">`)}
${fGroup("r-blood","Blood Group (optional)",`<input id="r-blood" class="form-input" placeholder="A+, B-, AB+, O-">`)}
<div class="form-full">
<div class="form-group">
<label class="form-label">Medical History</label>
<input id="r-history" class="form-input" placeholder="Diabetes, Hypertension, None, etc.">
</div>
</div>
<div class="form-full">
${fGroup("r-pw","Password",`<input id="r-pw" class="form-input" type="password" placeholder="Min 8 chars, letter + number">`,true)}
</div>
</div>
<div style="background:rgba(16,185,129,0.08);border:1px solid rgba(16,185,129,0.25);border-radius:8px;padding:10px 14px;margin-bottom:14px;font-size:0.8rem;color:var(--muted2)">
β
After registering, <strong style="color:var(--green)">log in using your phone number + password</strong>. No ID to remember!
</div>
<div id="f-err"></div>
<button id="f-submit" class="btn btn-primary btn-full">Create Account β</button>`;
},
doctorRegisterForm() {
const specialties = ["Cardiologist","Neurologist","Pulmonologist","Gastroenterologist","Orthopedic Surgeon",
"Urologist","Dermatologist","Endocrinologist","Rheumatologist","Gynecologist","Ophthalmologist",
"Hematologist","Oncologist","ENT Specialist","Nephrologist","Infectious Disease Specialist",
"Allergist","Psychiatrist","Pediatrician","General Surgeon"];
return `
<div class="form-grid">
<div class="form-full">
${fGroup("r-name","Full Name (without Dr.)",`<input id="r-name" class="form-input" placeholder="e.g. Ramesh Kumar">`,true)}
</div>
<div class="form-group">
<label class="form-label">Specialty <span style="color:var(--red)">*</span></label>
<select id="r-spec" class="form-select">
${specialties.map(s => `<option>${s}</option>`).join("")}
</select>
</div>
<div class="form-group">
<label class="form-label">Experience</label>
<input id="r-exp" class="form-input" placeholder="5 years">
</div>
${fGroup("r-phone","Phone (10-digit Indian mobile)",`<input id="r-phone" class="form-input" type="tel" placeholder="9XXXXXXXXX" maxlength="10">`,true)}
${fGroup("r-email","Email (optional)",`<input id="r-email" class="form-input" type="email" placeholder="doc@hospital.com">`)}
<div class="form-full">
${fGroup("r-pw","Password",`<input id="r-pw" class="form-input" type="password" placeholder="Min 8 chars, letter + number">`,true)}
</div>
</div>
<div style="background:rgba(245,158,11,0.08);border:1px solid rgba(245,158,11,0.25);border-radius:8px;padding:10px 14px;margin-bottom:14px;font-size:0.8rem;color:var(--muted2)">
β οΈ After registering, your <strong style="color:var(--yellow)">Doctor ID</strong> (e.g. D006) will be shown on screen. <strong style="color:var(--text)">Note it down</strong> β you'll use it to log in along with your password.
</div>
<div id="f-err"></div>
<button id="f-submit" class="btn btn-primary btn-full">Register as Doctor β</button>`;
},
setError(msg) {
const e = document.getElementById("f-err");
if (e) e.innerHTML = msg ? `<div class="error-msg">${msg}</div>` : "";
},
showRegisteredId(idValue, role, phone) {
const panel = document.getElementById("login-panel");
if (role === "patient") {
// Patient logs in with phone β no ID to show, just redirect with phone pre-filled
panel.innerHTML = `
<div class="card slide-up" style="text-align:center">
<div style="font-size:48px;margin-bottom:14px">π</div>
<h2 style="margin-bottom:8px">Registration Successful!</h2>
<p style="margin-bottom:24px">Your account is ready. Sign in using your phone number and password.</p>
<div style="background:rgba(16,185,129,0.1);border:1px solid rgba(16,185,129,0.3);border-radius:12px;padding:16px 20px;margin-bottom:22px">
<div style="font-size:0.75rem;color:var(--muted2);margin-bottom:6px">LOGIN WITH</div>
<div style="font-size:1.3rem;font-weight:700;color:var(--green);font-family:var(--mono)">${phone}</div>
<div style="font-size:0.75rem;color:var(--muted2);margin-top:4px">+ your password</div>
</div>
<button class="btn btn-primary btn-full" id="go-login-btn">Sign In Now β</button>
</div>`;
document.getElementById("go-login-btn").onclick = () => {
this.tab = "login";
this.renderForm();
setTimeout(() => {
const inp = document.getElementById("f-id");
if (inp) inp.value = phone;
}, 80);
};
} else {
// Doctor MUST note their ID β it's their login credential
panel.innerHTML = `
<div class="card slide-up" style="text-align:center">
<div style="font-size:48px;margin-bottom:14px">π¨ββοΈ</div>
<h2 style="margin-bottom:8px">Doctor Registered!</h2>
<p style="margin-bottom:20px">Your Doctor ID has been assigned. You'll need it every time you log in.</p>
<div class="id-badge" style="margin-bottom:20px">
<div class="id-label">YOUR DOCTOR ID</div>
<div class="id-value">${idValue}</div>
<div class="id-note">β οΈ Write this down β use it with your password to sign in</div>
</div>
<div style="background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:14px 16px;text-align:left;margin-bottom:20px;font-size:0.8rem;color:var(--muted2);line-height:1.7">
π <strong style="color:var(--text)">How to login:</strong> Go to Doctor Portal β Sign In β enter <strong style="color:var(--cyan)">${idValue}</strong> + your password
</div>
<button class="btn btn-primary btn-full" id="go-login-btn">Go to Sign In β</button>
</div>`;
document.getElementById("go-login-btn").onclick = () => {
this.tab = "login";
this.renderForm();
setTimeout(() => {
const inp = document.getElementById("f-id");
if (inp) inp.value = idValue;
}, 80);
};
}
},
async doLogin() {
const btn = document.getElementById("f-submit");
const id = document.getElementById("f-id")?.value.trim();
const pw = document.getElementById("f-pw")?.value.trim();
if (!id || !pw) return this.setError("Please fill all fields.");
setLoading(btn, true, "Signing in...");
try {
const data = await API.login(this.role, id, pw);
Session.save(data.token, this.role, data);
toast("Welcome back, " + data.name + "!");
if (this.role === "patient") PatientApp.init();
else if (this.role === "doctor") DoctorApp.init();
else AdminApp.init();
} catch (e) {
this.setError(e.message);
setLoading(btn, false, "Sign In β");
}
},
async doRegister() {
const btn = document.getElementById("f-submit");
if (this.role === "patient") {
// Validate all fields
const valid = Validate.checkAll(["r-name","r-age","r-phone","r-email","r-pw","r-blood"]);
if (!valid) return this.setError("Please fix the errors highlighted above.");
const name = document.getElementById("r-name").value.trim();
const phone = document.getElementById("r-phone").value.trim();
const pw = document.getElementById("r-pw").value.trim();
setLoading(btn, true, "Creating account...");
try {
const d = {
name, phone, password: pw,
age: document.getElementById("r-age").value,
gender: document.getElementById("r-gender").value,
email: document.getElementById("r-email").value.trim(),
blood_group: document.getElementById("r-blood").value.trim(),
history: document.getElementById("r-history").value.trim(),
};
const res = await API.registerPatient(d);
this.showRegisteredId(res.patient_id, "patient", phone);
} catch (e) {
this.setError(e.message);
setLoading(btn, false, "Create Account β");
}
} else {
const valid = Validate.checkAll(["r-name","r-phone","r-email","r-pw"]);
if (!valid) return this.setError("Please fix the errors highlighted above.");
const name = document.getElementById("r-name").value.trim();
const phone = document.getElementById("r-phone").value.trim();
const pw = document.getElementById("r-pw").value.trim();
setLoading(btn, true, "Registering...");
try {
const d = {
name: "Dr. " + name, phone, password: pw,
specialty: document.getElementById("r-spec").value,
experience: document.getElementById("r-exp").value.trim(),
email: document.getElementById("r-email").value.trim(),
};
const res = await API.registerDoctor(d);
this.showRegisteredId(res.doctor_id, "doctor");
} catch (e) {
this.setError(e.message);
setLoading(btn, false, "Register as Doctor β");
}
}
}
};
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// PATIENT APP
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const PatientApp = {
page: "home",
user: null,
triage: null,
assignment: null,
triageResult: null,
chat: [],
followQIdx: 0,
predictedTriage: null,
async init() {
this.user = Session.user();
document.body.innerHTML = this.renderLayout();
this.bindNav();
try {
const data = await API.patientMe();
this.user = data.patient;
this.triage = data.triage;
this.assignment = data.assignment;
} catch(e) {}
this.navigate("home");
},
renderLayout() {
const u = Session.user();
return `
<div class="layout">
<aside class="sidebar">
<div class="sidebar-logo">
<div class="icon">βοΈ</div>
<div><div class="title">MediFlow</div><div class="sub">Patient Portal</div></div>
</div>
<button class="nav-btn active" data-page="home"> <span class="icon">π </span> Dashboard</button>
<button class="nav-btn" data-page="triage"><span class="icon">π©Ί</span> Symptom Check</button>
<button class="nav-btn" data-page="status"><span class="icon">π</span> My Status</button>
<div class="sidebar-footer">
<div class="sidebar-user">
<div class="name">${u.name || "Patient"}</div>
<div class="sub">ID: ${u.id || ""}</div>
</div>
<button id="logout-btn" class="btn btn-ghost btn-full btn-sm">Sign Out</button>
</div>
</aside>
<main class="main" id="main-content"></main>
</div>`;
},
bindNav() {
document.querySelectorAll(".nav-btn[data-page]").forEach(b =>
b.addEventListener("click", () => this.navigate(b.dataset.page)));
document.getElementById("logout-btn")?.addEventListener("click", async () => {
await API.logout().catch(() => {});
Session.clear();
LoginApp.init();
});
},
navigate(page) {
this.page = page;
document.querySelectorAll(".nav-btn[data-page]").forEach(b =>
b.classList.toggle("active", b.dataset.page === page));
const main = document.getElementById("main-content");
if (page === "home") {
// Always reload from DB when going to dashboard
API.patientMe().then(data => {
this.user = data.patient;
this.triage = data.triage;
this.assignment = data.assignment;
main.innerHTML = this.renderHome();
animateBars(main);
}).catch(() => {
main.innerHTML = this.renderHome();
animateBars(main);
});
return;
}
if (page === "triage") { main.innerHTML = this.renderTriagePage(); this.bindTriage(); }
if (page === "status") {
API.patientMe().then(data => {
this.user = data.patient;
this.triage = data.triage;
this.assignment = data.assignment;
main.innerHTML = this.renderStatus();
animateBars(main);
}).catch(() => {
main.innerHTML = this.renderStatus();
animateBars(main);
});
return;
}
animateBars(main);
},
renderHome() {
const u = this.user;
const hasActive = this.triage && this.assignment;
const sev = this.triage?.severity || 0;
return `
<div class="fade-in">
<div class="page-header">
<h1>Hello, ${u?.name?.split(" ")[0] || "Patient"} π</h1>
<p>Welcome to your health dashboard</p>
</div>
<div class="card-grid-3" style="margin-bottom:28px">
<div class="stat-card"><div class="icon">π©Έ</div><div class="val" style="color:var(--red);font-size:1.3rem">${u?.blood_group || "β"}</div><div class="lbl">Blood Group</div></div>
<div class="stat-card"><div class="icon">π
</div><div class="val" style="color:var(--accent)">${u?.age || "β"}</div><div class="lbl">Age</div></div>
<div class="stat-card"><div class="icon">π</div><div class="val" style="color:var(--green);font-size:1rem">${u?.phone || "β"}</div><div class="lbl">Phone</div></div>
<div class="stat-card"><div class="icon">π₯</div><div class="val" style="color:var(--purple);font-size:0.95rem;margin-top:4px">${u?.history || "None"}</div><div class="lbl">Medical History</div></div>
</div>
${hasActive ? `
<div class="card glow-${sev>=8?'red':sev>=6?'yellow':'blue'}">
<h3 style="margin-bottom:14px">π Active Triage</h3>
${SeverityBar(sev)}
<div class="meta-row" style="margin-top:16px">
<div class="meta-item"><div class="key">Doctor</div><div class="val">${this.assignment.doc_name || "Assigned"}</div></div>
<div class="meta-item"><div class="key">Specialty</div><div class="val">${this.triage.specialty}</div></div>
<div class="meta-item"><div class="key">Disease</div><div class="val">${this.triage.disease}</div></div>
</div>
<div class="meta-row" style="margin-top:12px">
<div class="meta-item"><div class="key">Status</div>${Badge(this.assignment.status, statusBadgeClass(this.assignment.status))}</div>
<div class="meta-item"><div class="key">Priority Score</div><div class="val" style="color:var(--cyan);font-family:var(--mono)">${Number(this.triage.priority_score).toFixed(0)}</div></div>
</div>
</div>` : `
<div class="card" style="text-align:center;padding:48px 24px">
<div style="font-size:44px;margin-bottom:14px">π©Ί</div>
<h3 style="margin-bottom:8px">No Active Triage</h3>
<p style="margin-bottom:22px">Describe your symptoms to get matched with the right doctor</p>
<button class="btn btn-primary" onclick="PatientApp.navigate('triage')">Start Symptom Check β</button>
</div>`}
</div>`;
},
renderTriagePage() {
return `
<div class="fade-in" style="max-width:660px;margin:0 auto">
<div class="page-header">
<h1>Symptom Assessment</h1>
<p>Our AI model will analyze your symptoms and match you with the right specialist</p>
</div>
<div id="triage-step-1">
<div class="card">
<div class="form-group">
<label class="form-label">Describe your symptoms in detail *</label>
<textarea id="symptom-input" class="form-textarea" rows="5"
placeholder="e.g. chest pain, shortness of breath, sweating since this morning..."></textarea>
<div style="font-size:0.75rem;color:var(--muted2);margin-top:6px">
Use medical terms: fever, cough, breathlessness, chest pain, joint pain, nausea, etc.
</div>
</div>
<div id="symptom-error" style="display:none;background:rgba(239,68,68,0.1);border:1px solid rgba(239,68,68,0.25);border-radius:10px;padding:14px 16px;margin-bottom:14px;font-size:0.85rem;color:#fca5a5;line-height:1.7"></div>
<button id="analyze-btn" class="btn btn-primary btn-full">Analyze Symptoms β</button>
</div>
</div>
<div id="triage-step-2" style="display:none">
<div class="card">
<h3 style="margin-bottom:6px">π€ AI Triage Chat</h3>
<p style="margin-bottom:16px;font-size:0.82rem">Answer the questions below for a more accurate assessment</p>
<div class="chat-window" id="chat-window"></div>
<div class="chat-input-row">
<input id="chat-input" class="form-input" placeholder="Type your response...">
<button id="chat-send" class="btn btn-primary">Send</button>
</div>
</div>
</div>
<div id="triage-step-3" style="display:none">
<div id="triage-result-content"></div>
</div>
</div>`;
},
bindTriage() {
document.getElementById("analyze-btn")?.addEventListener("click", () => this.doAnalyze());
document.getElementById("symptom-input")?.addEventListener("keydown", e => {
if (e.ctrlKey && e.key === "Enter") this.doAnalyze();
});
},
showSymptomError(msg) {
const box = document.getElementById("symptom-error");
if (box) {
box.innerHTML = msg.replace(/\n/g, "<br>");
box.style.display = "";
}
},
clearSymptomError() {
const box = document.getElementById("symptom-error");
if (box) { box.innerHTML = ""; box.style.display = "none"; }
},
async doAnalyze() {
const btn = document.getElementById("analyze-btn");
const txt = document.getElementById("symptom-input")?.value.trim();
if (!txt) return toast("Please describe your symptoms first.", "error");
this.clearSymptomError();
// Frontend gibberish guard: must have at least some real alphabetic words
const alpha = txt.replace(/[^a-zA-Z ]/g, " ").trim();
const realWords = alpha.split(/\s+/).filter(w => w.length >= 2);
if (realWords.length === 0) {
return this.showSymptomError("Please describe your symptoms in English words (e.g. \"chest pain and breathlessness\").");
}
setLoading(btn, true, "Analyzing...");
try {
const result = await API.triagePredict(txt);
// Engine found no matching symptoms from the dataset
if (result.unknown) {
setLoading(btn, false, "Analyze Symptoms \u2192");
return this.showSymptomError(
`We couldn\'t identify any recognizable symptoms in your input.\n\nPlease describe your symptoms clearly using terms like:\n\u2022 chest pain, breathlessness, sweating\n\u2022 fever, cough, sputum, wheezing\n\u2022 nausea, vomiting, abdominal pain\n\u2022 joint pain, swelling, stiffness\n\u2022 headache, dizziness, blurred vision\n\nRandom letters or words not related to medical symptoms will not be processed.`
);
}
this.predictedTriage = result;
this._symptoms = txt;
this.chat = [];
this.followQIdx = 0;
setLoading(btn, false, "Analyze Symptoms \u2192");
document.getElementById("triage-step-1").style.display = "none";
document.getElementById("triage-step-2").style.display = "";
const questions = FOLLOWUP[result.specialty] ||
["How long have you had these symptoms?", "Any fever or nausea?", "Any known medical conditions?"];
this._questions = questions;
const detectedHtml = result.matched_symptoms?.length
? `<br><span style="font-size:0.75rem;color:var(--muted2);margin-top:4px;display:block">Detected: ${result.matched_symptoms.join(", ")}</span>`
: "";
this.addMsg("ai", `Symptoms analyzed. You may need a <strong>${result.specialty}</strong> (${result.specialty_conf}% confidence).${detectedHtml}<br>Let me ask a few follow-up questions.`);
await this.sleep(600);
this.addMsg("ai", questions[0]);
this.followQIdx = 1;
document.getElementById("chat-send")?.addEventListener("click", () => this.sendChat());
document.getElementById("chat-input")?.addEventListener("keydown", e => { if (e.key==="Enter") this.sendChat(); });
} catch(e) {
toast(e.message, "error");
setLoading(btn, false, "Analyze Symptoms \u2192");
}
},
sleep: ms => new Promise(r => setTimeout(r, ms)),
addMsg(from, text) {
const win = document.getElementById("chat-window");
if (!win) return;
const isAI = from === "ai";
const div = document.createElement("div");
div.className = `chat-msg ${from} slide-up`;
div.innerHTML = isAI
? `<div class="chat-avatar">β</div><div class="chat-bubble">${text}</div>`
: `<div class="chat-bubble">${text}</div>`;
win.appendChild(div);
win.scrollTop = win.scrollHeight;
this.chat.push({ from, text: text.replace(/<[^>]+>/g, "") });
},
async sendChat() {
const inp = document.getElementById("chat-input");
const msg = inp?.value.trim();
if (!msg) return;
inp.value = "";
this.addMsg("user", msg);
if (this.followQIdx < this._questions.length) {
await this.sleep(400);
this.addMsg("ai", this._questions[this.followQIdx]);
this.followQIdx++;
} else {
document.getElementById("chat-input").disabled = true;
document.getElementById("chat-send").disabled = true;
const typing = document.createElement("div");
typing.className = "chat-msg ai";
typing.innerHTML = `<div class="chat-avatar">β</div><div class="chat-bubble"><span style="animation:pulse 1s infinite;color:var(--muted2)">β β β</span></div>`;
document.getElementById("chat-window").appendChild(typing);
await this.sleep(900);
typing.remove();
this.addMsg("ai", "Thank you! I have all the information I need. Finalizing your triage report now...");
await this.sleep(700);
await this.submitTriage();
}
},
async submitTriage() {
try {
const result = await API.triageSubmit(this._symptoms, this.chat);
this.triageResult = result;
// ββ Save into PatientApp state so dashboard + status update instantly ββ
this.triage = {
id: result.triage_id,
patient_id: Session.user().id,
symptoms: this._symptoms,
disease: result.disease,
specialty: result.specialty,
severity: result.severity,
severity_label: result.severity_label,
priority_score: result.priority_score,
status: result.status,
created_at: new Date().toISOString(),
};
this.assignment = {
id: result.assignment_id,
triage_id: result.triage_id,
status: result.status,
doc_name: result.assigned_doctor.name,
specialty: result.assigned_doctor.specialty,
assigned_at: new Date().toISOString(),
};
document.getElementById("triage-step-2").style.display = "none";
document.getElementById("triage-step-3").style.display = "";
this.renderTriageResult(result);
} catch(e) {
if (e.message === "UNKNOWN_SYMPTOMS") {
document.getElementById("triage-step-2").style.display = "none";
document.getElementById("triage-step-1").style.display = "";
this.showSymptomError("We could not identify medical symptoms from your input. Please re-describe using recognized symptom terms.");
} else {
toast(e.message, "error");
}
}
},
renderTriageResult(r) {
const sevColor = severityColor(r.severity);
const doc = r.assigned_doctor;
document.getElementById("triage-result-content").innerHTML = `
<div class="slide-up">
<div class="card glow-${r.severity>=8?'red':r.severity>=6?'yellow':'blue'}" style="margin-bottom:16px">
<div style="display:flex;align-items:center;gap:8px;margin-bottom:16px">
<span style="font-size:22px">β
</span>
<h3>Triage Complete</h3>
<span class="confidence-chip">π§ ${r.specialty_conf}% confidence</span>
</div>
${SeverityBar(r.severity)}
<div class="meta-row" style="margin-top:16px">
<div class="meta-item"><div class="key">Predicted Disease</div><div class="val">${r.disease}</div></div>
<div class="meta-item"><div class="key">Specialty Needed</div><div class="val">${r.specialty}</div></div>
<div class="meta-item"><div class="key">Priority Score</div><div class="val" style="color:var(--cyan);font-family:var(--mono)">${Number(r.priority_score).toFixed(0)}</div></div>
</div>
<div class="meta-row" style="margin-top:12px">
<div class="meta-item"><div class="key">Status</div>${Badge(r.status || "Waiting", statusBadgeClass(r.status || "Waiting"))}</div>
<div class="meta-item"><div class="key">Est. Wait</div><div class="val">${r.estimated_wait} mins</div></div>
<div class="meta-item"><div class="key">Triage ID</div><div class="val" style="font-family:var(--mono)">${r.triage_id}</div></div>
</div>
</div>
<div class="card glow-green" style="margin-bottom:16px">
<h3 style="margin-bottom:14px">π¨ββοΈ Assigned Doctor</h3>
<div style="display:flex;align-items:center;gap:14px">
<div class="avatar" style="background:rgba(16,185,129,0.15);font-size:22px">π¨ββοΈ</div>
<div style="flex:1">
<div style="font-weight:700;font-size:1rem">${doc.name}</div>
<div style="font-size:0.82rem;color:var(--muted2)">${doc.specialty} β’ ${doc.experience}</div>
</div>
${Badge("Available", "badge-green")}
</div>
</div>
<div class="card" style="margin-bottom:16px">
<h3 style="margin-bottom:12px">π¬ Alternative Possibilities</h3>
${r.alternatives.map(a => `
<div style="display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid var(--border);font-size:0.875rem">
<span>${a.specialty}</span>
<div style="display:flex;align-items:center;gap:8px">
<div style="width:80px;background:var(--border);border-radius:4px;height:5px">
<div style="width:${a.confidence}%;background:var(--accent);border-radius:4px;height:100%"></div>
</div>
<span style="font-family:var(--mono);font-size:0.78rem;color:var(--cyan)">${a.confidence}%</span>
</div>
</div>`).join("")}
</div>
<button class="btn btn-primary btn-full" onclick="PatientApp.refreshAndGoHome()">Back to Dashboard β</button>
</div>`;
animateBars(document.getElementById("triage-result-content"));
},
async refreshAndGoHome() {
// Re-fetch from localStorage DB so dashboard is always up to date
try {
const data = await API.patientMe();
this.user = data.patient;
this.triage = data.triage;
this.assignment = data.assignment;
} catch(e) {}
this.navigate("home");
},
renderStatus() {
if (!this.triage) return `
<div class="fade-in">
<div class="page-header"><h1>My Status</h1></div>
<div class="empty-state card"><div class="ei">π</div><h3>No Active Case</h3><p>Start a symptom check to get triaged</p><br><button class="btn btn-primary" onclick="PatientApp.navigate('triage')">Check Symptoms β</button></div>
</div>`;
const sev = this.triage.severity;
return `
<div class="fade-in">
<div class="page-header"><h1>My Status</h1><p>Your current triage details</p></div>
<div class="card glow-${sev>=8?'red':sev>=6?'yellow':'blue'}" style="margin-bottom:16px">
<h3 style="margin-bottom:14px">Triage Summary</h3>
${SeverityBar(sev)}
<div class="meta-row" style="margin-top:16px">
<div class="meta-item"><div class="key">Disease</div><div class="val">${this.triage.disease}</div></div>
<div class="meta-item"><div class="key">Specialty</div><div class="val">${this.triage.specialty}</div></div>
<div class="meta-item"><div class="key">Triage ID</div><div class="val" style="font-family:var(--mono)">${this.triage.id}</div></div>
</div>
<div class="meta-row" style="margin-top:12px">
<div class="meta-item"><div class="key">Status</div>${Badge(this.triage.status, statusBadgeClass(this.triage.status))}</div>
<div class="meta-item"><div class="key">Priority Score</div><div class="val" style="color:var(--cyan);font-family:var(--mono)">${Number(this.triage.priority_score).toFixed(0)}</div></div>
<div class="meta-item"><div class="key">Since</div><div class="val">${new Date(this.triage.created_at).toLocaleTimeString()}</div></div>
</div>
</div>
${this.assignment ? `
<div class="card glow-green">
<h3 style="margin-bottom:14px">Doctor Assignment</h3>
<div style="display:flex;align-items:center;gap:14px">
<div class="avatar" style="background:rgba(16,185,129,0.15)">π¨ββοΈ</div>
<div><div style="font-weight:700">${this.assignment.doc_name}</div><div style="color:var(--muted2);font-size:0.82rem">${this.assignment.specialty}</div></div>
</div>
</div>` : ""}
</div>`;
}
};
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// DOCTOR APP
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const DoctorApp = {
page: "queue",
user: null,
queue: [],
async init() {
this.user = Session.user();
document.body.innerHTML = this.renderLayout();
this.bindNav();
this.navigate("queue");
try {
const d = await API.doctorMe();
this.user = d.doctor;
const q = await API.doctorQueue();
this.queue = q.queue;
this.navigate("queue");
} catch(e) {}
},
renderLayout() {
const u = Session.user();
return `
<div class="layout">
<aside class="sidebar">
<div class="sidebar-logo">
<div class="icon">βοΈ</div>
<div><div class="title">MediFlow</div><div class="sub">Doctor Portal</div></div>
</div>
<button class="nav-btn active green" data-page="queue"> <span class="icon">π</span> Patient Queue</button>
<button class="nav-btn" data-page="profile"><span class="icon">π€</span> My Profile</button>
<div class="sidebar-footer">
<div class="sidebar-user">
<div class="name">${u.name || "Doctor"}</div>
<div class="sub">${u.specialty || ""}</div>
</div>
<button id="logout-btn" class="btn btn-ghost btn-full btn-sm">Sign Out</button>
</div>
</aside>
<main class="main" id="main-content"></main>
</div>`;
},
bindNav() {
document.querySelectorAll(".nav-btn[data-page]").forEach(b =>
b.addEventListener("click", () => this.navigate(b.dataset.page)));
document.getElementById("logout-btn")?.addEventListener("click", async () => {
await API.logout().catch(() => {});
Session.clear(); LoginApp.init();
});
},
navigate(page) {
this.page = page;
document.querySelectorAll(".nav-btn[data-page]").forEach(b => {
b.classList.remove("active");
if (b.dataset.page === page) b.classList.add("active", "green");
});
const main = document.getElementById("main-content");
if (page === "queue") { main.innerHTML = this.renderQueue(); animateBars(main); }
if (page === "profile") main.innerHTML = this.renderProfile();
},
renderQueue() {
const q = this.queue;
return `
<div class="fade-in">
<div class="page-header">
<h1>Patient Queue</h1>
<p>Sorted by AI triage priority score (highest first)</p>
</div>
<div class="card-grid-3" style="margin-bottom:24px">
<div class="stat-card"><div class="icon">π₯</div><div class="val" style="color:var(--accent)">${q.length}</div><div class="lbl">Total Assigned</div></div>
<div class="stat-card"><div class="icon">π¨</div><div class="val" style="color:var(--red)">${q.filter(x=>x.severity>=8).length}</div><div class="lbl">Critical</div></div>
<div class="stat-card"><div class="icon">β³</div><div class="val" style="color:var(--yellow)">${q.filter(x=>x.status==="Waiting").length}</div><div class="lbl">Waiting</div></div>
<div class="stat-card"><div class="icon">β
</div><div class="val" style="color:var(--green)">${q.filter(x=>x.status==="In Progress").length}</div><div class="lbl">In Progress</div></div>
</div>
${q.length === 0 ? `<div class="empty-state card"><div class="ei">π</div><h3>No Patients Assigned</h3><p>You're all caught up!</p></div>` :
q.map((p, i) => this.renderQueueItem(p, i)).join("")}
</div>`;
},
renderQueueItem(p, i) {
const sev = p.severity;
const color = severityColor(sev);
const canStart = p.status === "Waiting" || p.status === "Immediate";
const canComplete = p.status === "In Progress" || p.status === "Waiting" || p.status === "Immediate";
return `
<div class="queue-item" style="border-left-color:${color}" data-assign-id="${p.assign_id}">
<div style="display:flex;align-items:center;gap:12px;margin-bottom:10px;flex-wrap:wrap">
<div class="queue-rank" style="background:${color}22;color:${color}">#${i+1}</div>
<div style="flex:1">
<div style="font-weight:700;font-size:0.95rem">${p.name}</div>
<div style="font-size:0.78rem;color:var(--muted2)">${p.age}y β’ ${p.gender} β’ ${p.blood_group}</div>
</div>
<div style="display:flex;gap:6px;flex-wrap:wrap">
${Badge(p.severity_label || severityLabel(sev), severityBadgeClass(sev))}
${Badge(p.status, statusBadgeClass(p.status))}
</div>
</div>
<div class="symptoms-box"><strong style="color:var(--muted2);font-size:0.75rem">SYMPTOMS:</strong> ${p.symptoms}</div>
<div style="font-size:0.82rem;color:var(--muted2);margin-bottom:8px"><strong>Predicted:</strong> ${p.disease} β ${p.specialty}</div>
${SeverityBar(sev)}
<div class="meta-row" style="margin-top:12px">
<div class="meta-item"><div class="key">Priority Score</div><div class="val" style="color:var(--cyan);font-family:var(--mono)">${Number(p.priority_score).toFixed(0)}</div></div>
<div class="meta-item"><div class="key">History</div><div class="val">${p.history}</div></div>
<div class="meta-item"><div class="key">Admitted</div><div class="val">${new Date(p.triage_time).toLocaleTimeString()}</div></div>
</div>
<div style="display:flex;gap:10px;margin-top:14px;padding-top:12px;border-top:1px solid var(--border)">
${canStart ? `<button class="btn btn-primary btn-sm queue-action-btn" data-id="${p.assign_id}" data-status="In Progress" style="flex:1">βΆ Start Consultation</button>` : ""}
${canComplete ? `<button class="btn btn-sm queue-action-btn" data-id="${p.assign_id}" data-status="Completed" style="flex:1;background:rgba(16,185,129,0.15);color:var(--green);border:1px solid rgba(16,185,129,0.3)">β Mark Complete</button>` : ""}
</div>
</div>`;
},
bindQueueActions(container = document) {
container.querySelectorAll(".queue-action-btn").forEach(btn => {
btn.addEventListener("click", async () => {
const id = btn.dataset.id;
const status = btn.dataset.status;
btn.disabled = true;
btn.textContent = "Updating...";
try {
await API.updateAssignment(id, status, "");
toast(status === "Completed" ? "Patient marked as Completed and removed from queue." : "Consultation started!", "success");
// Reload the queue
this.navigate("queue");
} catch(e) {
toast("Failed to update status.", "error");
btn.disabled = false;
}
});
});