Repository navigation
Expand file tree
/
Copy pathscripts.js
More file actions
3325 lines (2935 loc) · 128 KB
/
Copy pathscripts.js
File metadata and controls
3325 lines (2935 loc) · 128 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
// ── GLOBAL GOOGLE AUTH & APP VARIABLES ──
var googleAccessToken = null;
var googleTokenExpiry = null;
var tokenClient = null;
var autoLockTimer = null;
var lastActivityTime = Date.now();
var currentRxZoom = 1.0;
var externalDrugs = [];
// ── STATE ──
let state = {
loggedIn: false,
loginMethod: 'local', // 'google' or 'local'
securityPin: '',
autoLockMinutes: 0, // Lock disabled
theme: 'light', // 'light' or 'dark'
user: { name: 'Dr. Someone', email: '', initials: 'DS' },
profile: {
name: 'Dr. Someone',
qualifications: 'MBBS (DU)',
designation: 'General Practitioner / Specialist',
hospital: 'Medical College & Hospital',
reg: '',
phone: '+880 1700-000000',
address: 'Chamber: House 12, Road 5, Dhaka',
hours: '4:00 PM - 9:00 PM (Closed on Friday)',
footer: 'নিয়ম মাফিক ঔষধ খাবেন। ডাক্তারের পরামর্শ ব্যতীত ঔষধ পরিবর্তন নিষেধ।',
chamberName: '',
chamberPhone: '+880 1800-000000',
chamberAddr1: 'Dhanmondi, Dhaka',
chamberAddr2: 'Room 302, 3rd Floor',
chamberHours: '5 PM - 9 PM',
chamberNote: 'Serial by phone'
},
padSettings: {
align: 'center',
leftWidth: 165,
color: '#1a3a5c',
showHistory: true,
showFindings: true,
showInvestigation: true,
showAdvice: true,
showFollowup: true,
showSignature: true, // Toggle Doctor's Signature block on prescription
showGenericNames: false, // Default: Brand Name shown, Generic Name togglable
useClinicalPrefix: true, // e.g. "Tab. Napa" instead of "Tablet Napa"
margins: { top: 13, bottom: 14, left: 14, right: 14 },
signature: null
},
patients: [],
prescriptions: [],
customDrugs: [],
tombstones: {
patients: {},
prescriptions: {},
customDrugs: {}
},
currentRx: null,
editingPatientId: null
};
// ── CLINICAL MEDICINE TYPES / FORMS ──
const MEDICINE_FORMS = [
{ label: 'Tab. (Tablet)', value: 'Tab.', full: 'Tablet' },
{ label: 'Cap. (Capsule)', value: 'Cap.', full: 'Capsule' },
{ label: 'Syr. (Syrup)', value: 'Syr.', full: 'Syrup' },
{ label: 'Susp. (Suspension)', value: 'Susp.', full: 'Suspension' },
{ label: 'Inj. (Injection)', value: 'Inj.', full: 'Injection' },
{ label: 'IV Infu. (IV Infusion)', value: 'IV Infu.', full: 'IV Infusion' },
{ label: 'Gtt. (Eye/Ear Drops)', value: 'Gtt.', full: 'Drops' },
{ label: 'Oint. (Ointment)', value: 'Oint.', full: 'Ointment' },
{ label: 'Cream', value: 'Cream', full: 'Cream' },
{ label: 'Gel', value: 'Gel', full: 'Gel' },
{ label: 'Supp. (Suppository)', value: 'Supp.', full: 'Suppository' },
{ label: 'Inh. (Inhaler/Rotacap)', value: 'Inh.', full: 'Inhaler' },
{ label: 'Spray (Nasal/Oral Spray)', value: 'Spray', full: 'Spray' },
{ label: 'Sachet (Powder / Sachet)', value: 'Sachet', full: 'Sachet' },
{ label: 'Sol. (Solution)', value: 'Sol.', full: 'Solution' },
{ label: 'Lotion', value: 'Lotion', full: 'Lotion' },
{ label: 'Mouth W. (Mouthwash/Gargle)', value: 'Mouth W.', full: 'Mouthwash' }
];
// Route of administration presets (auto-suggested from the medicine form, bilingual English [বাংলা]).
const ROUTES = [
'Oral [মুখে]',
'IM/IV [মাংসপেশীতে বা শিরায়]',
'IV [শিরায়]',
'IM [মাংসপেশীতে]',
'SC [ত্বকের নিচে]',
'Topical [ত্বকে ব্যবহার্য]',
'Inhalation [নিঃশ্বাসের সাথে]',
'Ophthalmic/Otic [চোখে/কানে]',
'Eye Drop [চোখে]',
'Ear Drop [কানে]',
'Nasal [নাকে]',
'Rectal [মলদ্বারে]',
'Sublingual [জিহ্বার নিচে]',
'Oral Rinse [কুলকুচা/গার্গল]',
'Vaginal [যোনিপথে]'
];
const ROUTE_BY_FORM = {
'Tab.': 'Oral [মুখে]',
'Cap.': 'Oral [মুখে]',
'Syr.': 'Oral [মুখে]',
'Susp.': 'Oral [মুখে]',
'Sachet': 'Oral [মুখে]',
'Sol.': 'Oral [মুখে]',
'Gtt.': 'Ophthalmic/Otic [চোখে/কানে]',
'Oint.': 'Topical [ত্বকে ব্যবহার্য]',
'Cream': 'Topical [ত্বকে ব্যবহার্য]',
'Gel': 'Topical [ত্বকে ব্যবহার্য]',
'Lotion': 'Topical [ত্বকে ব্যবহার্য]',
'Inh.': 'Inhalation [নিঃশ্বাসের সাথে]',
'Spray': 'Nasal [নাকে]',
'Supp.': 'Rectal [মলদ্বারে]',
'Inj.': 'IM/IV [মাংসপেশীতে বা শিরায়]',
'IV Infu.': 'IV [শিরায়]',
'Mouth W.': 'Oral Rinse [কুলকুচা/গার্গল]'
};
function formatRoute(route) {
if (!route) return '';
const r = String(route).trim();
const map = {
'Oral': 'Oral [মুখে]',
'IM/IV': 'IM/IV [মাংসপেশীতে বা শিরায়]',
'IV': 'IV [শিরায়]',
'IM': 'IM [মাংসপেশীতে]',
'SC': 'SC [ত্বকের নিচে]',
'Topical': 'Topical [ত্বকে ব্যবহার্য]',
'Inhalation': 'Inhalation [নিঃশ্বাসের সাথে]',
'Ophthalmic/Otic': 'Ophthalmic/Otic [চোখে/কানে]',
'Ophthalmic': 'Ophthalmic [চোখে]',
'Otic': 'Otic [কানে]',
'Nasal': 'Nasal [নাকে]',
'Rectal': 'Rectal [মলদ্বারে]',
'Sublingual': 'Sublingual [জিহ্বার নিচে]',
'Oral Rinse': 'Oral Rinse [কুলকুচা/গার্গল]',
'Vaginal': 'Vaginal [যোনিপথে]'
};
return map[r] || r;
}
function formatClinicalBulletLines(text) {
if (!text) return '';
const lines = String(text)
.split(/\r?\n/)
.map(line => line.trim())
.filter(Boolean);
if (lines.length === 0) return '';
return lines.map(line => {
if (/^[-–—•*]\s*/.test(line)) {
return `- ${line.replace(/^[-–—•*]\s*/, '')}`;
}
return `- ${line}`;
}).join('\n');
}
// Dosing-frequency and duration presets (Bengali First, then English)
const FREQ_PRESETS_BN = ['১+০+১', '১+১+১', '১+০+০', '০+০+১', '২+০+২', '১+১+০', '০+১+১', 'প্রয়োজনে (SOS)'];
const FREQ_PRESETS_EN = ['1+0+1', '1+1+1', '1+0+0', '0+0+1', '2+0+2', 'SOS'];
const DURATION_PRESETS_BN = ['৩ দিন', '৫ দিন', '৭ দিন', '১০ দিন', '১৪ দিন', '১ মাস', 'চলবে'];
const DURATION_PRESETS_EN = ['3 days', '5 days', '7 days', '10 days', '14 days', '1 month', 'Continue'];
function formatFrequency(freq) {
if (!freq) return '';
let str = String(freq).trim();
return str.replace(/([0-9১-৯০]+)\s*[-]\s*([0-9১-৯০]+)/g, '$1+$2')
.replace(/([0-9১-৯০]+)\s*[-]\s*([0-9১-৯০]+)/g, '$1+$2');
}
function formatDuration(dur) {
if (!dur) return '';
let str = String(dur).trim();
if (!str) return '';
if (str.startsWith('(') && str.endsWith(')')) return str;
return `(${str})`;
}
// Common clinical phrases for one-tap entry into the clinical notes.
const CLINICAL_PRESETS = {
'rx-complaints': ['Fever', 'Cough', 'Headache', 'Sore throat', 'Runny nose', 'Body ache', 'Abdominal pain', 'Vomiting', 'Diarrhoea', 'Shortness of breath', 'Chest pain', 'Dizziness', 'Generalized weakness', 'Insomnia', 'Loss of appetite'],
'rx-history': ['No HTN', 'No DM', 'Non-smoker', 'Non-alcoholic', 'Known asthmatic', 'Known IHD', 'Known CKD', 'Previous surgery', 'Family history of DM'],
'rx-findings': ['BP: / mmHg', 'Temp: °F', 'Pulse: /min', 'Chest: Clear', 'Abdomen: Soft, non-tender', 'No pedal edema', 'Conscious, oriented', 'Anaemia: present'],
'rx-investigation': ['CBC with ESR', 'RBS', 'Serum creatinine', 'Lipid profile', 'Chest X-Ray (P/A view)', 'ECG', 'USG whole abdomen', 'Urine R/E'],
'rx-diagnosis': ['Acute URTI', 'Acute Gastroenteritis', 'Type 2 Diabetes Mellitus', 'Hypertension', 'Bronchial Asthma', 'Iron deficiency anaemia', 'URTI with Bronchitis', 'Peptic ulcer disease'],
'rx-plan': ['Scaling & Polishing', 'Root Canal Treatment (RCT)', 'Restoration / Filling', 'Tooth Extraction', 'Crown & Bridge Work', 'Operculectomy', 'Re-evaluation after 7 days', 'Refer to specialist']
};
// ── BUILT-IN FALLBACK DRUG DATABASE ──
const DRUGS = [
{ name: 'Napa', generic: 'Paracetamol', dose: '500mg', form: 'Tab.', company: 'Beximco Pharma', price: '৳1.50/tab' },
{ name: 'Napa Extra', generic: 'Paracetamol + Caffeine', dose: '500mg+65mg', form: 'Tab.', company: 'Beximco Pharma', price: '৳2.00/tab' },
{ name: 'Napa Extend', generic: 'Paracetamol (Extended Release)', dose: '665mg', form: 'Tab.', company: 'Beximco Pharma', price: '৳2.50/tab' },
{ name: 'Ace', generic: 'Paracetamol', dose: '500mg', form: 'Tab.', company: 'Square Pharma', price: '৳1.50/tab' },
{ name: 'Ace Plus', generic: 'Paracetamol + Caffeine', dose: '500mg+65mg', form: 'Tab.', company: 'Square Pharma', price: '৳2.00/tab' },
{ name: 'Renova', generic: 'Paracetamol', dose: '500mg', form: 'Tab.', company: 'Renata Ltd', price: '৳1.50/tab' },
{ name: 'Fast', generic: 'Paracetamol', dose: '500mg', form: 'Tab.', company: 'ACI Pharma', price: '৳1.50/tab' },
{ name: 'Seclo', generic: 'Omeprazole', dose: '20mg', form: 'Cap.', company: 'Square Pharma', price: '৳5.00/cap' },
{ name: 'Losectil', generic: 'Omeprazole', dose: '20mg', form: 'Cap.', company: 'Beximco Pharma', price: '৳5.00/cap' },
{ name: 'Sergel', generic: 'Esomeprazole', dose: '20mg', form: 'Cap.', company: 'Healthcare Pharma', price: '৳7.00/cap' },
{ name: 'Maxpro', generic: 'Esomeprazole', dose: '20mg', form: 'Cap.', company: 'Renata Ltd', price: '৳7.00/cap' },
{ name: 'Pantop', generic: 'Pantoprazole', dose: '20mg', form: 'Tab.', company: 'Square Pharma', price: '৳7.00/tab' },
{ name: 'Neopan', generic: 'Pantoprazole', dose: '40mg', form: 'Tab.', company: 'Beximco Pharma', price: '৳7.00/tab' },
{ name: 'Rabeca', generic: 'Rabeprazole', dose: '20mg', form: 'Tab.', company: 'Square Pharma', price: '৳8.00/tab' },
{ name: 'Amoxil', generic: 'Amoxicillin', dose: '500mg', form: 'Cap.', company: 'Square Pharma', price: '৳8.00/cap' },
{ name: 'Moxacil', generic: 'Amoxicillin', dose: '500mg', form: 'Cap.', company: 'Beximco Pharma', price: '৳8.00/cap' },
{ name: 'Zithromax', generic: 'Azithromycin', dose: '500mg', form: 'Tab.', company: 'Pfizer / Square', price: '৳50.00/tab' },
{ name: 'Azithcin', generic: 'Azithromycin', dose: '500mg', form: 'Tab.', company: 'Beximco Pharma', price: '৳48.00/tab' },
{ name: 'Zimax', generic: 'Azithromycin', dose: '500mg', form: 'Tab.', company: 'Renata Ltd', price: '৳50.00/tab' },
{ name: 'Ciprocin', generic: 'Ciprofloxacin', dose: '500mg', form: 'Tab.', company: 'Square Pharma', price: '৳14.00/tab' },
{ name: 'Neofloxin', generic: 'Ciprofloxacin', dose: '500mg', form: 'Tab.', company: 'Beximco Pharma', price: '৳14.00/tab' },
{ name: 'Flagyl', generic: 'Metronidazole', dose: '400mg', form: 'Tab.', company: 'Sanofi / Square', price: '৳3.50/tab' },
{ name: 'Amodis', generic: 'Metronidazole', dose: '400mg', form: 'Tab.', company: 'Beximco Pharma', price: '৳3.50/tab' },
{ name: 'Cef-3', generic: 'Cefixime', dose: '200mg', form: 'Cap.', company: 'Beximco Pharma', price: '৳35.00/cap' },
{ name: 'Cefix', generic: 'Cefixime', dose: '200mg', form: 'Cap.', company: 'Square Pharma', price: '৳35.00/cap' },
{ name: 'Zinnat', generic: 'Cefuroxime Axetil', dose: '500mg', form: 'Tab.', company: 'GSK', price: '৳85.00/tab' },
{ name: 'Kilmax', generic: 'Cefuroxime Axetil', dose: '500mg', form: 'Tab.', company: 'Square Pharma', price: '৳80.00/tab' },
{ name: 'Doxacin', generic: 'Doxycycline', dose: '100mg', form: 'Cap.', company: 'Square Pharma', price: '৳7.00/cap' },
{ name: 'Glucomin', generic: 'Metformin HCl', dose: '500mg', form: 'Tab.', company: 'Square Pharma', price: '৳3.50/tab' },
{ name: 'Comet', generic: 'Metformin HCl', dose: '500mg', form: 'Tab.', company: 'Square Pharma', price: '৳3.50/tab' },
{ name: 'Amaryl', generic: 'Glimepiride', dose: '2mg', form: 'Tab.', company: 'Sanofi-Aventis', price: '৳15.00/tab' },
{ name: 'Secrin', generic: 'Glimepiride', dose: '2mg', form: 'Tab.', company: 'Square Pharma', price: '৳12.00/tab' },
{ name: 'Amdocal', generic: 'Amlodipine', dose: '5mg', form: 'Tab.', company: 'Square Pharma', price: '৳5.00/tab' },
{ name: 'Amlong', generic: 'Amlodipine', dose: '5mg', form: 'Tab.', company: 'Beximco Pharma', price: '৳5.00/tab' },
{ name: 'Bisoren', generic: 'Bisoprolol Fumarate', dose: '2.5mg', form: 'Tab.', company: 'Square Pharma', price: '৳8.00/tab' },
{ name: 'Losartan', generic: 'Losartan Potassium', dose: '50mg', form: 'Tab.', company: 'Square Pharma', price: '৳9.00/tab' },
{ name: 'Angilock', generic: 'Losartan Potassium', dose: '50mg', form: 'Tab.', company: 'Square Pharma', price: '৳9.00/tab' },
{ name: 'Atova', generic: 'Atorvastatin', dose: '10mg', form: 'Tab.', company: 'Square Pharma', price: '৳12.00/tab' },
{ name: 'Lipicon', generic: 'Atorvastatin', dose: '10mg', form: 'Tab.', company: 'Beximco Pharma', price: '৳12.00/tab' },
{ name: 'Ecotrin', generic: 'Aspirin (Gastro-resistant)', dose: '75mg', form: 'Tab.', company: 'Square Pharma', price: '৳2.00/tab' },
{ name: 'Clopid', generic: 'Clopidogrel', dose: '75mg', form: 'Tab.', company: 'Square Pharma', price: '৳12.00/tab' },
{ name: 'Anlet', generic: 'Clopidogrel', dose: '75mg', form: 'Tab.', company: 'Beximco Pharma', price: '৳12.00/tab' },
{ name: 'Calbo-D', generic: 'Calcium + Vitamin D3', dose: '500mg+200IU', form: 'Tab.', company: 'Square Pharma', price: '৳9.00/tab' },
{ name: 'Calcin-D', generic: 'Calcium + Vitamin D3', dose: '500mg+200IU', form: 'Tab.', company: 'Beximco Pharma', price: '৳9.00/tab' },
{ name: 'Fexo', generic: 'Fexofenadine HCl', dose: '120mg', form: 'Tab.', company: 'Square Pharma', price: '৳12.00/tab' },
{ name: 'Alatrol', generic: 'Cetirizine HCl', dose: '10mg', form: 'Tab.', company: 'Renata Ltd', price: '৳4.00/tab' },
{ name: 'Cetriz', generic: 'Cetirizine HCl', dose: '10mg', form: 'Tab.', company: 'Square Pharma', price: '৳4.00/tab' },
{ name: 'Monas', generic: 'Montelukast', dose: '10mg', form: 'Tab.', company: 'Acme Laboratories', price: '৳16.00/tab' },
{ name: 'Provair', generic: 'Montelukast', dose: '10mg', form: 'Tab.', company: 'Unimed Unihealth', price: '৳16.00/tab' },
{ name: 'Naprox', generic: 'Naproxen', dose: '500mg', form: 'Tab.', company: 'Square Pharma', price: '৳10.00/tab' },
{ name: 'Profen', generic: 'Ibuprofen', dose: '400mg', form: 'Tab.', company: 'Square Pharma', price: '৳4.00/tab' },
{ name: 'Clofenac', generic: 'Diclofenac Sodium', dose: '50mg', form: 'Tab.', company: 'Square Pharma', price: '৳4.00/tab' },
{ name: 'Motigut', generic: 'Domperidone', dose: '10mg', form: 'Tab.', company: 'Square Pharma', price: '৳3.50/tab' },
{ name: 'Ondem', generic: 'Ondansetron', dose: '4mg', form: 'Tab.', company: 'Beximco Pharma', price: '৳20.00/tab' },
{ name: 'Visset', generic: 'Ondansetron', dose: '4mg', form: 'Tab.', company: 'Square Pharma', price: '৳20.00/tab' },
{ name: 'Almex', generic: 'Albendazole', dose: '400mg', form: 'Tab.', company: 'Square Pharma', price: '৳15.00/tab' },
{ name: 'Salbulin Inhaler', generic: 'Salbutamol', dose: '100mcg/puff', form: 'Inh.', company: 'Square Pharma', price: '৳180.00/inhaler' },
{ name: 'Biphasic Insulin 30/70', generic: 'Insulin (Human)', dose: '100IU/ml', form: 'Inj.', company: 'Novo Nordisk', price: '৳450.00/vial' }
];
// ── FAST INDEXEDDB DRUG CACHING (0ms INSTANT LOAD WITHOUT LOCALSTORAGE QUOTA LIMITS) ──
function openDrugDB() {
return new Promise((resolve, reject) => {
if (!window.indexedDB) return reject(new Error('IndexedDB unsupported'));
const req = indexedDB.open('PrescribeProDrugsDB', 1);
req.onupgradeneeded = e => {
const db = e.target.result;
if (!db.objectStoreNames.contains('catalog')) {
db.createObjectStore('catalog');
}
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
async function getCachedDrugsIDB() {
try {
const db = await openDrugDB();
return new Promise(resolve => {
const tx = db.transaction('catalog', 'readonly');
const req = tx.objectStore('catalog').get('drugs_list');
req.onsuccess = () => resolve(req.result || null);
req.onerror = () => resolve(null);
});
} catch (e) {
return null;
}
}
async function setCachedDrugsIDB(data) {
try {
const db = await openDrugDB();
return new Promise(resolve => {
const tx = db.transaction('catalog', 'readwrite');
const req = tx.objectStore('catalog').put(data, 'drugs_list');
req.onsuccess = () => resolve(true);
req.onerror = () => resolve(false);
});
} catch (e) {
return false;
}
}
async function loadExternalDrugDatabase() {
// Step 1: Clean legacy localStorage quota hog if any remains
try { localStorage.removeItem('prescribepro_cached_drugs'); } catch (_) {}
// Step 2: Instant 0ms load from IndexedDB
try {
const cached = await getCachedDrugsIDB();
if (Array.isArray(cached) && cached.length > 0) {
externalDrugs = cached;
console.log(`⚡ Instant loaded ${externalDrugs.length} medicines from IndexedDB cache`);
}
} catch (e) {
console.warn('IDB load error:', e);
}
// Step 3: Background fetch data/drugs.json to populate/refresh IndexedDB
try {
const res = await fetch('data/drugs.json');
if (res.ok) {
const data = await res.json();
if (Array.isArray(data) && data.length > 0) {
externalDrugs = data;
await setCachedDrugsIDB(data);
console.log(`Updated IndexedDB cache with ${externalDrugs.length} clinical medicines`);
}
}
} catch (e) {
console.warn('Could not fetch data/drugs.json, using cached or fallback formulary:', e);
}
}
// ── REAL-TIME PRESCRIPTION DRAFT AUTO-SAVE & RECOVERY ──
function saveRxDraft() {
const modalRx = document.getElementById('modal-rx');
if (!modalRx || modalRx.classList.contains('hidden')) return;
const rx = collectRxData();
const hasContent = rx.complaints || rx.diagnosis || rx.plan || rx.history || rx.findings || rx.investigation || rx.advice || (rx.drugs && rx.drugs.length > 0 && rx.drugs[0].name);
if (hasContent) {
localStorage.setItem('prescribepro_rx_draft', JSON.stringify(rx));
} else {
clearRxDraft();
}
}
function clearRxDraft() {
localStorage.removeItem('prescribepro_rx_draft');
}
function restoreRxDraft(expectedPatientId) {
const savedDraft = localStorage.getItem('prescribepro_rx_draft');
if (!savedDraft) return false;
try {
const draft = JSON.parse(savedDraft);
if (!draft) return false;
// If a specific patient was requested, only auto-restore a draft written
// for that same patient. Otherwise opening a patient's "New Rx" could
// silently load another patient's notes. A blank request (global "New
// Prescription") restores whatever draft exists, as before.
if (expectedPatientId && (draft.patientId || '') !== expectedPatientId) {
return false;
}
const sel = document.getElementById('rx-patient-select');
if (sel && draft.patientId) sel.value = draft.patientId;
setV('rx-date', draft.date || new Date().toISOString().split('T')[0]);
setV('rx-visit', draft.visitType || 'New Visit');
setV('rx-complaints', draft.complaints || '');
setV('rx-diagnosis', draft.diagnosis || '');
setV('rx-history', draft.history || '');
setV('rx-findings', draft.findings || '');
setV('rx-investigation', draft.investigation || '');
setV('rx-advice', draft.advice || '');
setV('rx-notes', draft.notes || '');
setV('rx-plan', draft.plan || '');
const planCheck = document.getElementById('rx-plan-check');
if (planCheck) {
planCheck.checked = Boolean(draft.plan && draft.plan.trim());
togglePlanField();
}
setV('rx-followup-days', draft.followupDays || '');
setV('rx-followup-unit', draft.followupUnit || 'days');
if (draft.drugs && draft.drugs.length > 0) {
document.getElementById('drug-rows').innerHTML = '';
draft.drugs.forEach(drug => {
applyDrugToRow(addDrugRow(), drug);
});
}
toast('📝 Unsaved prescription draft restored');
return true;
} catch(e) {
console.error('Error restoring draft:', e);
return false;
}
}
// ── THEME MANAGEMENT ──
function applyTheme(t, skipSave = false) {
state.theme = t;
document.documentElement.setAttribute('data-theme', t);
const btn = document.getElementById('theme-toggle-btn');
if (btn) btn.textContent = t === 'dark' ? '☀️' : '🌙';
if (!skipSave && state.loggedIn) {
saveState();
}
}
function toggleTheme() {
const newTheme = state.theme === 'dark' ? 'light' : 'dark';
applyTheme(newTheme);
toast(newTheme === 'dark' ? '🌙 Dark Mode Enabled' : '☀️ Light Mode Enabled');
}
// ── PERSISTENCE & TOMBSTONE TRACKING ──
function ensureTombstones() {
if (!state.tombstones || typeof state.tombstones !== 'object') {
state.tombstones = { patients: {}, prescriptions: {}, customDrugs: {} };
}
if (!state.tombstones.patients || typeof state.tombstones.patients !== 'object') state.tombstones.patients = {};
if (!state.tombstones.prescriptions || typeof state.tombstones.prescriptions !== 'object') state.tombstones.prescriptions = {};
if (!state.tombstones.customDrugs || typeof state.tombstones.customDrugs !== 'object') state.tombstones.customDrugs = {};
}
function getStorageKey() {
const email = (state.user && state.user.email) ? state.user.email : 'local_doctor';
return 'prescribepro_state_' + email;
}
function saveState() {
ensureTombstones();
if (state.loggedIn) {
localStorage.setItem('prescribepro_session_active', 'true');
localStorage.setItem('prescribepro_session_method', state.loginMethod || 'local');
if (state.user && state.user.email) {
localStorage.setItem('prescribepro_last_email', state.user.email);
}
}
try {
localStorage.setItem(getStorageKey(), JSON.stringify(state));
} catch (e) {
// Most commonly a QuotaExceededError caused by the large cached drug
// database sharing the same storage quota. Free that cache and retry so
// patient/prescription data is never silently lost.
console.warn('Could not persist state (retrying after clearing drug cache):', e);
try {
localStorage.removeItem('prescribepro_cached_drugs');
localStorage.setItem(getStorageKey(), JSON.stringify(state));
} catch (e2) {
console.error('CRITICAL: Failed to save state to localStorage:', e2);
if (typeof toast === 'function') toast('⚠️ Device storage full — data could not be saved');
}
}
}
function loadState() {
const sessionActive = localStorage.getItem('prescribepro_session_active') === 'true';
const lastEmail = localStorage.getItem('prescribepro_last_email') || 'local_doctor';
const key = 'prescribepro_state_' + lastEmail;
const s = localStorage.getItem(key) || localStorage.getItem('prescribepro_state') || localStorage.getItem('prescribepro_state_local_doctor');
if (s) {
try {
const loaded = JSON.parse(s);
Object.assign(state, loaded);
if (!Array.isArray(state.customDrugs)) state.customDrugs = [];
ensureTombstones();
} catch(e) {
console.error('Failed to parse local state:', e);
ensureTombstones();
}
} else {
ensureTombstones();
}
if (sessionActive) {
state.loggedIn = true;
state.loginMethod = localStorage.getItem('prescribepro_session_method') || state.loginMethod || 'local';
}
if (state.theme) applyTheme(state.theme, true);
const cachedToken = localStorage.getItem('google_access_token');
const cachedExpiry = localStorage.getItem('google_token_expiry');
if (cachedToken && cachedExpiry && parseInt(cachedExpiry) > Date.now()) {
googleAccessToken = cachedToken;
googleTokenExpiry = parseInt(cachedExpiry);
}
}
function resetActivityTimer() {}
function startAutoLockMonitor() {}
function lockDesk() {}
function unlockDesk() {}
// ── INITIALIZATION ──
document.addEventListener('DOMContentLoaded', () => {
loadState();
initUI();
loadExternalDrugDatabase();
startAutoLockMonitor();
const sessionActive = localStorage.getItem('prescribepro_session_active') === 'true';
if (state.loggedIn || sessionActive) {
state.loggedIn = true;
saveState();
showApp();
if (state.loginMethod === 'google') {
syncWithGoogleCloud();
setInterval(() => {
if (state.loggedIn && state.loginMethod === 'google') {
refreshGoogleTokenSilently();
}
}, 40 * 60 * 1000);
} else {
updateDriveStatus('offline');
}
} else {
showSection('login');
}
});
function initUI() {
['pad-align','pad-left-width','pad-color','show-history','show-findings','show-investigation','show-advice','show-followup','show-signature','show-generic']
.forEach(id => {
const el = document.getElementById(id);
if (el) el.addEventListener('change', updatePadPreview);
});
const rxModalEl = document.getElementById('modal-rx');
if (rxModalEl) {
rxModalEl.addEventListener('input', saveRxDraft);
rxModalEl.addEventListener('change', saveRxDraft);
}
if (document.getElementById('drug-rows')) {
addDrugRow();
}
document.querySelectorAll('#section-profile input').forEach(input => {
input.addEventListener('change', () => saveProfile(true));
});
initClinicalQuickPicks();
if (window.RxQuad && typeof RxQuad.init === 'function') RxQuad.init(); // [QUAD]
}
// Add a collapsible "Quick picks" chip row above each clinical text field.
function initClinicalQuickPicks() {
Object.entries(CLINICAL_PRESETS).forEach(([fieldId, presets]) => {
const ta = document.getElementById(fieldId);
if (!ta || ta.dataset.quickPicks === 'done') return;
ta.dataset.quickPicks = 'done';
const toggle = document.createElement('button');
toggle.type = 'button';
toggle.className = 'qp-toggle';
toggle.textContent = '⚡ Quick picks';
const row = document.createElement('div');
row.className = 'chip-row clinical hidden';
presets.forEach(p => {
const b = document.createElement('button');
b.type = 'button';
b.className = 'chip';
b.textContent = p;
b.addEventListener('click', () => appendToField(fieldId, p));
row.appendChild(b);
});
toggle.addEventListener('click', () => row.classList.toggle('hidden'));
ta.parentNode.insertBefore(toggle, ta);
ta.parentNode.insertBefore(row, ta);
});
}
// Append a phrase to a text field, avoiding exact duplicates.
function appendToField(fieldId, text) {
const ta = document.getElementById(fieldId);
if (!ta) return;
const current = ta.value.trim();
const existing = current ? current.split(/\n|,\s*/).map(s => s.trim().toLowerCase()) : [];
if (!existing.includes(text.toLowerCase())) {
ta.value = current ? current + '\n' + text : text;
}
ta.focus();
ta.dispatchEvent(new Event('input', { bubbles: true }));
}
function togglePlanField() {
const check = document.getElementById('rx-plan-check');
const container = document.getElementById('rx-plan-container');
if (!check || !container) return;
if (check.checked) {
container.classList.remove('hidden');
const editor = container.querySelector('.rx-quad-editor');
if (editor) {
setTimeout(() => editor.focus(), 50);
} else {
const ta = document.getElementById('rx-plan');
if (ta) setTimeout(() => ta.focus(), 50);
}
} else {
container.classList.add('hidden');
}
}
// ── AUTH TAB & LOGIN METHODS ──
function switchAuthTab(mode) {
document.querySelectorAll('.auth-tab').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.auth-panel').forEach(p => p.classList.remove('active'));
if (mode === 'google') {
document.getElementById('tab-btn-google')?.classList.add('active');
document.getElementById('panel-auth-google')?.classList.add('active');
} else {
document.getElementById('tab-btn-local')?.classList.add('active');
document.getElementById('panel-auth-local')?.classList.add('active');
}
}
// ── BMDC REGISTRATION HELPERS ──
function cleanBmdcValue(raw) {
if (!raw) return '';
let str = String(raw).trim();
str = str.replace(/^(BMDC\s*(?:Reg(?:\s*No)?\.?)?:?|Reg(?:\s*No)?\.?:?)\s*/i, '').trim();
return str;
}
function extractBmdcNumber(raw) {
return cleanBmdcValue(raw);
}
function formatBmdcReg(raw) {
const cleaned = cleanBmdcValue(raw);
if (!cleaned) return '';
return `BMDC Reg No: ${cleaned}`;
}
function startLocalLogin() {
const docName = v('local-doc-name').trim();
const rawBmdc = v('local-bmdc-reg').trim();
if (!docName) {
toast('⚠️ Please enter Doctor Name');
document.getElementById('local-doc-name')?.focus();
return;
}
const bmdcVal = cleanBmdcValue(rawBmdc);
if (!bmdcVal) {
toast('⚠️ BMDC Registration Number is required to enter workspace');
document.getElementById('local-bmdc-reg')?.focus();
return;
}
state.loggedIn = true;
state.loginMethod = 'local';
state.user = { name: docName, email: 'local@doctor', initials: getInitials(docName) };
if (!state.profile.name || state.profile.name === 'Dr. Someone') {
state.profile.name = docName;
}
state.profile.reg = formatBmdcReg(bmdcVal);
saveState();
showApp();
toast('✅ Welcome, ' + docName);
}
function getInitials(name) {
const parts = name.replace(/^Dr\.\s*/i, '').split(' ');
return parts.map(p => p[0]).join('').substring(0, 2).toUpperCase() || 'DR';
}
function logout() {
if (confirm('Log out from current session?')) {
state.loggedIn = false;
googleAccessToken = null;
googleTokenExpiry = null;
localStorage.setItem('prescribepro_session_active', 'false');
localStorage.removeItem('google_access_token');
localStorage.removeItem('google_token_expiry');
saveState();
location.reload();
}
}
// ── GOOGLE AUTH ──
const GOOGLE_CLIENT_ID = '744204331957-vnium3sdih08go5iuv0rlpctvgqhjara.apps.googleusercontent.com';
const GOOGLE_SCOPES = 'openid profile email https://www.googleapis.com/auth/drive.appdata';
function initGoogleAuth() {
if (typeof google === 'undefined' || !google.accounts) return;
if (tokenClient) return;
try {
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: GOOGLE_CLIENT_ID,
scope: GOOGLE_SCOPES,
callback: onTokenReceived,
error_callback: onTokenError,
});
} catch(e) {
console.error('Failed to initialize Google GSI Client:', e);
}
}
let isRefreshingToken = false;
function refreshGoogleTokenSilently() {
if (typeof google === 'undefined' || !google.accounts) return Promise.resolve(false);
initGoogleAuth();
if (!tokenClient) return Promise.resolve(false);
if (isRefreshingToken) return Promise.resolve(false);
isRefreshingToken = true;
return new Promise((resolve) => {
const originalCallback = tokenClient.callback;
const timeoutTimer = setTimeout(() => {
tokenClient.callback = originalCallback;
isRefreshingToken = false;
resolve(false);
}, 10000);
tokenClient.callback = (tokenResponse) => {
clearTimeout(timeoutTimer);
tokenClient.callback = originalCallback;
isRefreshingToken = false;
if (tokenResponse && !tokenResponse.error && tokenResponse.access_token) {
googleAccessToken = tokenResponse.access_token;
googleTokenExpiry = Date.now() + ((tokenResponse.expires_in || 3600) * 1000);
localStorage.setItem('google_access_token', googleAccessToken);
localStorage.setItem('google_token_expiry', googleTokenExpiry.toString());
updateDriveStatus('synced');
console.log('⚡ Google Cloud token silently renewed!');
resolve(true);
} else {
console.warn('Silent Google token refresh returned error:', tokenResponse?.error);
resolve(false);
}
};
try {
tokenClient.requestAccessToken({ prompt: '' });
} catch(e) {
clearTimeout(timeoutTimer);
tokenClient.callback = originalCallback;
isRefreshingToken = false;
resolve(false);
}
});
}
function startGoogleLogin() {
if (typeof google === 'undefined' || !google.accounts) {
toast('❌ Google sign-in script not loaded. You can use Quick Local Mode offline!');
switchAuthTab('local');
return;
}
initGoogleAuth();
if (!tokenClient) {
toast('❌ Initializing Google auth, please retry in a second.');
return;
}
setLoginLoading(true, 'Opening Google sign-in…');
try {
tokenClient.requestAccessToken({ prompt: 'select_account' });
} catch (e) {
setLoginLoading(false);
toast('❌ Google Sign-In Error: ' + e.message);
}
}
function onTokenReceived(tokenResponse) {
if (tokenResponse.error) {
setLoginLoading(false);
toast('❌ Google Auth cancelled or failed: ' + tokenResponse.error);
return;
}
googleAccessToken = tokenResponse.access_token;
googleTokenExpiry = Date.now() + ((tokenResponse.expires_in || 3600) * 1000);
localStorage.setItem('google_access_token', googleAccessToken);
localStorage.setItem('google_token_expiry', googleTokenExpiry.toString());
fetchUserInfoAndLogin();
}
function onTokenError(err) {
setLoginLoading(false);
toast('❌ Auth Error: ' + (err.message || 'Unknown error'));
}
async function fetchUserInfoAndLogin() {
setLoginLoading(true, 'Fetching doctor account info…');
try {
const res = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', {
headers: { Authorization: `Bearer ${googleAccessToken}` }
});
if (res.ok) {
const userInfo = await res.json();
state.user = {
name: userInfo.name || 'Doctor',
email: userInfo.email || 'doctor@gmail.com',
initials: getInitials(userInfo.name || 'Doctor')
};
if (!state.profile.name || state.profile.name === 'Dr. Someone') {
state.profile.name = 'Dr. ' + (userInfo.name || '');
}
}
} catch (e) {
console.warn('Could not fetch Google user profile info:', e);
}
state.loggedIn = true;
state.loginMethod = 'google';
localStorage.setItem('prescribepro_session_active', 'true');
saveState();
setLoginLoading(false);
showApp();
toast('✅ Signed in with Google');
setTimeout(() => { syncWithGoogleCloud(true); }, 500);
}
function setLoginLoading(show, text) {
const btn = document.getElementById('btn-google-signin');
const loading = document.getElementById('login-loading');
const txt = document.getElementById('login-loading-text');
if (btn) btn.style.display = show ? 'none' : 'flex';
if (loading) loading.style.display = show ? 'flex' : 'none';
if (txt && text) txt.textContent = text;
}
// ── NAVIGATION & VIEWS ──
function showApp() {
document.getElementById('page-login').classList.remove('active');
document.getElementById('topnav').classList.remove('hidden');
document.getElementById('main-layout').classList.remove('hidden');
document.getElementById('mobile-bottom-nav')?.classList.remove('hidden');
const avatar = document.getElementById('user-avatar');
if (avatar) avatar.textContent = state.user.initials || 'DR';
if (window.RxQuad && typeof RxQuad.init === 'function') RxQuad.init(); // [QUAD]
showSection('dashboard');
}
function showSection(sec) {
document.querySelectorAll('.section-content').forEach(s => s.classList.add('hidden'));
document.querySelectorAll('.sidebar-btn').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.mob-nav-btn').forEach(b => b.classList.remove('active'));
const target = document.getElementById(`section-${sec}`);
const sbtn = document.getElementById(`sb-${sec}`);
const mbtn = document.getElementById(`mnob-${sec}`);
if (target) target.classList.remove('hidden');
if (sbtn) sbtn.classList.add('active');
if (mbtn) mbtn.classList.add('active');
if (sec === 'dashboard') renderDashboard();
if (sec === 'patients') renderPatients();
if (sec === 'prescriptions') renderAllRx();
if (sec === 'profile') populateProfileForm();
if (sec === 'paddesign') initPadDesignSection();
}
function scrollToRxSec(secId) {
const el = document.getElementById(secId);
if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
// ── DRUG ROWS & PRESCRIPTION WRITING ──
let drugRowId = 0;
function addDrugRow(autoFocus = false) {
const id = ++drugRowId;
const card = document.createElement('div');
card.className = 'drug-card';
card.id = `dr-${id}`;
const formOptions = MEDICINE_FORMS.map(f => `<option value="${f.value}">${f.label}</option>`).join('');
const routeOptions = ROUTES.map(r => `<option value="${r}">${r}</option>`).join('');
const freqChipsBn = FREQ_PRESETS_BN.map(p => `<button type="button" class="chip" onclick="applyPreset('dfreq-${id}','${p}',${id})">${p}</button>`).join('');
const freqChipsEn = FREQ_PRESETS_EN.map(p => `<button type="button" class="chip" onclick="applyPreset('dfreq-${id}','${p}',${id})">${p}</button>`).join('');
const durChipsBn = DURATION_PRESETS_BN.map(p => `<button type="button" class="chip" onclick="applyPreset('ddur-${id}','${p}',${id})">${p}</button>`).join('');
const durChipsEn = DURATION_PRESETS_EN.map(p => `<button type="button" class="chip" onclick="applyPreset('ddur-${id}','${p}',${id})">${p}</button>`).join('');
card.innerHTML = `
<div class="drug-card-tools">
<button type="button" class="tool-btn" onclick="moveDrugRow(${id},-1)" title="Move up" aria-label="Move medication up">▲</button>
<button type="button" class="tool-btn" onclick="moveDrugRow(${id},1)" title="Move down" aria-label="Move medication down">▼</button>
<button type="button" class="tool-btn danger" onclick="removeDrugRow(${id})" title="Remove medication" aria-label="Remove medication">✕</button>
</div>
<div class="drug-grid-main">
<div>
<div class="drug-field-label">Type / Form</div>
<select id="dform-${id}" onchange="onDrugFormChange(${id})">
${formOptions}
</select>
</div>
<div class="drug-name-wrap">
<div class="drug-field-label">Brand / Generic Name</div>
<input type="text" id="dname-${id}" placeholder="Search brand or generic…" oninput="drugSearch(this, ${id})" onkeydown="handleDrugKeydown(event, ${id})" autocomplete="off" style="font-weight:700; color:var(--rx-blue)">
<div class="drug-autocomplete hidden" id="dac-${id}"></div>
</div>
<div>
<div class="drug-field-label">Generic Name (Molecule)</div>
<input type="text" id="dgeneric-${id}" placeholder="e.g. Paracetamol" style="font-style:italic">
</div>
<div>
<div class="drug-field-label">Strength / Dose</div>
<input type="text" id="ddose-${id}" placeholder="e.g. 500mg">
</div>
</div>
<div class="drug-grid-secondary">
<div class="drug-field">
<div class="drug-field-label">Frequency (সেবন মাত্রা)</div>
<input type="text" id="dfreq-${id}" placeholder="e.g. ১+০+১ / 1+0+1" autocomplete="off">
<div class="chip-group">
<div class="chip-row mini">${freqChipsBn}</div>
<div class="chip-row mini">${freqChipsEn}</div>
</div>
</div>
<div class="drug-field">
<div class="drug-field-label">Duration (স্থায়িত্বকাল)</div>
<input type="text" id="ddur-${id}" placeholder="e.g. ৭ দিন / 7 days" autocomplete="off">
<div class="chip-group">
<div class="chip-row mini">${durChipsBn}</div>
<div class="chip-row mini">${durChipsEn}</div>
</div>
</div>
<div class="drug-field">
<div class="drug-field-label">Timing (খাওয়ার সময়)</div>
<select id="dtiming-sel-${id}" onchange="toggleCustomTiming(${id})">
<option value="" selected>— Not set —</option>
<optgroup label="🇧🇩 বাংলা নির্দেশনা (Bengali First)">
<option value="খাবার পরে">খাবার পরে (After meal)</option>
<option value="খাবার আগে">খাবার আগে (Before meal)</option>
<option value="খাবারের সাথে">খাবারের সাথে (With meal)</option>
<option value="খালি পেটে">খালি পেটে (Empty stomach)</option>
<option value="রাতে ঘুমানোর আগে">রাতে ঘুমানোর আগে (At bedtime)</option>
<option value="ভরা পেটে">ভরা পেটে</option>
<option value="জ্বর আসলে">জ্বর আসলে (SOS)</option>
<option value="ব্যথা হলে">ব্যথা হলে (SOS)</option>
</optgroup>
<optgroup label="🇬🇧 English Instructions">
<option value="After meal">After meal</option>
<option value="Before meal">Before meal</option>
<option value="With meal">With meal</option>
<option value="Empty stomach">Empty stomach</option>
<option value="At bedtime">At bedtime</option>
<option value="As needed (SOS)">As needed (SOS)</option>
</optgroup>
<optgroup label="Custom">
<option value="Custom">✏️ Custom instruction…</option>
</optgroup>
</select>
<input type="text" id="dtiming-custom-${id}" class="hidden" placeholder="Type custom timing instruction…" style="margin-top:4px">
</div>
<div class="drug-field">
<div class="drug-field-label">Route</div>
<select id="droute-${id}">
<option value="">Auto / by form</option>
${routeOptions}
</select>
</div>
<div class="drug-field wide">
<div class="drug-field-label">Special Advice / Notes</div>
<input type="text" id="dnotes-${id}" placeholder="e.g. Take with plenty of water">
</div>
</div>
<div class="drug-card-foot">
<span class="sig-label">Prints as:</span>
<span class="sig-preview" id="sig-${id}">—</span>
</div>
`;
document.getElementById('drug-rows').appendChild(card);
// Live "prints as" preview updates for every field on the card.
['dname', 'dgeneric', 'ddose', 'dfreq', 'ddur', 'dnotes', 'dtiming-sel', 'dtiming-custom', 'droute']
.forEach(pre => {
const el = document.getElementById(`${pre}-${id}`);
if (!el) return;
el.addEventListener(el.tagName === 'SELECT' ? 'change' : 'input', () => updateSigPreview(id));