File size: 48,895 Bytes
6ea020b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
<!-- templates/result_entry.html -->
{% extends "base.html" %}
{% block title %}Double Authorisation - NexLab{% endblock %}
{% block page_title %}Double Authorisation{% endblock %}
{% block content %}
<!-- Quill.js Rich Text Editor CSS -->
<link href="/static/vendor/quill/quill.snow.css" rel="stylesheet">
<style>
    .result-grid { font-size: 13px; border-collapse: collapse; }
    .result-grid th { position: sticky; top: 0; z-index: 10; background: #e2e8f0; border: 1px solid #cbd5e1; }
    .result-grid td, .result-grid th { padding: 3px 5px; white-space: nowrap; vertical-align: middle; text-align: center; border: 1px solid #cbd5e1; }
    .result-grid input, .result-grid select { font-size: 13px; padding: 4px 6px; }
    .row-parent { background: #eef2ff !important; font-weight: 600; }
    .row-parent td { border-bottom: 1px solid #c7d2fe; }
    .row-child .test-name { padding-left: 32px !important; font-weight: 400; color: #475569; }
    .row-header .test-name { padding-left: 32px !important; font-weight: 600; color: #334155; font-style: italic; }
    .row-standalone { font-weight: 500; }
    .result-input { width: 120px; border: 1px solid #cbd5e1; border-radius: 6px; transition: all 0.2s; }
    .result-input:focus { outline: none; border-color: #6366f1; box-shadow: 0 0 0 2px rgba(99,102,241,0.2); }
    .bg-high { background-color: #fef3c7 !important; border-color: #f59e0b !important; }
    .bg-low { background-color: #dbeafe !important; border-color: #3b82f6 !important; }
    .bg-panic { background-color: #fee2e2 !important; border-color: #ef4444 !important; }
    .status-high { color: #d97706; font-weight: 700; }
    .status-low { color: #2563eb; font-weight: 700; }
    .status-normal { color: #16a34a; font-weight: 500; }
    .status-panic { color: #dc2626; font-weight: 700; }
    .device-select { width: 130px; border: 1px solid #cbd5e1; border-radius: 6px; }
    .remark-input { width: 100px; border: 1px solid #cbd5e1; border-radius: 6px; }
    .save-footer { position: sticky; bottom: 0; z-index: 20; }
    .action-btn { padding: 4px 10px; font-size: 16px; border-radius: 4px; border: 1px solid #e2e8f0; cursor: pointer; transition: all 0.15s; display: inline-flex; align-items: center; justify-content: center; }
    .action-btn:hover { background: #f1f5f9; }
    .authorize-cb { width: 16px; height: 16px; accent-color: #4f46e5; cursor: pointer; }
    .loading-overlay { position: absolute; inset: 0; background: rgba(255,255,255,0.8); display: flex; align-items: center; justify-content: center; z-index: 50; }
    .spinner { width: 40px; height: 40px; border: 4px solid #e2e8f0; border-top-color: #6366f1; border-radius: 50%; animation: spin 0.7s linear infinite; }
    @keyframes spin { to { transform: rotate(360deg); } }
</style>

<!-- Patient Header -->
<div class="bg-white rounded-3xl shadow-sm border border-slate-200 mb-4 p-5 relative overflow-hidden">
    <div class="absolute top-4 right-4">
        <a href="/patients/edit/{{ patient.patient_id }}{% if visit %}?visit_id={{ visit.visit_id }}{% endif %}" class="bg-slate-100 hover:bg-slate-200 text-slate-700 px-4 py-2 rounded-lg text-sm font-medium transition">← Back to Patient</a>
    </div>
    
    <div class="flex items-start gap-4">
        <div class="w-14 h-14 rounded-full bg-indigo-100 text-indigo-600 flex items-center justify-center text-2xl font-bold flex-shrink-0 mt-1">
            {{ patient.full_name[0] if patient.full_name else '?' }}
        </div>
        
        <div class="flex-1 min-w-0 pr-24">
            <h3 class="text-xl font-bold text-slate-800 mb-3"><span class="text-slate-500 text-sm font-semibold mr-1">Name:</span>{{ patient.full_name }}</h3>
            
            <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-y-2 gap-x-4 text-sm text-slate-700 mb-4">
                <div class="truncate" title="ID: {{ patient.patient_id }}"><span class="font-semibold text-slate-500">ID:</span> <span class="font-mono font-bold bg-slate-100 px-1 rounded">{{ patient.patient_id }}</span></div>
                <div class="truncate"><span class="font-semibold text-slate-500">Gender:</span> 
                    <span class="px-1.5 py-0.5 rounded text-xs font-bold {{ 'bg-blue-100 text-blue-800' if patient.gender == 'male' else 'bg-pink-100 text-pink-800' }}">
                        {{ patient.gender|capitalize }}
                    </span>
                </div>
                <div class="truncate"><span class="font-semibold text-slate-500">Age:</span> <span class="font-bold">{{ patient.age }} {{ patient.age_unit or 'year' }}{{ 's' if patient.age and patient.age > 1 else '' }}</span></div>
                <div class="truncate"><span class="font-semibold text-slate-500">Weight:</span> <span class="font-bold">{{ patient.weight or 'N/A' }}</span></div>
                <div class="truncate"><span class="font-semibold text-slate-500">Height:</span> <span class="font-bold">{{ patient.height or 'N/A' }}</span></div>
                <div class="truncate"><span class="font-semibold text-slate-500">Phone:</span> <span class="font-bold">{{ patient.phone_number or 'N/A' }}</span></div>

                {% if visit %}
                <div class="truncate"><span class="font-semibold text-slate-500">Visit:</span> <span class="font-mono font-bold text-xs">{{ visit.visit_id }}</span></div>
                <div class="truncate"><span class="font-semibold text-slate-500">Date:</span> <span class="font-bold">{{ visit.visit_date.strftime('%Y-%m-%d %H:%M') if visit.visit_date else 'N/A' }}</span></div>
                <div class="truncate"><span class="font-semibold text-slate-500">User:</span> <span class="font-bold">{{ visit_user_name or 'System' }}</span></div>
                {% endif %}
                <div class="truncate"><span class="font-semibold text-slate-500">Fasting Time:</span> <span class="font-bold">{{ patient.fasting_time ~ ' hr' if patient.fasting_time is not none else 'N/A' }}</span></div>
            </div>

            <!-- Medical Details -->
            <div class="bg-amber-50 rounded-lg p-3 border border-amber-100">
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 text-sm text-slate-700">
                    <div><span class="font-semibold text-slate-500 block text-xs">Disease/Diagnosis</span><div class="truncate font-bold text-blue-600">{{ patient.diagnosis or '' }}</div></div>
                    <div><span class="font-semibold text-slate-500 block text-xs">Symptoms</span><div class="truncate font-bold text-blue-600">{{ patient.symptoms or '' }}</div></div>
                    <div><span class="font-semibold text-slate-500 block text-xs">Therapy</span><div class="truncate font-bold text-blue-600">{{ patient.therapy or '' }}</div></div>
                    <div><span class="font-semibold text-slate-500 block text-xs">Note</span><div class="truncate font-bold text-blue-600" title="{{ patient.note or '' }}">{{ patient.note or '' }}</div></div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Previous Results -->
{% if all_visits and all_visits|length > 0 %}
<div class="bg-[#d29b9b] rounded-t-lg px-4 py-2 mb-0 flex items-center gap-6 border border-[#c18686]">
    <div class="font-bold text-[#5c2a2a] whitespace-nowrap">Previous Results</div>
    <div class="flex flex-wrap gap-2">
        {% for v in all_visits %}
        <a href="/print-report/{{ patient.patient_id }}?visit_id={{ v.visit_id }}" target="_blank" 
           class="bg-white border border-[#a86f6f] hover:bg-slate-50 text-slate-700 px-3 py-1 shadow-sm text-xs font-medium transition-colors" style="border-radius: 2px;">
            {{ v.visit_date.strftime('%Y-%m-%d') if v.visit_date else 'Unknown' }}
        </a>
        {% endfor %}
    </div>
</div>
{% endif %}

<!-- Grid Container -->
<div class="bg-white rounded-b-3xl rounded-t-none shadow-sm border border-slate-200 relative overflow-hidden" id="gridWrapper">
    <!-- Loading Overlay -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="text-center">
            <div class="spinner mx-auto mb-3"></div>
            <p class="text-slate-500 text-sm">Loading results grid...</p>
        </div>
    </div>

    <div class="overflow-x-auto">
        <table class="min-w-full result-grid" id="resultGrid">
            <thead>
                <tr class="border-b border-slate-200">
                    <th class="text-center text-xs font-semibold text-slate-600 uppercase tracking-wider">Test / Parameter</th>
                    <th class="text-center text-xs font-semibold text-slate-600 uppercase tracking-wider">Result</th>
                    <th class="text-center text-xs font-semibold text-slate-600 uppercase tracking-wider">Unit</th>
                    <th class="text-center text-xs font-semibold text-slate-600 uppercase tracking-wider">Device</th>
                    <th class="text-center text-xs font-semibold text-slate-600 uppercase tracking-wider">Range</th>
                    <th class="text-center text-xs font-semibold text-slate-600 uppercase tracking-wider">AUTH status</th>
                    <th class="text-center text-xs font-semibold text-slate-600 uppercase tracking-wider">Status</th>
                    <th class="text-center text-xs font-semibold text-slate-600 uppercase tracking-wider">ReRun Result</th>
                    <th class="text-center text-xs font-semibold text-slate-600 uppercase tracking-wider">Remark</th>
                    <th class="text-center text-xs font-semibold text-slate-600 uppercase tracking-wider">Actions</th>
                </tr>
            </thead>
            <tbody id="gridBody">
                <!-- Rows will be rendered by JavaScript -->
            </tbody>
        </table>
    </div>

    <!-- Empty State -->
    <div id="emptyState" class="hidden p-12 text-center text-slate-400">
        <svg class="w-16 h-16 mx-auto mb-4 text-slate-300" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path></svg>
        <p class="text-lg font-medium">No orders found for this patient visit</p>
        <p class="text-sm mt-1">Register tests for the patient first.</p>
    </div>

    <!-- Footer with Stats -->
    <div class="p-4 bg-white border-t border-slate-200 rounded-b-xl flex items-center justify-between" id="saveFooter" style="display: none;">
        <div class="text-sm text-slate-500">
            <span id="resultStats"></span>
        </div>
        <button type="button" onclick="doubleAuthorizeAll()" class="bg-indigo-600 hover:bg-indigo-700 text-white px-5 py-2 rounded-lg font-bold shadow-sm transition-colors text-sm">
            ✓✓ Double Auth All
        </button>
    </div>
</div>

<script>
// ===========================
// GLOBAL STATE
// ===========================
let gridData = null;
let allRanges = [];
const patientId = '{{ patient.patient_id }}';
const visitIdParam = '{{ visit.visit_id if visit else "" }}';
const patientGender = '{{ patient.gender }}';
const patientAge = {{ patient.age or 0 }};
let currentNoSampleOrderId = null;

// ===========================
// LOAD DATA
// ===========================
async function loadGridData() {
    try {
        let fetchUrl = `/api/result-entry-data/${patientId}`;
        if (visitIdParam) fetchUrl += `?visit_id=${encodeURIComponent(visitIdParam)}`;
        const resp = await fetch(fetchUrl);
        const data = await resp.json();
        if (data.error) {
            document.getElementById('loadingOverlay').innerHTML = `<p class="text-red-500">${data.error}</p>`;
            return;
        }
        gridData = data;
        allRanges = data.all_ranges || [];
        renderGrid(data.grid_rows);
        
        // Auto-calculate any loaded mathematical formulas immediately mapping variables across rows natively
        calculateAllFormulas();
        
        document.getElementById('loadingOverlay').style.display = 'none';
        if (data.grid_rows.length > 0) {
            document.getElementById('saveFooter').style.display = 'flex';
        } else {
            document.getElementById('emptyState').classList.remove('hidden');
        }
        updateStats();
    } catch (err) {
        document.getElementById('loadingOverlay').innerHTML = `<p class="text-red-500">Error: ${err.message}</p>`;
    }
}

// ===========================
// RENDER GRID
// ===========================
function renderGrid(rows) {
    const tbody = document.getElementById('gridBody');
    tbody.innerHTML = '';

    rows.forEach((row, idx) => {
        if (row.type === 'parent') {
            tbody.appendChild(createParentRow(row, idx));
        } else if (row.type === 'child') {
            tbody.appendChild(createChildRow(row, idx));
        } else {
            tbody.appendChild(createStandaloneRow(row, idx));
        }
    });
}

function createParentRow(row, idx) {
    const tr = document.createElement('tr');
    tr.className = 'row-parent';
    tr.dataset.orderId = row.order_id;
    tr.dataset.idx = idx;
    tr.dataset.type = 'parent';
    const devOptions = buildDeviceOptions(row.devices, row.selected_device_id);
    tr.innerHTML = `
        <td class="test-name">
            <span class="text-indigo-700">📋 ${escHtml(row.test_name)}</span>
        </td>
        <td></td><td></td>
        <td><select class="device-select parent-device-select" data-order-id="${row.order_id}" data-idx="${idx}" disabled>${devOptions}</select></td>
        <td></td>
        <td class="text-center">
            ${row.double_authorized ? '<span class="text-purple-600 font-bold text-lg">✓✓</span>' : (row.authorized ? '<span class="text-green-500 font-bold text-lg">✓</span>' : '')}
        </td>
        <td></td>
        <td class="rerun-result-cell"></td>
        <td><input type="text" class="remark-input parent-remark" data-order-id="${row.order_id}" value="${escAttr(row.note || '')}" placeholder="Note..." disabled></td>
        <td class="text-center">
            ${buildActionButtonsHTML(row)}
        </td>
    `;
    return tr;
}

function createChildRow(row, idx) {
    const tr = document.createElement('tr');
    const isHeader = row.is_header;
    tr.className = isHeader ? 'row-header hover:bg-slate-50' : 'row-child hover:bg-slate-50';
    tr.dataset.orderId = row.order_id;
    tr.dataset.paramId = row.parameter_id;
    tr.dataset.testId = row.test_id;
    tr.dataset.idx = idx;
    tr.dataset.type = 'child';

    if (isHeader) {
        tr.innerHTML = `
            <td class="test-name" colspan="10">
                <span class="text-slate-600">— ${escHtml(row.parameter_name)} —</span>
            </td>
        `;
        return tr;
    }

    const rng = row.range || {};
    const rangeDisplay = formatRangeDisplay(rng);
    const inputHtml = buildInputHtml(row, idx);
    const unitText = rng.unit || '';
    const { statusText, statusClass, inputClass } = computeStatus(row.result_value, rng);
    
    let deviceName = '—';
    if (row.selected_device_id && row.devices) {
        const d = row.devices.find(x => x.id === row.selected_device_id);
        if (d) deviceName = d.name;
    }

    let rerunHtml = escHtml(row.rerun_result || '');
    if (row.result_type === 'paragraph' && row.rerun_result) {
        rerunHtml = `<button type="button" class="bg-indigo-50 text-indigo-700 hover:bg-indigo-100 font-medium text-xs px-2 py-1 rounded border border-indigo-200 transition-colors shadow-sm" onclick="viewRerunParagraph(${idx})">View Rerun</button>`;
    }

    tr.innerHTML = `
        <td class="test-name">${escHtml(row.parameter_name)}</td>
        <td>${inputHtml}</td>
        <td class="text-xs text-slate-600 unit-cell" data-idx="${idx}">${escHtml(unitText)}</td>
        <td class="text-center text-slate-500 text-xs child-device-name" data-idx="${idx}">${escHtml(deviceName)}</td>
        <td class="text-xs text-slate-500 range-cell" data-idx="${idx}">${rangeDisplay}</td>
        <td class="text-center">
            ${row.double_authorized ? '<span class="text-purple-600 font-bold text-lg">✓✓</span>' : (row.authorized ? '<span class="text-green-500 font-bold text-lg">✓</span>' : '')}
        </td>
        <td class="text-center status-cell ${statusClass}" data-idx="${idx}">${statusText}</td>
        <td class="text-center text-sm font-mono text-indigo-500 rerun-result-cell" data-idx="${idx}">${rerunHtml}</td>
        <td></td>
        <td></td>
    `;

    // Apply input class after render
    setTimeout(() => {
        const inp = tr.querySelector('.result-input');
        if (inp && inputClass) inp.classList.add(inputClass);
    }, 0);

    return tr;
}

function createStandaloneRow(row, idx) {
    const tr = document.createElement('tr');
    tr.className = 'row-standalone hover:bg-slate-50';
    tr.dataset.orderId = row.order_id;
    tr.dataset.testId = row.test_id;
    tr.dataset.idx = idx;
    tr.dataset.type = 'standalone';

    const rng = row.range || {};
    const rangeDisplay = formatRangeDisplay(rng);
    const inputHtml = buildInputHtml(row, idx);
    const unitText = rng.unit || '';
    const devOptions = buildDeviceOptions(row.devices, row.selected_device_id);
    const { statusText, statusClass, inputClass } = computeStatus(row.result_value, rng);

    let rerunHtml = escHtml(row.rerun_result || '');
    if (row.result_type === 'paragraph' && row.rerun_result) {
        rerunHtml = `<button type="button" class="bg-indigo-50 text-indigo-700 hover:bg-indigo-100 font-medium text-xs px-2 py-1 rounded border border-indigo-200 transition-colors shadow-sm" onclick="viewRerunParagraph(${idx})">View Rerun</button>`;
    }

    tr.innerHTML = `
        <td class="test-name font-semibold text-slate-800">${escHtml(row.test_name)}</td>
        <td>${inputHtml}</td>
        <td class="text-xs text-slate-600 unit-cell" data-idx="${idx}">${escHtml(unitText)}</td>
        <td><select class="device-select" data-idx="${idx}" disabled>${devOptions}</select></td>
        <td class="text-xs text-slate-500 range-cell" data-idx="${idx}">${rangeDisplay}</td>
        <td class="text-center">
            ${row.double_authorized ? '<span class="text-purple-600 font-bold text-lg">✓✓</span>' : (row.authorized ? '<span class="text-green-500 font-bold text-lg">✓</span>' : '')}
        </td>
        <td class="text-center status-cell ${statusClass}" data-idx="${idx}">${statusText}</td>
        <td class="text-center text-sm font-mono text-indigo-500 rerun-result-cell" data-idx="${idx}">${rerunHtml}</td>
        <td><input type="text" class="remark-input" data-idx="${idx}" value="${escAttr(row.note || '')}" placeholder="Note..." disabled></td>
        <td class="text-center">
            ${buildActionButtonsHTML(row)}
        </td>
    `;

    setTimeout(() => {
        const inp = tr.querySelector('.result-input');
        if (inp && inputClass) inp.classList.add(inputClass);
    }, 0);

    return tr;
}

// ===========================
// BUILD HELPERS
// ===========================
function buildActionButtonsHTML(row) {
    if (row.double_authorized) {
        return `
            <div class="flex gap-2 justify-center">
                <button class="bg-red-50 text-red-600 hover:bg-red-100 px-3 py-1 rounded text-xs font-bold transition" onclick="unauthOrder(${row.order_id}, '${escAttr(row.test_name)}')">UnAUTH</button>
            </div>
        `;
    } else if (row.authorized) {
        return `
            <div class="flex gap-2 justify-center">
                <button class="bg-emerald-50 text-emerald-700 hover:bg-emerald-100 px-3 py-1 rounded text-xs font-bold transition" onclick="doubleAuthorizeOrder(${row.order_id})">Double Auth</button>
                <button class="bg-blue-50 text-blue-600 hover:bg-blue-100 px-3 py-1 rounded text-xs font-bold transition" onclick="rerunOrderDA(${row.order_id})">ReRun</button>
            </div>
        `;
    }
    return '<span class="text-xs text-slate-400">Pending</span>';
}

function buildInputHtml(row, idx) {
    const val = escAttr(row.result_value || '');
    const rt = row.result_type || 'number';
    const disabledAttr = 'readonly';
    
    // Formula Integration
    const isFormula = !!row.formula_expression;
    const formulaAttr = isFormula ? 'readonly title="Auto-calculated from formula"' : '';
    const extraClass = isFormula ? 'bg-indigo-50 border-indigo-200 shadow-inner' : '';

    if (rt === 'selection' && row.selection_options) {
        let opts = [];
        try {
            if (typeof row.selection_options === 'string' && row.selection_options.trim().startsWith('[')) {
                opts = JSON.parse(row.selection_options).map(String);
            } else {
                opts = String(row.selection_options).split(',').map(o => o.trim());
            }
        } catch (e) {
            opts = String(row.selection_options).split(',').map(o => o.trim());
        }
        
        let html = `<div class="flex items-center"><select class="result-input ${extraClass}" data-idx="${idx}" onchange="onResultChange(this)" ${disabledAttr} ${formulaAttr}>`;
        html += `<option value="">-- Select --</option>`;
        opts.forEach(o => {
            html += `<option value="${escAttr(o)}" ${val === String(o) ? 'selected' : ''}>${escHtml(o)}</option>`;
        });
        html += `</select></div>`;
        return html;
    } else if (rt === 'upload') {
        return `<div class="flex items-center"><input type="file" class="result-input text-xs ${extraClass}" data-idx="${idx}" style="width:140px;" ${disabledAttr} ${formulaAttr}></div>`;
    } else if (rt === 'paragraph') {
        return `<div class="flex items-center justify-center">
                    <button type="button" class="bg-indigo-50 text-indigo-700 hover:bg-indigo-100 font-medium text-xs px-3 py-1.5 rounded border border-indigo-200 transition-colors shadow-sm" onclick="viewParagraph(${idx})" ${disabledAttr}>View Paragraph</button>
                </div>`;
    } else if (rt === 'text') {
        return `<div class="flex items-center"><input type="text" class="result-input ${extraClass}" data-idx="${idx}" value="${val}" oninput="onResultChange(this)" placeholder="Enter text..." ${disabledAttr} ${formulaAttr}></div>`;
    } else {
        // Default: number
        return `<div class="flex items-center"><input type="number" step="any" class="result-input ${extraClass}" data-idx="${idx}" value="${val}" oninput="onResultChange(this)" placeholder="0.0" ${disabledAttr} ${formulaAttr}></div>`;
    }
}

function buildDeviceOptions(devices, selectedId) {
    if (!devices || devices.length === 0) return '<option value="">No device</option>';
    let html = '';
    devices.forEach(d => {
        html += `<option value="${d.id}" ${d.id === selectedId ? 'selected' : ''}>${escHtml(d.name)}</option>`;
    });
    return html;
}

function formatRangeDisplay(rng) {
    if (!rng) return '—';
    if (rng.range_type === 'text' && rng.text_range) {
        return `<span class="range-hover-wrapper"><span class="range-hover-btn">Range</span><span class="range-hover-bubble">${rng.text_range}</span></span>`;
    }
    if (rng.normal_from != null && rng.normal_to != null) return `${rng.normal_from} - ${rng.normal_to}`;
    if (rng.normal_from != null) return `≥ ${rng.normal_from}`;
    if (rng.normal_to != null) return `≤ ${rng.normal_to}`;
    return '—';
}

// ===========================
// REAL-TIME VALIDATION
// ===========================
function computeStatus(value, rng) {
    if (!value || value === '' || !rng || rng.range_type === 'text') {
        return { statusText: '', statusClass: '', inputClass: '' };
    }

    const num = parseFloat(value);
    if (isNaN(num)) return { statusText: '', statusClass: '', inputClass: '' };

    // Check panic first
    if (rng.panic_less_than != null && num < rng.panic_less_than) {
        return { statusText: '⚠ PANIC', statusClass: 'status-panic', inputClass: 'bg-panic' };
    }
    if (rng.panic_more_than != null && num > rng.panic_more_than) {
        return { statusText: '⚠ PANIC', statusClass: 'status-panic', inputClass: 'bg-panic' };
    }

    // Check normal
    if (rng.normal_from != null && rng.normal_to != null) {
        if (num >= rng.normal_from && num <= rng.normal_to) {
            return { statusText: 'Normal', statusClass: 'status-normal', inputClass: '' };
        }
    }

    // Check high
    if (rng.high_from != null && num >= rng.high_from) {
        return { statusText: 'High', statusClass: 'status-high', inputClass: 'bg-high' };
    }
    if (rng.normal_to != null && num > rng.normal_to) {
        return { statusText: 'High', statusClass: 'status-high', inputClass: 'bg-high' };
    }

    // Check low
    if (rng.low_to != null && num <= rng.low_to) {
        return { statusText: 'Low', statusClass: 'status-low', inputClass: 'bg-low' };
    }
    if (rng.normal_from != null && num < rng.normal_from) {
        return { statusText: 'Low', statusClass: 'status-low', inputClass: 'bg-low' };
    }

    // Normal if range exists but no specific match
    if (rng.normal_from != null || rng.normal_to != null) {
        return { statusText: 'Normal', statusClass: 'status-normal', inputClass: '' };
    }

    return { statusText: '', statusClass: '', inputClass: '' };
}

function onResultChange(el) {
    const idx = parseInt(el.dataset.idx);
    const row = gridData.grid_rows[idx];
    if (!row) return;

    // Persist exact current typing into JS memory so dependent formulas see it!
    row.result_value = el.value;

    const rng = row.range || {};
    const value = el.value;

    // Remove old classes
    el.classList.remove('bg-high', 'bg-low', 'bg-panic');

    const { statusText, statusClass, inputClass } = computeStatus(value, rng);

    // Update status cell
    const statusCell = document.querySelector(`.status-cell[data-idx="${idx}"]`);
    if (statusCell) {
        statusCell.textContent = statusText;
        statusCell.className = `text-center status-cell ${statusClass}`;
        statusCell.dataset.idx = idx;
    }

    // Update input bg
    if (inputClass) el.classList.add(inputClass);

    updateStats();
    
    // Auto Update formulas globally on screen anytime ANY value naturally changes!
    calculateAllFormulas();
}

// ===========================
// FORMULA CALCULATION
// ===========================
function calculateAllFormulas() {
    gridData.grid_rows.forEach((row, i) => {
        if (!row.formula_expression) return;
        
        let expr = row.formula_expression;
        let isComplete = true;
        let evalExpression = expr;
        
        const varRegex = /\{([^}]+)\}/g;
        const matches = [...expr.matchAll(varRegex)];
        
        for (const m of matches) {
            const varName = m[1].trim();
            // Securely find variable value anywhere in gridData (via Standalone Name or Parameter Name!)
            const sourceRow = gridData.grid_rows.find(r => 
                (r.test_name === varName && r.type === 'standalone') || 
                (r.parameter_name === varName && r.type === 'child')
            );
            
            if (!sourceRow || sourceRow.result_value == null || sourceRow.result_value === '') {
                isComplete = false;
                break;
            }
            
            const numVal = parseFloat(sourceRow.result_value);
            if (isNaN(numVal)) {
                isComplete = false;
                break;
            }
            
            const safeVarName = m[1].replace(/[.*+?^${}()|[\\]]/g, '\\$&');
            evalExpression = evalExpression.replace(new RegExp('\\{' + safeVarName + '\\}', 'g'), numVal);
        }
        
        const inputEl = document.querySelector(`.result-input[data-idx="${i}"]`);
        
        if (isComplete && inputEl && !row.authorized) {
            try {
                const result = Function('"use strict";return (' + evalExpression + ')')();
                if (!isNaN(result) && isFinite(result)) {
                    const finalVal = result.toFixed(2);
                    if (row.result_value !== finalVal) {
                        row.result_value = finalVal;
                        inputEl.value = finalVal;
                        
                        // Force manual render logic for Status styling to avoid infinite loop
                        const rng = row.range || {};
                        inputEl.classList.remove('bg-high', 'bg-low', 'bg-panic');
                        const { statusText, statusClass, inputClass } = computeStatus(finalVal, rng);
                        const statusCell = document.querySelector(`.status-cell[data-idx="${i}"]`);
                        if (statusCell) {
                            statusCell.textContent = statusText;
                            statusCell.className = `text-center status-cell ${statusClass}`;
                        }
                        if (inputClass) inputEl.classList.add(inputClass);
                    }
                }
            } catch (err) {
                console.error("Formula error resolving:", evalExpression, err);
            }
        } else if (!isComplete && inputEl && !row.authorized && inputEl.value !== '') {
            // Drop calculation back to zero natively
            inputEl.value = '';
            row.result_value = '';
            inputEl.classList.remove('bg-high', 'bg-low', 'bg-panic');
            const statusCell = document.querySelector(`.status-cell[data-idx="${i}"]`);
            if (statusCell) {
                statusCell.textContent = '';
                statusCell.className = `text-center status-cell`;
            }
        }
    });
}

// ===========================
// DEVICE CHANGE HANDLER
// ===========================
async function onParentDeviceChange(selectEl, testId, orderId) {
    const deviceId = parseInt(selectEl.value);
    const idx = selectEl.dataset.idx;

    // Update parent's selected device
    if (gridData.grid_rows[parseInt(idx)]) {
        gridData.grid_rows[parseInt(idx)].selected_device_id = deviceId;
    }

    // Find all parameters (children) for this order
    const childrenNodes = document.querySelectorAll(`tr.row-child[data-order-id="${orderId}"]`);
    for (const childTr of childrenNodes) {
        const childIdx = childTr.dataset.idx;
        const childRow = gridData.grid_rows[parseInt(childIdx)];
        if (!childRow) continue;
        childRow.selected_device_id = deviceId;
        
        let deviceName = '—';
        if (childRow.devices) {
            const d = childRow.devices.find(x => x.id === deviceId);
            if (d) deviceName = d.name;
        }
        const devNameCell = document.querySelector(`.child-device-name[data-idx="${childIdx}"]`);
        if (devNameCell) devNameCell.textContent = deviceName;

        try {
            let url = `/api/range-for-device?test_id=${testId}&device_id=${deviceId}&gender=${patientGender}&age=${patientAge}&parameter_id=${childRow.parameter_id}`;
            const resp = await fetch(url);
            const rng = await resp.json();

            childRow.range = rng;

            // Update Unit cell
            const unitCell = document.querySelector(`.unit-cell[data-idx="${childIdx}"]`);
            if (unitCell) unitCell.textContent = rng.unit || '';

            // Update Range cell
            const rangeCell = document.querySelector(`.range-cell[data-idx="${childIdx}"]`);
            if (rangeCell) rangeCell.innerHTML = formatRangeDisplay(rng);

            // Re-validate current result
            const resultInput = document.querySelector(`.result-input[data-idx="${childIdx}"]`);
            if (resultInput) onResultChange(resultInput);

        } catch (err) {
            console.error('Error fetching range for parameter:', err);
        }
    }
}

async function onDeviceChange(selectEl, testId, paramId) {
    const deviceId = parseInt(selectEl.value);
    const idx = selectEl.dataset.idx;

    try {
        let url = `/api/range-for-device?test_id=${testId}&device_id=${deviceId}&gender=${patientGender}&age=${patientAge}`;
        if (paramId) url += `&parameter_id=${paramId}`;

        const resp = await fetch(url);
        const rng = await resp.json();

        // Update the range in gridData
        const rowIdx = parseInt(idx);
        if (gridData.grid_rows[rowIdx]) {
            gridData.grid_rows[rowIdx].range = rng;
            gridData.grid_rows[rowIdx].selected_device_id = deviceId;
        }

        // Update Unit cell
        const unitCell = document.querySelector(`.unit-cell[data-idx="${idx}"]`);
        if (unitCell) unitCell.textContent = rng.unit || '';

        // Update Range cell
        const rangeCell = document.querySelector(`.range-cell[data-idx="${idx}"]`);
        if (rangeCell) rangeCell.innerHTML = formatRangeDisplay(rng);

        // Re-validate current result
        const resultInput = document.querySelector(`.result-input[data-idx="${idx}"]`);
        if (resultInput) onResultChange(resultInput);

    } catch (err) {
        console.error('Error fetching range:', err);
    }
}

// ===========================
// DOUBLE AUTH ACTIONS
// ===========================
function doubleAuthorizeOrder(orderId) {
    let inputs = [];
    const parentRow = document.querySelector(`tr.row-parent[data-order-id="${orderId}"]`);
    if (parentRow) {
        const childRows = document.querySelectorAll(`tr.row-child[data-order-id="${orderId}"]`);
        childRows.forEach(cr => {
            const inp = cr.querySelector('.result-input');
            if (inp) inputs.push(inp);
        });
    } else {
        const standaloneRow = document.querySelector(`tr.row-standalone[data-order-id="${orderId}"]`);
        if (standaloneRow) {
            const inp = standaloneRow.querySelector('.result-input');
            if (inp) inputs.push(inp);
        }
    }
    
    if (inputs.length > 0 && !inputs.some(inp => inp.value && inp.value.trim() !== '')) {
        showNotification('Please enter the result to AUTH', 'error');
        return;
    }

    showNotification('Processing...', 'info');
    fetch(`/api/double-auth/authorize/${orderId}`, { method: 'POST' })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            showNotification(data.message, 'success');
            loadGridData();
        } else showNotification(data.error || data.message, 'error');
    }).catch(e => showNotification('Error communicating with server', 'error'));
}

async function doubleAuthorizeAll() {
    let pendingOrders = [];
    gridData.grid_rows.forEach(r => {
        if ((r.type === 'standalone' || r.type === 'parent') && r.authorized && !r.double_authorized) {
            pendingOrders.push(r.order_id);
        }
    });

    if (pendingOrders.length === 0) {
        showNotification('No tests pending double authorization.', 'info');
        return;
    }

    const emptyOrders = pendingOrders.filter(orderId => {
        let inputs = [];
        const parentRow = document.querySelector(`tr.row-parent[data-order-id="${orderId}"]`);
        if (parentRow) {
            const childRows = document.querySelectorAll(`tr.row-child[data-order-id="${orderId}"]`);
            childRows.forEach(cr => {
                const inp = cr.querySelector('.result-input');
                if (inp) inputs.push(inp);
            });
        } else {
            const standaloneRow = document.querySelector(`tr.row-standalone[data-order-id="${orderId}"]`);
            if (standaloneRow) {
                const inp = standaloneRow.querySelector('.result-input');
                if (inp) inputs.push(inp);
            }
        }
        return inputs.length > 0 && !inputs.some(inp => inp.value && inp.value.trim() !== '');
    });

    if (emptyOrders.length > 0) {
        showNotification('Please enter the result for all pending tests before double authorizing.', 'error');
        return;
    }

    showNotification(`Processing ${pendingOrders.length} tests...`, 'info');
    
    let successes = 0;
    for (let orderId of pendingOrders) {
        try {
            const res = await fetch(`/api/double-auth/authorize/${orderId}`, { method: 'POST' });
            const data = await res.json();
            if (data.success) successes++;
        } catch (e) {
            console.error(e);
        }
    }
    
    if (successes < pendingOrders.length) {
        showNotification(`Finished: ${successes} successful, ${pendingOrders.length - successes} failed.`, 'error');
    } else {
        showNotification(`Successfully Double Authorized ${successes} test(s).`, 'success');
    }
    
    loadGridData();
}

function rerunOrderDA(orderId) {
    showNotification('Processing...', 'info');
    fetch(`/api/double-auth/rerun/${orderId}`, { method: 'POST' })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            showNotification(data.message, 'success');
            loadGridData();
        } else showNotification(data.error || data.message, 'error');
    }).catch(e => showNotification('Error communicating with server', 'error'));
}

let currentUnauthOrderId = null;

function unauthOrder(orderId, testName) {
    currentUnauthOrderId = orderId;
    document.getElementById('unauthTestName').textContent = 'Test: ' + (testName || 'Unknown');
    document.getElementById('unauthReasonInput').value = '';
    document.getElementById('unauthError').classList.add('hidden');
    document.getElementById('btnSubmitUnauth').textContent = 'Submit UnAUTH';
    document.getElementById('btnSubmitUnauth').disabled = false;
    
    const modal = document.getElementById('unauthReasonModal');
    const content = document.getElementById('unauthModalContent');
    modal.classList.remove('hidden');
    setTimeout(() => {
        content.classList.remove('scale-95', 'opacity-0');
        content.classList.add('scale-100', 'opacity-100');
        document.getElementById('unauthReasonInput').focus();
    }, 10);
}

function closeUnauthModal() {
    const modal = document.getElementById('unauthReasonModal');
    const content = document.getElementById('unauthModalContent');
    content.classList.remove('scale-100', 'opacity-100');
    content.classList.add('scale-95', 'opacity-0');
    setTimeout(() => {
        modal.classList.add('hidden');
    }, 200);
}

function submitUnauth() {
    const reason = document.getElementById('unauthReasonInput').value.trim();
    if(!reason) {
        document.getElementById('unauthError').classList.remove('hidden');
        document.getElementById('unauthReasonInput').focus();
        return;
    }
    
    document.getElementById('btnSubmitUnauth').textContent = 'Processing...';
    document.getElementById('btnSubmitUnauth').disabled = true;
    
    fetch(`/api/double-auth/unauth/${currentUnauthOrderId}`, { 
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ reason: reason })
    })
    .then(res => res.json())
    .then(data => {
        if(data.success) {
            showNotification(data.message, 'success');
            closeUnauthModal();
            loadGridData();
        } else {
            showNotification('Error: ' + data.message, 'error');
            document.getElementById('btnSubmitUnauth').disabled = false;
            document.getElementById('btnSubmitUnauth').textContent = 'Submit UnAUTH';
        }
    })
    .catch(e => {
        showNotification('Error communicating with server', 'error');
        document.getElementById('btnSubmitUnauth').disabled = false;
        document.getElementById('btnSubmitUnauth').textContent = 'Submit UnAUTH';
    });
}

// ===========================
// STATS
// ===========================
function updateStats() {
    const inputs = document.querySelectorAll('.result-input');
    let filled = 0, total = 0;
    inputs.forEach(inp => {
        if (inp.type === 'file') return;
        total++;
        if (inp.value && inp.value.trim()) filled++;
    });
    const el = document.getElementById('resultStats');
    if (el) el.textContent = `${filled} / ${total} results entered`;
}

// ===========================
// NOTIFICATION
// ===========================
function showNotification(msg, type) {
    const div = document.createElement('div');
    div.className = `fixed top-5 right-5 z-50 px-5 py-3 rounded-lg shadow-lg text-white text-sm font-medium transition-all`;
    div.style.animation = 'slideIn 0.3s ease-out';
    if (type === 'success') div.classList.add('bg-green-600');
    else if (type === 'error') div.classList.add('bg-red-600');
    else div.classList.add('bg-indigo-600');
    div.textContent = msg;
    document.body.appendChild(div);
    setTimeout(() => { div.style.opacity = '0'; setTimeout(() => div.remove(), 300); }, 3000);
}

// ===========================
// UTILITIES
// ===========================
function escHtml(str) {
    if (!str) return '';
    const div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
}
function escAttr(str) {
    if (!str) return '';
    return String(str).replace(/"/g, '&quot;').replace(/'/g, '&#39;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

// ===========================
// INIT
// ===========================
document.addEventListener('DOMContentLoaded', function() {
    loadGridData();
});

// ===========================
// VIEW PARAGRAPHS
// ===========================

function viewParagraph(idx) {
    const row = gridData.grid_rows[idx];
    if (!row) return;
    
    const content = row.result_value || '<p class="text-slate-500 italic">No content</p>';
    document.getElementById('viewParagraphContent').innerHTML = content;
    
    const modal = document.getElementById('viewParagraphModal');
    const modalContent = document.getElementById('viewParagraphModalContent');
    modal.classList.remove('hidden');
    setTimeout(() => {
        modal.classList.remove('opacity-0');
        modalContent.classList.remove('scale-95', 'opacity-0');
        modalContent.classList.add('scale-100', 'opacity-100');
    }, 10);
}

function closeViewParagraph() {
    const modal = document.getElementById('viewParagraphModal');
    const modalContent = document.getElementById('viewParagraphModalContent');
    modal.classList.remove('opacity-100');
    modalContent.classList.remove('scale-100', 'opacity-100');
    modalContent.classList.add('scale-95', 'opacity-0');
    setTimeout(() => {
        modal.classList.add('hidden');
    }, 200);
}

// View Rerun Paragraph
function viewRerunParagraph(idx) {
    const row = gridData.grid_rows[idx];
    if (!row) return;
    
    const content = row.rerun_result || '<p class="text-slate-500 italic">No rerun content</p>';
    document.getElementById('viewRerunParagraphContent').innerHTML = content;
    
    const modal = document.getElementById('viewRerunParagraphModal');
    const modalContent = document.getElementById('viewRerunParagraphModalContent');
    modal.classList.remove('hidden');
    setTimeout(() => {
        modal.classList.remove('opacity-0');
        modalContent.classList.remove('scale-95', 'opacity-0');
        modalContent.classList.add('scale-100', 'opacity-100');
    }, 10);
}

function closeViewRerunParagraph() {
    const modal = document.getElementById('viewRerunParagraphModal');
    const modalContent = document.getElementById('viewRerunParagraphModalContent');
    modal.classList.remove('opacity-100');
    modalContent.classList.remove('scale-100', 'opacity-100');
    modalContent.classList.add('scale-95', 'opacity-0');
    setTimeout(() => {
        modal.classList.add('hidden');
    }, 200);
}
</script>

<!-- UnAUTH Reason Modal -->
<div id="unauthReasonModal" class="hidden fixed inset-0 z-[1000] flex items-center justify-center bg-black/40 backdrop-blur-sm transition-opacity">
    <div class="bg-white rounded-[20px] shadow-2xl w-full max-w-md overflow-hidden transform scale-95 opacity-0 transition-all duration-200" id="unauthModalContent">
        <!-- Header -->
        <div class="bg-red-50/70 px-6 py-5 border-b border-red-100 flex flex-col">
            <div class="flex items-center gap-2 text-red-800 font-bold text-lg tracking-tight">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path></svg>
                UnAUTHORISE Test
            </div>
            <div class="text-[#dc2626] text-[13px] font-semibold mt-1" id="unauthTestName">Test: </div>
        </div>
        
        <!-- Body -->
        <div class="p-6 pb-4">
            <label class="block text-slate-700 text-sm font-semibold mb-2">Reason for UnAUTHORISATION <span class="text-red-500">*</span></label>
            <textarea id="unauthReasonInput" rows="3" class="w-full border-[1.5px] border-red-500 rounded-lg p-3 text-slate-700 focus:outline-none focus:ring-[3px] focus:ring-red-100 transition-all resize-none shadow-sm" placeholder="Please enter the reason for un-authorising this test..."></textarea>
            <p id="unauthError" class="text-red-500 text-xs font-semibold mt-1.5 hidden">Reason is required</p>
        </div>
        
        <!-- Footer -->
        <div class="px-6 py-4 bg-white border-t border-slate-100 flex justify-end gap-3 flex-row-reverse pb-6">
            <button onclick="submitUnauth()" id="btnSubmitUnauth" class="px-5 py-2.5 bg-[#ec7c7c] hover:bg-[#e06b6b] text-white font-bold rounded-lg shadow-sm transition-colors text-sm">
                Submit UnAUTH
            </button>
            <button onclick="closeUnauthModal()" class="px-5 py-2.5 bg-white border border-slate-300 hover:bg-slate-50 text-slate-700 font-bold rounded-lg shadow-sm transition-colors text-sm">
                Cancel
            </button>
        </div>
    </div>
</div>

<!-- View Paragraph Modal -->
<div id="viewParagraphModal" class="hidden fixed inset-0 z-[1000] flex items-center justify-center bg-black/40 backdrop-blur-sm transition-opacity opacity-0">
    <div class="bg-white rounded-[20px] shadow-2xl w-full max-w-3xl overflow-hidden transform scale-95 opacity-0 transition-all duration-200" id="viewParagraphModalContent">
        <div class="bg-indigo-50 px-6 py-4 border-b border-indigo-100 flex justify-between items-center">
            <div class="flex items-center gap-2 text-indigo-800 font-bold text-lg">
                <i class="fas fa-file-alt"></i> Paragraph Result
            </div>
            <button onclick="closeViewParagraph()" class="text-indigo-400 hover:text-indigo-600">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        <div class="p-6 max-h-[70vh] overflow-y-auto">
            <div id="viewParagraphContent" class="prose max-w-none text-slate-700"></div>
        </div>
        <div class="px-6 py-4 bg-slate-50 border-t border-slate-100 flex justify-end">
            <button onclick="closeViewParagraph()" class="px-5 py-2.5 bg-white border border-slate-300 hover:bg-slate-50 text-slate-700 font-bold rounded-lg shadow-sm">
                Close
            </button>
        </div>
    </div>
</div>

<!-- View Rerun Paragraph Modal -->
<div id="viewRerunParagraphModal" class="hidden fixed inset-0 z-[1000] flex items-center justify-center bg-black/40 backdrop-blur-sm transition-opacity opacity-0">
    <div class="bg-white rounded-[20px] shadow-2xl w-full max-w-3xl overflow-hidden transform scale-95 opacity-0 transition-all duration-200" id="viewRerunParagraphModalContent">
        <div class="bg-indigo-50 px-6 py-4 border-b border-indigo-100 flex justify-between items-center">
            <div class="flex items-center gap-2 text-indigo-800 font-bold text-lg">
                <i class="fas fa-history"></i> ReRun Paragraph Result
            </div>
            <button onclick="closeViewRerunParagraph()" class="text-indigo-400 hover:text-indigo-600">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        <div class="p-6 max-h-[70vh] overflow-y-auto">
            <div id="viewRerunParagraphContent" class="prose max-w-none text-slate-700"></div>
        </div>
        <div class="px-6 py-4 bg-slate-50 border-t border-slate-100 flex justify-end">
            <button onclick="closeViewRerunParagraph()" class="px-5 py-2.5 bg-white border border-slate-300 hover:bg-slate-50 text-slate-700 font-bold rounded-lg shadow-sm">
                Close
            </button>
        </div>
    </div>
</div>

{% endblock %}