File size: 62,899 Bytes
7c60b26
 
 
 
 
6daf9bc
7c60b26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4807d36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c60b26
 
 
4807d36
 
 
 
 
 
 
7c60b26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
013c80d
721621d
 
 
7c60b26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4807d36
7c60b26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
721621d
7c60b26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
721621d
7c60b26
 
4807d36
 
 
 
 
 
 
721621d
4807d36
 
7c60b26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
721621d
 
7c60b26
 
 
 
 
 
 
 
 
 
 
 
 
 
721621d
 
 
 
 
 
 
 
 
 
 
 
 
7c60b26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bf9097
7c60b26
 
 
8bf9097
7c60b26
 
 
 
 
 
 
 
 
 
 
 
4807d36
7c60b26
 
 
4807d36
7c60b26
 
 
4807d36
7c60b26
 
 
4807d36
 
 
 
 
7c60b26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61ff2de
7c60b26
61ff2de
7c60b26
 
 
61ff2de
7c60b26
61ff2de
7c60b26
 
 
61ff2de
7c60b26
61ff2de
 
7c60b26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61ff2de
7c60b26
61ff2de
7c60b26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4807d36
7c60b26
 
4807d36
 
 
 
 
 
 
 
7c60b26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4807d36
 
 
 
 
 
7c60b26
 
 
 
 
4807d36
 
 
 
 
 
 
7c60b26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Система учёта пациентов</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap');
        
        body {
            font-family: 'Roboto', sans-serif;
            background-color: #111827;
            color: #e5e7eb;
        }
        
        .monospace {
            font-family: 'Courier New', Courier, monospace;
        }
        
        .modal {
            transition: opacity 0.3s ease;
        }
        
        .patient-card {
            transition: all 0.3s ease;
        }
        
        .patient-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
        }
        
        .status-active {
            color: white;
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            padding: 2px 8px;
            border-radius: 12px;
            display: inline-block;
            font-weight: 500;
            box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }
        
        .status-warning {
            color: white;
            background: linear-gradient(135deg, #eab308 0%, #ca8a04 100%);
            padding: 2px 8px;
            border-radius: 12px;
            display: inline-block;
            font-weight: 500;
            box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }
        
        .status-inactive {
            color: white;
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            padding: 2px 8px;
            border-radius: 12px;
            display: inline-block;
            font-weight: 500;
            box-shadow: 0 1px 2px rgba(0,0,0,0.1);
        }
        
        /* Custom scrollbar */
        ::-webkit-scrollbar {
            width: 6px;
        }
        
        ::-webkit-scrollbar-track {
            background: #1f2937;
        }
        
        ::-webkit-scrollbar-thumb {
            background: #4b5563;
            border-radius: 3px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: #6b7280;
        }
        
        /* Animation for new tag button */
        @keyframes pulse {
            0% {
                transform: scale(1);
            }
            50% {
                transform: scale(1.05);
            }
            100% {
                transform: scale(1);
            }
        }
        
        .pulse {
            animation: pulse 2s infinite;
        }
    </style>
</head>
<body class="min-h-screen">
    <div class="container mx-auto px-4 py-6 max-w-3xl">
        <!-- Header -->
        <header class="mb-6">
            <h1 class="text-2xl font-bold text-center text-gray-100">Система учёта пациентов</h1>
            <div class="text-center text-gray-400 text-sm mb-2">
                <span id="currentDate" class="bg-gray-700/50 px-3 py-1 rounded-full"></span>
            </div>
            <div id="newTagAlert" class="hidden mt-4">
                <button id="newTagBtn" class="w-full py-2 px-4 bg-red-600 hover:bg-red-700 text-white font-bold rounded-lg shadow-md pulse">
                    ⚠️ Обнаружена новая метка
                </button>
            </div>
        </header>

        <!-- Demo mode toggle -->
        <div class="flex justify-end mb-4">
            <label class="inline-flex items-center cursor-pointer">
                <input type="checkbox" id="demoModeToggle" class="sr-only peer" checked>
                <div class="relative w-11 h-6 bg-gray-700 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"></div>
                <span class="ms-3 text-sm font-medium text-gray-300">DEMO MODE</span>
            </label>
        </div>

        <!-- Filters -->
        <div class="bg-gray-800 rounded-lg p-4 mb-6 shadow-lg">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label for="searchInput" class="block text-sm font-medium text-gray-300 mb-1">Поиск по фамилии</label>
                    <input type="text" id="searchInput" placeholder="Введите фамилию..." class="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-md text-gray-200 focus:outline-none focus:ring-1 focus:ring-blue-500">
                </div>
                <div>
                    <label for="statusFilter" class="block text-sm font-medium text-gray-300 mb-1">Статус</label>
                    <select id="statusFilter" class="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-md text-gray-200 focus:outline-none focus:ring-1 focus:ring-blue-500">
                        <option value="all">Все</option>
                        <option value="Активен">Активен</option>
                        <option value="Пропустил 1 день">Пропустил 1 день</option>
                        <option value="Пропустил 2 дня">Пропустил 2 дня</option>
                    </select>
                </div>
                <div>
                    <label for="admissionDateFilter" class="block text-sm font-medium text-gray-300 mb-1">Дата поступления</label>
                    <input type="date" id="admissionDateFilter" class="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-md text-gray-200 focus:outline-none focus:ring-1 focus:ring-blue-500">
                </div>
                <div>
                    <label for="dischargeDateFilter" class="block text-sm font-medium text-gray-300 mb-1">Дата выписки</label>
                    <input type="date" id="dischargeDateFilter" class="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-md text-gray-200 focus:outline-none focus:ring-1 focus:ring-blue-500">
                </div>
            </div>
            <div class="mt-4 flex justify-end">
                <button id="resetFiltersBtn" class="px-4 py-2 bg-gray-600 hover:bg-gray-500 text-white rounded-md text-sm">
                    Сбросить фильтры
                </button>
            </div>
        </div>

        <!-- Patients list -->
        <div class="bg-gray-800 rounded-lg shadow-lg p-4">
            <div id="patientsGrid" class="grid grid-cols-1 gap-4">
                <!-- Patients will be loaded here as cards -->
            </div>
            <div id="loadingIndicator" class="p-4 text-center text-gray-400">
                <i class="fas fa-spinner fa-spin mr-2"></i> Загрузка данных...
            </div>
            <div id="noPatientsFound" class="hidden p-4 text-center text-gray-400">
                Пациенты не найдены
            </div>
        </div>

        <!-- Demo mode controls -->
        <div id="demoControls" class="mt-6 bg-gray-800 rounded-lg p-4 shadow-lg">
            <h3 class="text-lg font-medium text-gray-300 mb-3">Демо-контролы</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label for="demoUidInput" class="block text-sm font-medium text-gray-300 mb-1">UID метки</label>
                    <input type="text" id="demoUidInput" value="A1B2C3D4" class="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-md text-gray-200 focus:outline-none focus:ring-1 focus:ring-blue-500 monospace">
                </div>
                <div class="flex items-end">
                    <button id="simulateTagBtn" class="w-full px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-md">
                        Эмулировать метку
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Modals -->
    
    <!-- Edit Patient Modal -->
    <div id="editPatientModal" class="fixed inset-0 z-50 hidden overflow-y-auto">
        <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                <div class="absolute inset-0 bg-gray-900 opacity-75"></div>
            </div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="inline-block align-bottom bg-gray-800 rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <div class="px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <h3 class="text-lg leading-6 font-medium text-gray-100 mb-4" id="editPatientModalTitle">Редактировать пациента</h3>
                    <div class="space-y-4">
                        <div>
                            <label for="editName" class="block text-sm font-medium text-gray-300">ФИО</label>
                            <input type="text" id="editName" class="mt-1 block w-full bg-gray-700 border border-gray-600 rounded-md text-gray-200 px-3 py-2 focus:outline-none focus:ring-1 focus:ring-blue-500">
                        </div>
                        <div>
                            <label for="editHist" class="block text-sm font-medium text-gray-300">№ истории</label>
                            <input type="text" id="editHist" class="mt-1 block w-full bg-gray-700 border border-gray-600 rounded-md text-gray-200 px-3 py-2 focus:outline-none focus:ring-1 focus:ring-blue-500">
                        </div>
                        <div>
                            <label for="editDischarge" class="block text-sm font-medium text-gray-300">Дата выписки</label>
                            <input type="date" id="editDischarge" class="mt-1 block w-full bg-gray-700 border border-gray-600 rounded-md text-gray-200 px-3 py-2 focus:outline-none focus:ring-1 focus:ring-blue-500">
                        </div>
                    </div>
                </div>
                <div class="bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button type="button" id="savePatientBtn" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm">
                        Сохранить
                    </button>
                    <button type="button" id="cancelEditBtn" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-600 shadow-sm px-4 py-2 bg-gray-600 text-base font-medium text-gray-100 hover:bg-gray-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                        Отмена
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- New Tag Modal -->
    <div id="newTagModal" class="fixed inset-0 z-50 hidden overflow-y-auto">
        <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                <div class="absolute inset-0 bg-gray-900 opacity-75"></div>
            </div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="inline-block align-bottom bg-gray-800 rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <div class="px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <h3 class="text-lg leading-6 font-medium text-gray-100 mb-4">Обнаружена новая метка: <span id="newTagUid" class="font-mono text-blue-400"></span></h3>
                    <div class="space-y-4">
                        <button id="newPatientBtn" class="w-full text-left p-4 bg-gray-700 hover:bg-gray-600 rounded-lg">
                            <h4 class="font-medium text-gray-100">Новый пациент</h4>
                            <p class="text-sm text-gray-400">Создать нового пациента и привязать метку</p>
                        </button>
                        <button id="assignPatientBtn" class="w-full text-left p-4 bg-gray-700 hover:bg-gray-600 rounded-lg">
                            <h4 class="font-medium text-gray-100">Присвоить существующему</h4>
                            <p class="text-sm text-gray-400">Найти пациента и привязать метку</p>
                        </button>
                    </div>
                </div>
                <div class="bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button type="button" id="cancelNewTagBtn" class="w-full inline-flex justify-center rounded-md border border-gray-600 shadow-sm px-4 py-2 bg-gray-600 text-base font-medium text-gray-100 hover:bg-gray-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 sm:ml-3 sm:w-auto sm:text-sm">
                        Отмена
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- New Patient Modal -->
    <div id="newPatientModal" class="fixed inset-0 z-50 hidden overflow-y-auto">
        <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                <div class="absolute inset-0 bg-gray-900 opacity-75"></div>
            </div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="inline-block align-bottom bg-gray-800 rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <div class="px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <h3 class="text-lg leading-6 font-medium text-gray-100 mb-4">Новый пациент</h3>
                    <div class="space-y-4">
                        <div>
                            <label for="newName" class="block text-sm font-medium text-gray-300">ФИО</label>
                            <input type="text" id="newName" class="mt-1 block w-full bg-gray-700 border border-gray-600 rounded-md text-gray-200 px-3 py-2 focus:outline-none focus:ring-1 focus:ring-blue-500">
                        </div>
                        <div>
                            <label for="newHist" class="block text-sm font-medium text-gray-300">№ истории</label>
                            <input type="text" id="newHist" class="mt-1 block w-full bg-gray-700 border border-gray-600 rounded-md text-gray-200 px-3 py-2 focus:outline-none focus:ring-1 focus:ring-blue-500">
                        </div>
                        <div>
                            <label for="newAdmission" class="block text-sm font-medium text-gray-300">Дата поступления</label>
                            <input type="date" id="newAdmission" class="mt-1 block w-full bg-gray-700 border border-gray-600 rounded-md text-gray-200 px-3 py-2 focus:outline-none focus:ring-1 focus:ring-blue-500">
                        </div>
                    </div>
                </div>
                <div class="bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button type="button" id="saveNewPatientBtn" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm">
                        Сохранить
                    </button>
                    <button type="button" id="cancelNewPatientBtn" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-600 shadow-sm px-4 py-2 bg-gray-600 text-base font-medium text-gray-100 hover:bg-gray-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                        Отмена
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Assign Patient Modal -->
    <div id="assignPatientModal" class="fixed inset-0 z-50 hidden overflow-y-auto">
        <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                <div class="absolute inset-0 bg-gray-900 opacity-75"></div>
            </div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="inline-block align-bottom bg-gray-800 rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <div class="px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <h3 class="text-lg leading-6 font-medium text-gray-100 mb-4">Присвоить метку <span id="assignTagUid" class="font-mono text-blue-400"></span></h3>
                    <div class="mb-4">
                        <label for="assignSearch" class="block text-sm font-medium text-gray-300 mb-1">Поиск пациента</label>
                        <input type="text" id="assignSearch" placeholder="Введите фамилию или № истории..." class="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-md text-gray-200 focus:outline-none focus:ring-1 focus:ring-blue-500">
                    </div>
                    <div class="max-h-60 overflow-y-auto">
                        <table class="min-w-full divide-y divide-gray-700">
                            <thead class="bg-gray-700">
                                <tr>
                                    <th scope="col" class="px-4 py-2 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">ФИО</th>
                                    <th scope="col" class="px-4 py-2 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">№ истории</th>
                                    <th scope="col" class="px-4 py-2 text-left text-xs font-medium text-gray-300 uppercase tracking-wider">Выбрать</th>
                                </tr>
                            </thead>
                            <tbody id="assignPatientsList" class="bg-gray-800 divide-y divide-gray-700">
                                <!-- Patients will be loaded here -->
                            </tbody>
                        </table>
                        <div id="noAssignPatientsFound" class="hidden p-4 text-center text-gray-400">
                            Пациенты не найдены
                        </div>
                    </div>
                </div>
                <div class="bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button type="button" id="cancelAssignBtn" class="w-full inline-flex justify-center rounded-md border border-gray-600 shadow-sm px-4 py-2 bg-gray-600 text-base font-medium text-gray-100 hover:bg-gray-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 sm:ml-3 sm:w-auto sm:text-sm">
                        Отмена
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Confirm Assign Modal -->
    <div id="confirmAssignModal" class="fixed inset-0 z-50 hidden overflow-y-auto">
        <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                <div class="absolute inset-0 bg-gray-900 opacity-75"></div>
            </div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="inline-block align-bottom bg-gray-800 rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <div class="px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <h3 class="text-lg leading-6 font-medium text-gray-100 mb-4">Подтверждение</h3>
                    <p class="text-gray-300 mb-4">Присвоить метку <span id="confirmTagUid" class="font-mono text-blue-400"></span> пациенту <span id="confirmPatientName" class="font-medium"></span>?</p>
                    <div class="bg-gray-700 p-3 rounded-md">
                        <p class="text-sm text-gray-300">№ истории: <span id="confirmPatientHist" class="font-mono"></span></p>
                    </div>
                </div>
                <div class="bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button type="button" id="confirmAssignBtn" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm">
                        Подтвердить
                    </button>
                    <button type="button" id="cancelConfirmAssignBtn" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-600 shadow-sm px-4 py-2 bg-gray-600 text-base font-medium text-gray-100 hover:bg-gray-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                        Отмена
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Visit Confirmation Modal -->
    <div id="visitConfirmationModal" class="fixed inset-0 z-50 hidden overflow-y-auto">
        <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div class="fixed inset-0 transition-opacity" aria-hidden="true">
                <div class="absolute inset-0 bg-gray-900 opacity-75"></div>
            </div>
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            <div class="inline-block align-bottom bg-gray-800 rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
                <div class="px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
                    <h3 class="text-lg leading-6 font-medium text-gray-100 mb-4">Посещение пациента</h3>
                    <p class="text-gray-300 mb-4">Метка <span id="visitTagUid" class="font-mono text-blue-400"></span> уже привязана к пациенту <span id="visitPatientName" class="font-medium"></span>.</p>
                    <div class="bg-gray-700 p-3 rounded-md mb-4">
                        <p class="text-sm text-gray-300">№ истории: <span id="visitPatientHist" class="font-mono"></span></p>
                        <p class="text-sm text-gray-300">Последнее посещение: <span id="visitPatientLastVisit" class="font-mono"></span></p>
                    </div>
                    <p class="text-gray-300">Зарегистрировать посещение сейчас?</p>
                </div>
                <div class="bg-gray-700 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
                    <button type="button" id="confirmVisitBtn" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm">
                        Подтвердить
                    </button>
                    <button type="button" id="cancelVisitBtn" class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-600 shadow-sm px-4 py-2 bg-gray-600 text-base font-medium text-gray-100 hover:bg-gray-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm">
                        Отмена
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Demo data
        const demoPatients = [
            {
                id: 1,
                name: "Иванов И.И.",
                hist: "12345",
                uid: "3A63D805",
                admission: "2025-08-01",
                discharge: "",
                lastVisit: "2025-08-25",
                status: "Активен"
            },
            {
                id: 2,
                name: "Петров П.П.",
                hist: "67890",
                uid: "72FFA1B4",
                admission: "2025-08-05",
                discharge: "",
                lastVisit: "2025-08-24",
                status: "Активен"
            },
            {
                id: 3,
                name: "Сидоров С.С.",
                hist: "54321",
                uid: "5C89E1F2",
                admission: "2025-08-10",
                discharge: "2025-08-20",
                lastVisit: "2025-08-20",
                status: "Пропустил 2 дня"
            },
            {
                id: 4,
                name: "Кузнецов К.К.",
                hist: "98765",
                uid: "A1B2C3D4",
                admission: "2025-07-15",
                discharge: "",
                lastVisit: "2025-08-26",
                status: "Активен"
            },
            {
                id: 5,
                name: "Смирнова А.А.",
                hist: "13579",
                uid: "9D4F7B12",
                admission: "2025-08-15",
                discharge: "",
                lastVisit: "2025-08-25",
                status: "Пропустил 1 день"
            },
            {
                id: 6,
                name: "Васильев В.В.",
                hist: "24680",
                uid: "E6F5A3C8",
                admission: "2025-08-10",
                discharge: "",
                lastVisit: "",
                status: "Пропустил 2 дня"
            }
        ];

        // State
        let patients = [];
        let filteredPatients = [];
        let currentPatientId = null;
        let currentUid = null;
        let demoMode = true;
        let pollingInterval = null;
        let lastUid = null;

        // DOM elements
        const patientsTableBody = document.getElementById('patientsTableBody');
        const loadingIndicator = document.getElementById('loadingIndicator');
        const noPatientsFound = document.getElementById('noPatientsFound');
        const searchInput = document.getElementById('searchInput');
        const statusFilter = document.getElementById('statusFilter');
        const admissionDateFilter = document.getElementById('admissionDateFilter');
        const dischargeDateFilter = document.getElementById('dischargeDateFilter');
        const resetFiltersBtn = document.getElementById('resetFiltersBtn');
        const newTagAlert = document.getElementById('newTagAlert');
        const newTagBtn = document.getElementById('newTagBtn');
        const demoModeToggle = document.getElementById('demoModeToggle');
        const demoControls = document.getElementById('demoControls');
        const demoUidInput = document.getElementById('demoUidInput');
        const simulateTagBtn = document.getElementById('simulateTagBtn');

        // Modals
        const editPatientModal = document.getElementById('editPatientModal');
        const editName = document.getElementById('editName');
        const editHist = document.getElementById('editHist');
        const editDischarge = document.getElementById('editDischarge');
        const savePatientBtn = document.getElementById('savePatientBtn');
        const cancelEditBtn = document.getElementById('cancelEditBtn');

        const newTagModal = document.getElementById('newTagModal');
        const newTagUid = document.getElementById('newTagUid');
        const newPatientBtn = document.getElementById('newPatientBtn');
        const assignPatientBtn = document.getElementById('assignPatientBtn');
        const cancelNewTagBtn = document.getElementById('cancelNewTagBtn');

        const newPatientModal = document.getElementById('newPatientModal');
        const newName = document.getElementById('newName');
        const newHist = document.getElementById('newHist');
        const newAdmission = document.getElementById('newAdmission');
        const saveNewPatientBtn = document.getElementById('saveNewPatientBtn');
        const cancelNewPatientBtn = document.getElementById('cancelNewPatientBtn');

        const assignPatientModal = document.getElementById('assignPatientModal');
        const assignTagUid = document.getElementById('assignTagUid');
        const assignSearch = document.getElementById('assignSearch');
        const assignPatientsList = document.getElementById('assignPatientsList');
        const noAssignPatientsFound = document.getElementById('noAssignPatientsFound');
        const cancelAssignBtn = document.getElementById('cancelAssignBtn');

        const confirmAssignModal = document.getElementById('confirmAssignModal');
        const confirmTagUid = document.getElementById('confirmTagUid');
        const confirmPatientName = document.getElementById('confirmPatientName');
        const confirmPatientHist = document.getElementById('confirmPatientHist');
        const confirmAssignBtn = document.getElementById('confirmAssignBtn');
        const cancelConfirmAssignBtn = document.getElementById('cancelConfirmAssignBtn');

        const visitConfirmationModal = document.getElementById('visitConfirmationModal');
        const visitTagUid = document.getElementById('visitTagUid');
        const visitPatientName = document.getElementById('visitPatientName');
        const visitPatientHist = document.getElementById('visitPatientHist');
        const visitPatientLastVisit = document.getElementById('visitPatientLastVisit');
        const confirmVisitBtn = document.getElementById('confirmVisitBtn');
        const cancelVisitBtn = document.getElementById('cancelVisitBtn');

        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            // Update current date
            updateCurrentDate();
            // Load patients
            loadPatients();
            
            // Set up event listeners
            setupEventListeners();
            
            // Start polling for new UIDs
            startPolling();
            
            // Set today's date as default for new patient admission
            const today = new Date().toISOString().split('T')[0];
            newAdmission.value = today;
        });

        function updateCurrentDate() {
            const now = new Date();
            const options = { 
                weekday: 'long', 
                year: 'numeric', 
                month: 'long', 
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            };
            document.getElementById('currentDate').textContent = now.toLocaleDateString('ru-RU', options);
        }

        function setupEventListeners() {
            // Filter controls
            searchInput.addEventListener('input', applyFilters);
            statusFilter.addEventListener('change', applyFilters);
            admissionDateFilter.addEventListener('change', applyFilters);
            dischargeDateFilter.addEventListener('change', applyFilters);
            resetFiltersBtn.addEventListener('click', resetFilters);
            
            // Demo mode toggle
            demoModeToggle.addEventListener('change', toggleDemoMode);
            
            // New tag button
            newTagBtn.addEventListener('click', showNewTagModal);
            
            // Demo controls
            simulateTagBtn.addEventListener('click', simulateTag);
            
            // Edit patient modal
            savePatientBtn.addEventListener('click', savePatient);
            cancelEditBtn.addEventListener('click', () => hideModal(editPatientModal));
            
            // New tag modal
            newPatientBtn.addEventListener('click', showNewPatientModal);
            assignPatientBtn.addEventListener('click', showAssignPatientModal);
            cancelNewTagBtn.addEventListener('click', () => hideModal(newTagModal));
            
            // New patient modal
            saveNewPatientBtn.addEventListener('click', saveNewPatient);
            cancelNewPatientBtn.addEventListener('click', () => hideModal(newPatientModal));
            
            // Assign patient modal
            assignSearch.addEventListener('input', filterAssignPatients);
            cancelAssignBtn.addEventListener('click', () => hideModal(assignPatientModal));
            
            // Confirm assign modal
            confirmAssignBtn.addEventListener('click', assignTagToPatient);
            cancelConfirmAssignBtn.addEventListener('click', () => hideModal(confirmAssignModal));
            
            // Visit confirmation modal
            confirmVisitBtn.addEventListener('click', logVisit);
            cancelVisitBtn.addEventListener('click', () => hideModal(visitConfirmationModal));
        }

        function loadPatients() {
            if (demoMode) {
                // Use demo data
                patients = [...demoPatients];
                renderPatients(patients);
                loadingIndicator.classList.add('hidden');
            } else {
                // Fetch from API
                fetch('/api/patients')
                    .then(response => response.json())
                    .then(data => {
                        patients = data.patients;
                        renderPatients(patients);
                        loadingIndicator.classList.add('hidden');
                    })
                    .catch(error => {
                        console.error('Error loading patients:', error);
                        // Fallback to demo data if API fails
                        patients = [...demoPatients];
                        renderPatients(patients);
                        loadingIndicator.classList.add('hidden');
                    });
            }
        }

        function renderPatients(patientsToRender) {
            const patientsGrid = document.getElementById('patientsGrid');
            patientsGrid.innerHTML = '';
            
            if (patientsToRender.length === 0) {
                noPatientsFound.classList.remove('hidden');
                return;
            }
            
            noPatientsFound.classList.add('hidden');
            
            patientsToRender.forEach(patient => {
                const card = document.createElement('div');
                card.className = `patient-card bg-gray-700 rounded-lg p-4 shadow-md hover:shadow-lg transition-shadow cursor-pointer ${lastUid && patient.uid === lastUid ? 'border-2 border-blue-500' : ''}`;
                card.dataset.id = patient.id;
                
                card.innerHTML = `
                    <div class="flex items-start mb-3 gap-2">
                        <button class="edit-btn text-gray-400 hover:text-blue-400" data-id="${patient.id}">
                            <i class="fas fa-edit"></i>
                        </button>
                        <h3 class="text-lg font-medium text-gray-100 truncate">${patient.name}</h3>
                    </div>
                    <div class="grid grid-cols-2 gap-2 text-sm">
                        <div>
                            <p class="text-gray-400">№ истории:</p>
                            <p class="text-gray-300">${patient.hist}</p>
                        </div>
                        <div>
                            <p class="text-gray-400">UID:</p>
                            <p class="text-gray-300 monospace">${patient.uid || '-'}</p>
                        </div>
                        <div>
                            <p class="text-gray-400">Поступление:</p>
                            <p class="text-gray-300">${formatDate(patient.admission)}</p>
                        </div>
                        <div>
                            <p class="text-gray-400">Выписка:</p>
                            <p class="text-gray-300">${patient.discharge ? formatDate(patient.discharge) : '-'}</p>
                        </div>
                        <div>
                            <p class="text-gray-400">Последнее посещение:</p>
                            <p class="text-gray-300">${patient.lastVisit ? formatDate(patient.lastVisit) : '-'}</p>
                        </div>
                        <div>
                            <p class="text-gray-400">Статус:</p>
                            <span class="${
                              patient.status === 'Активен' ? 'status-active' : 
                              patient.status === 'Пропустил 1 день' ? 'status-warning' : 
                              'status-inactive'
                            }">${patient.status}</span>
                        </div>
                    </div>
                `;
                
                patientsGrid.appendChild(card);
            });
            
            // Add event listeners to edit buttons
            document.querySelectorAll('.edit-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    e.stopPropagation();
                    const patientId = parseInt(btn.dataset.id);
                    showEditPatientModal(patientId);
                });
            });
            
            // Add click event to cards
            document.querySelectorAll('.patient-card').forEach(card => {
                card.addEventListener('click', () => {
                    // Remove active class from all cards
                    document.querySelectorAll('.patient-card').forEach(c => {
                        c.classList.remove('border-blue-500');
                    });
                    
                    // Add active class to clicked card
                    card.classList.add('border-blue-500');
                    
                    // Store current patient ID
                    currentPatientId = parseInt(card.dataset.id);
                });
            });
        }

        function applyFilters() {
            const searchTerm = searchInput.value.toLowerCase();
            const statusFilterValue = statusFilter.value;
            const admissionDateFilterValue = admissionDateFilter.value;
            const dischargeDateFilterValue = dischargeDateFilter.value;
            
            filteredPatients = patients.filter(patient => {
                // Search by name
                if (searchTerm && !patient.name.toLowerCase().includes(searchTerm)) {
                    return false;
                }
                
                // Filter by status
                if (statusFilterValue !== 'all' && patient.status !== statusFilterValue) {
                    return false;
                }
                
                // Filter by admission date
                if (admissionDateFilterValue && patient.admission !== admissionDateFilterValue) {
                    return false;
                }
                
                // Filter by discharge date
                if (dischargeDateFilterValue) {
                    if (dischargeDateFilterValue && patient.discharge !== dischargeDateFilterValue) {
                        // If patient doesn't have discharge date but we're filtering for empty
                        if (dischargeDateFilterValue === 'empty' && patient.discharge === '') {
                            return true;
                        }
                        return false;
                    }
                }
                
                return true;
            });
            
            renderPatients(filteredPatients);
        }

        function resetFilters() {
            searchInput.value = '';
            statusFilter.value = 'all';
            admissionDateFilter.value = '';
            dischargeDateFilter.value = '';
            applyFilters();
        }

        function toggleDemoMode() {
            demoMode = demoModeToggle.checked;
            demoControls.classList.toggle('hidden', !demoMode);
            
            if (demoMode) {
                // Stop polling
                stopPolling();
                // Reload demo data
                loadPatients();
            } else {
                // Start polling
                startPolling();
                // Load from API
                loadPatients();
            }
        }

        function startPolling() {
            if (demoMode) return;
            
            // Clear any existing interval
            stopPolling();
            
            // Poll every 1.5 seconds
            pollingInterval = setInterval(() => {
                fetch('/api/last_uid')
                    .then(response => response.json())
                    .then(data => {
                        if (data.uid && data.uid !== lastUid) {
                            lastUid = data.uid;
                            handleNewUid(data.uid);
                        }
                    })
                    .catch(error => {
                        console.error('Error polling for last UID:', error);
                    });
            }, 1500);
        }

        function stopPolling() {
            if (pollingInterval) {
                clearInterval(pollingInterval);
                pollingInterval = null;
            }
        }

        function handleNewUid(uid) {
            // Check if this UID is already assigned to a patient
            const patientWithUid = patients.find(p => p.uid === uid);
            
            if (patientWithUid) {
                // UID is already assigned - show visit confirmation
                showVisitConfirmation(patientWithUid, uid);
            } else {
                // New UID - show the alert button
                currentUid = uid;
                newTagAlert.classList.remove('hidden');
            }
        }

        function showNewTagModal() {
            newTagUid.textContent = currentUid;
            showModal(newTagModal);
        }

        function showNewPatientModal() {
            hideModal(newTagModal);
            newName.value = '';
            newHist.value = '';
            // Set today's date as default
            newAdmission.value = new Date().toISOString().split('T')[0];
            showModal(newPatientModal);
        }

        function showAssignPatientModal() {
            hideModal(newTagModal);
            assignTagUid.textContent = currentUid;
            
            // Populate assign patients list with ALL patients
            assignPatientsList.innerHTML = '';
            if (patients.length === 0) {
                noAssignPatientsFound.classList.remove('hidden');
            } else {
                noAssignPatientsFound.classList.add('hidden');
                patients.forEach(patient => {
                    const row = document.createElement('tr');
                    row.className = `hover:bg-gray-700 ${patient.uid ? 'bg-gray-700/50' : ''}`;
                    row.innerHTML = `
                        <td class="px-4 py-2 text-gray-300">${patient.name}</td>
                        <td class="px-4 py-2 text-gray-300">${patient.hist}</td>
                        <td class="px-4 py-2 text-gray-300 monospace text-sm">${patient.uid || 'нет метки'}</td>
                        <td class="px-4 py-2">
                            <button class="select-patient-btn px-3 py-1 ${patient.uid ? 'bg-yellow-600 hover:bg-yellow-500' : 'bg-blue-600 hover:bg-blue-500'} text-white rounded text-sm" data-id="${patient.id}" data-name="${patient.name}" data-hist="${patient.hist}">
                                ${patient.uid ? 'Заменить' : 'Присвоить'}
                            </button>
                        </td>
                    `;
                    assignPatientsList.appendChild(row);
                });
                
                // Add event listeners to select buttons
                document.querySelectorAll('.select-patient-btn').forEach(btn => {
                    btn.addEventListener('click', () => {
                        const patientId = parseInt(btn.dataset.id);
                        const patientName = btn.dataset.name;
                        const patientHist = btn.dataset.hist;
                        
                        showConfirmAssignModal(patientId, patientName, patientHist);
                    });
                });
            }
            
            showModal(assignPatientModal);
        }

        function filterAssignPatients() {
            const searchTerm = assignSearch.value.toLowerCase();
            let hasResults = false;
            
            document.querySelectorAll('#assignPatientsList tr').forEach(row => {
                const name = row.querySelector('td:first-child').textContent.toLowerCase();
                const hist = row.querySelector('td:nth-child(2)').textContent.toLowerCase();
                const uid = row.querySelector('td:nth-child(3)').textContent.toLowerCase();
                
                if (name.includes(searchTerm) || hist.includes(searchTerm) || uid.includes(searchTerm)) {
                    row.classList.remove('hidden');
                    hasResults = true;
                } else {
                    row.classList.add('hidden');
                }
            });
            
            noAssignPatientsFound.classList.toggle('hidden', hasResults);
        }

        function showConfirmAssignModal(patientId, patientName, patientHist) {
            hideModal(assignPatientModal);
            
            currentPatientId = patientId;
            confirmTagUid.textContent = currentUid;
            confirmPatientName.textContent = patientName;
            confirmPatientHist.textContent = patientHist;
            
            showModal(confirmAssignModal);
        }

        function showVisitConfirmation(patient, uid) {
            visitTagUid.textContent = uid;
            visitPatientName.textContent = patient.name;
            visitPatientHist.textContent = patient.hist;
            visitPatientLastVisit.textContent = patient.lastVisit || 'никогда';
            currentPatientId = patient.id;
            
            showModal(visitConfirmationModal);
        }

        function showEditPatientModal(patientId) {
            const patient = patients.find(p => p.id === patientId);
            if (!patient) return;
            
            currentPatientId = patientId;
            editName.value = patient.name;
            editHist.value = patient.hist;
            editDischarge.value = patient.discharge || '';
            
            showModal(editPatientModal);
        }

        function assignTagToPatient() {
            hideModal(confirmAssignModal);
            
            if (demoMode) {
                // Update patient in demo data
                const patientIndex = patients.findIndex(p => p.id === currentPatientId);
                if (patientIndex !== -1) {
                    patients[patientIndex].uid = currentUid;
                    patients[patientIndex].lastVisit = new Date().toISOString().split('T')[0];
                    patients[patientIndex].status = "Активен";
                    
                    // Hide the new tag alert
                    newTagAlert.classList.add('hidden');
                    lastUid = null;
                    
                    // Re-render patients
                    renderPatients(patients);
                    applyFilters();
                }
            } else {
                // Call API to assign tag
                fetch('/api/assign', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        uid: currentUid,
                        patient_id: currentPatientId
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.ok) {
                        // Reload patients
                        loadPatients();
                        // Hide the new tag alert
                        newTagAlert.classList.add('hidden');
                        lastUid = null;
                    }
                })
                .catch(error => {
                    console.error('Error assigning tag:', error);
                });
            }
        }

        function logVisit() {
            hideModal(visitConfirmationModal);
            
            if (demoMode) {
                // Update patient in demo data
                const patientIndex = patients.findIndex(p => p.id === currentPatientId);
                if (patientIndex !== -1) {
                    patients[patientIndex].lastVisit = new Date().toISOString().split('T')[0];
                    patients[patientIndex].status = "Активен";
                    
                    // Re-render patients
                    renderPatients(patients);
                    applyFilters();
                }
            } else {
                // Call API to log visit
                fetch('/api/log_visit', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        uid: lastUid,
                        patient_id: currentPatientId,
                        timestamp: new Date().toISOString()
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.ok) {
                        // Reload patients
                        loadPatients();
                    }
                })
                .catch(error => {
                    console.error('Error logging visit:', error);
                });
            }
        }

        function savePatient() {
            const name = editName.value.trim();
            const hist = editHist.value.trim();
            const discharge = editDischarge.value;
            
            if (!name || !hist) {
                alert('Пожалуйста, заполните все обязательные поля');
                return;
            }
            
            hideModal(editPatientModal);
            
            if (demoMode) {
                // Update patient in demo data
                const patientIndex = patients.findIndex(p => p.id === currentPatientId);
                if (patientIndex !== -1) {
                    patients[patientIndex].name = name;
                    patients[patientIndex].hist = hist;
                    patients[patientIndex].discharge = discharge || '';
                    
                    // Recalculate status if discharge date was added/removed
                    if (discharge) {
                        patients[patientIndex].status = "Пропустил 2 дня";
                    } else {
                        // Check if patient has recent visit
                        const lastVisit = patients[patientIndex].lastVisit;
                        if (!lastVisit) {
                            patients[patientIndex].status = "Пропустил 2 дня";
                        } else {
                            const overdueStatus = isVisitOverdue(lastVisit);
                            if (overdueStatus === 2) {
                                patients[patientIndex].status = "Пропустил 2 дня";
                            } else if (overdueStatus === 1) {
                                patients[patientIndex].status = "Пропустил 1 день";
                            } else {
                                patients[patientIndex].status = "Активен";
                            }
                        }
                    }
                    
                    // Re-render patients
                    renderPatients(patients);
                    applyFilters();
                }
            } else {
                // Call API to update patient
                fetch(`/api/patients/${currentPatientId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        name: name,
                        hist: hist,
                        discharge: discharge || null
                    })
                })
                .then(response => response.json())
                .then(data => {
                    // Reload patients
                    loadPatients();
                })
                .catch(error => {
                    console.error('Error updating patient:', error);
                });
            }
        }

        function saveNewPatient() {
            const name = newName.value.trim();
            const hist = newHist.value.trim();
            const admission = newAdmission.value;
            
            if (!name || !hist || !admission) {
                alert('Пожалуйста, заполните все обязательные поля');
                return;
            }
            
            hideModal(newPatientModal);
            
            if (demoMode) {
                // Create new patient in demo data
                const newId = patients.length > 0 ? Math.max(...patients.map(p => p.id)) + 1 : 1;
                const newPatient = {
                    id: newId,
                    name: name,
                    hist: hist,
                    uid: currentUid,
                    admission: admission,
                    discharge: '',
                    lastVisit: new Date().toISOString().split('T')[0],
                    status: "Активен"
                };
                
                patients.push(newPatient);
                
                // Hide the new tag alert
                newTagAlert.classList.add('hidden');
                lastUid = null;
                
                // Re-render patients
                renderPatients(patients);
                applyFilters();
            } else {
                // Call API to create new patient
                fetch('/api/patients', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        name: name,
                        hist: hist,
                        admission: admission,
                        discharge: null
                    })
                })
                .then(response => response.json())
                .then(data => {
                    // Now assign the UID to this patient
                    return fetch('/api/assign', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            uid: currentUid,
                            patient_id: data.id
                        })
                    });
                })
                .then(response => response.json())
                .then(data => {
                    if (data.ok) {
                        // Reload patients
                        loadPatients();
                        // Hide the new tag alert
                        newTagAlert.classList.add('hidden');
                        lastUid = null;
                    }
                })
                .catch(error => {
                    console.error('Error creating new patient:', error);
                });
            }
        }

        function simulateTag() {
            const uid = demoUidInput.value.trim().toUpperCase();
            if (!uid) {
                alert('Пожалуйста, введите UID метки');
                return;
            }
            
            // Simulate new UID detection
            lastUid = uid;
            handleNewUid(uid);
        }

        function formatDate(isoDate) {
            if (!isoDate) return '';
            const [year, month, day] = isoDate.split('-');
            return `${day}.${month}.${year}`;
        }

        function isVisitOverdue(lastVisitDate) {
            const today = new Date();
            const lastVisit = new Date(lastVisitDate);
            const diffTime = today - lastVisit;
            const diffDays = diffTime / (1000 * 60 * 60 * 24);
            
            if (diffDays > 2) {
                return 2; // Пропустил 2+ дней
            } else if (diffDays > 1) {
                return 1; // Пропустил 1 день
            }
            return 0; // Активен
        }

        function showModal(modal) {
            modal.classList.remove('hidden');
            document.body.classList.add('overflow-hidden');
        }

        function hideModal(modal) {
            modal.classList.add('hidden');
            document.body.classList.remove('overflow-hidden');
        }
    </script>

    <!-- README section (hidden by default) -->
    <div id="readme" class="hidden">
        <h1>Система учёта пациентов с RFID</h1>
        <h2>API Endpoints</h2>
        
        <h3>GET /api/patients</h3>
        <p>Получить список всех пациентов.</p>
        <p><strong>Ответ:</strong></p>
        <pre>{
  "patients": [
    {
      "id": 1,
      "name": "Иванов И.И.",
      "hist": "12345",
      "uid": "3A63D805",
      "admission": "2025-08-01",
      "discharge": "",
      "lastVisit": "2025-08-25",
      "status": "Активен"
    },
    ...
  ]
}</pre>

        <h3>POST /api/patients</h3>
        <p>Создать нового пациента.</p>
        <p><strong>Тело запроса:</strong></p>
        <pre>{
  "name": "...",
  "hist": "...",
  "admission": "YYYY-MM-DD",
  "discharge": "YYYY-MM-DD?"
}</pre>
        <p><strong>Ответ:</strong> Созданный объект пациента (с id).</p>

        <h3>PUT /api/patients/&lt;id&gt;</h3>
        <p>Редактировать пациента.</p>
        <p><strong>Тело запроса:</strong> Поля для изменения (name, hist, discharge).</p>

        <h3>GET /api/last_uid</h3>
        <p>Вернуть последний считанный UID (если есть).</p>
        <p><strong>Ответ:</strong></p>
        <pre>{
  "uid": "72FFA1B4"
}</pre>
        <p>или</p>
        <pre>{
  "uid": null
}</pre>

        <h3>POST /api/assign</h3>
        <p>Присвоить UID существующему пациенту.</p>
        <p><strong>Тело запроса:</strong></p>
        <pre>{
  "uid": "...",
  "patient_id": 123
}</pre>
        <p><strong>Ответ:</strong></p>
        <pre>{
  "ok": true,
  "patient": { ... }
}</pre>

        <h3>POST /api/log_visit</h3>
        <p>Зарегистрировать посещение пациента.</p>
        <p><strong>Тело запроса:</strong></p>
        <pre>{
  "uid": "...",
  "patient_id": 123,
  "timestamp": "ISO"
}</pre>
        <p><strong>Ответ:</strong></p>
        <pre>{
  "ok": true
}</pre>

        <h3>GET /api/time</h3>
        <p>Получить текущую метку времени (опционально).</p>
        <p><strong>Ответ:</strong></p>
        <pre>{
  "iso": "2025-08-26T14:22:00+03:00"
}</pre>

        <h2>Формат лог-файла</h2>
        <p>Одной строкой на событие:</p>
        <pre>TS(iso) UID: &lt;UID&gt; PATIENT_ID: &lt;id&gt; NAME: &lt;ФИО&gt; ACTION: &lt;assigned|visit|created&gt;</pre>
        <p>Пример:</p>
        <pre>2025-08-26T14:22:00+03:00 UID: 727FA104 PATIENT_ID: 12 NAME: Иванов И.И. ACTION: visit</pre>

        <h2>Инструкция по публикации</h2>
        <ol>
            <li>Скопируйте файл index.html в SPIFFS на ESP32</li>
            <li>Убедитесь, что ESP32 реализует все необходимые API endpoints</li>
            <li>Настройте WiFi (AP или STA mode) в скетче ESP32</li>
            <li>Подключите RFID-ридер (MFRC522), RTC модуль (DS3231) и SD карту</li>
        </ol>
    </div>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=Repin777/https-huggingface-co-spaces-repin777-repinsite" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>