File size: 59,426 Bytes
0dcd2ca
 
86b4aeb
 
 
6f093ab
463dbc3
 
86b4aeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
463dbc3
0dcd2ca
86b4aeb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f093ab
463dbc3
86b4aeb
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
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
import { Component, HostListener, ElementRef, ViewChild, AfterViewInit, OnInit, OnDestroy } from '@angular/core';
import { trigger, state, style, transition, animate } from '@angular/animations';
import { Subject } from 'rxjs';
import { debounceTime, takeUntil } from 'rxjs/operators';
import { Router, ActivatedRoute } from '@angular/router';
import { CaseStoreService } from '../shared/case-store.service';

@Component({
  selector: 'app-infopage',
  templateUrl: './infopage.component.html',
  styleUrls: ['./infopage.component.css'],
  animations: [
    // Simple card animation
    trigger('cardSlide', [
      transition(':enter', [
        style({ transform: 'translateY(20px)', opacity: 0 }),
        animate('300ms ease-out', style({ transform: 'translateY(0)', opacity: 1 }))
      ]),
      transition(':leave', [
        animate('300ms ease-in', style({ transform: 'translateY(20px)', opacity: 0 }))
      ])
    ]),
    // Field animation
    trigger('fieldAnimation', [
      transition(':enter', [
        style({ opacity: 0, transform: 'translateY(10px)' }),
        animate('200ms ease-out', style({ opacity: 1, transform: 'translateY(0)' }))
      ]),
      transition(':leave', [
        animate('150ms ease-out', style({ opacity: 0, transform: 'translateY(10px)' }))
      ])
    ]),
    // Simple fade animation
    trigger('fadeIn', [
      transition(':enter', [
        style({ opacity: 0 }),
        animate('200ms ease-in', style({ opacity: 1 }))
      ]),
      transition(':leave', [
        animate('150ms ease-out', style({ opacity: 0 }))
      ])
    ]),
    // Help animation
    trigger('helpAnimation', [
      transition(':enter', [
        style({ opacity: 0, transform: 'translateY(-10px)' }),
        animate('200ms ease-out', style({ opacity: 1, transform: 'translateY(0)' }))
      ]),
      transition(':leave', [
        animate('150ms ease-in', style({ opacity: 0, transform: 'translateY(-10px)' }))
      ])
    ])
  ]
})
export class InfopageComponent implements OnInit, AfterViewInit, OnDestroy {
  showRemarkModal: boolean = false;
  showSubmitPopup: boolean = false;
  showMicPopup: boolean = false;
  isRecording: boolean = false;
  // New per-field recording state
  recordingField: string | null = null;
  showMicPopupField: string | null = null;

  // Current logged-in user profile (display only)
  currentUser: { name: string; email?: string; avatarUrl?: string } | null = null;
  // Profile dropdown visibility
  showProfileMenu: boolean = false;

  // NEW: Case ID duplicate popup state
  showCaseIdExistsPopup: boolean = false;
  caseIdExistsMessage: string = '';
  showNoDataPopup: boolean = false; // <-- New property for no data popup

  // When editing an existing case, store its ID to avoid false duplicate detection
  editingCaseId: string | null = null;

  constructor(private router: Router, private route: ActivatedRoute, private caseStore: CaseStoreService) { }

  // Core state
  currentSection: 'crime' | 'suspect' | 'notes' = 'crime';
  currentSubgroup: string = 'Identification & Timing';
  showHelpFor: string | null = null;

  // UI state
  isAutoSaving: boolean = false;
  autoSaveStatus: string = 'Saved';
  isDragOver: boolean = false;
  showViewRecordsTooltip: boolean = false;

  // Card state
  isCardMinimized = {
    primary: false,
    secondary: false,
    tertiary: false
  };

  // Form data and validation
  formData: Record<string, any> = {};
  fieldValidation: Record<string, { hasError: boolean; isValid: boolean; message: string }> = {};
  completedFields: Set<string> = new Set();
  completedSubgroups: Set<string> = new Set();
  completedSections: Set<string> = new Set();

  // Subjects for reactive programming
  private destroy$ = new Subject<void>();
  private autoSave$ = new Subject<void>();

  // Constants
  readonly sectionKeys: ('crime' | 'suspect' | 'notes')[] = ['crime', 'suspect', 'notes'];
  readonly maxFieldsPerCard = 8;
  readonly maxFieldsPerSecondaryCard = 8;
  readonly maxFieldsPerCardIdentificationTiming = 6;
  readonly maxFieldsPerSecondaryCardIdentificationTiming = 6;

  @ViewChild('formCard1') formCard1!: ElementRef<HTMLDivElement>;
  @ViewChild('formCard2') formCard2!: ElementRef<HTMLDivElement>;
  @ViewChild('formCard3') formCard3!: ElementRef<HTMLDivElement>;
  // Reference to profile display for positioning menu
  @ViewChild('profileDisplay', { read: ElementRef }) profileDisplayRef!: ElementRef;
  // Dynamic inline styles for positioned profile menu
  profileMenuStyle: Record<string, string> = {};

  // Enhanced field definitions with validation rules
  readonly requiredFields = new Set<string>([
    'Case ID', 'Crime Type', 'Date & Time (Entry)', 'Location', 'Suspect Name', 'Age', 'Gender',
    'FIR / Ref #', 'Case Category', 'Occurred From', 'Country', 'State', 'District',
    'Jurisdiction / PS', 'Scene Type', 'Reported By', 'Investigative Status', 'Investigating Officer'
  ]);

  readonly compactFields = new Set<string>([
    'Age', 'Gender', 'Height (cm)', 'Weight (kg)', 'Build', 'Hair Color', 'Eye Color',
    'Number of Victims', 'Witness Count', 'Prior Arrests', 'Arrest Count', 'Case Priority',
    'Photos / Video?', 'CCTV Present?', 'Arrest Made', 'risk Level', 'Confidentiality'
  ]);

  readonly numericFields = new Set<string>([
    'Age', 'Height (cm)', 'Weight (kg)', 'Number of Victims', 'Witness Count', 'Prior Arrests', 'Arrest Count'
  ]);

  readonly fileTypeConfig: Record<string, string> = {
    'Photo Upload': 'image/*',
    'Evidence Photos': 'image/*',
    'Evidence Videos': 'video/*',
    'Evidence Documents': '.pdf,.doc,.docx,.txt',
    'Evidence Files': '*',
    'Upload Evidence Files': '*',
    'Digital Evidence': '*'
  };

  selectedValues: Record<string, string> = {};

  dateTimeFields = new Set<string>(['Date & Time (Entry)', 'Occurred From', 'Occurred To', 'Time Reported', 'Time Discovered', 'Scene Secured Time']);
  dateFields = new Set<string>(['Follow-up Date', 'Next Hearing Date']);

  countries = ['India'];
  indiaStates = [
    'Andhra Pradesh', 'Arunachal Pradesh', 'Assam', 'Bihar', 'Chhattisgarh', 'Goa', 'Gujarat',
    'Haryana', 'Himachal Pradesh', 'Jharkhand', 'Karnataka', 'Kerala', 'Madhya Pradesh',
    'Maharashtra', 'Manipur', 'Meghalaya', 'Mizoram', 'Nagaland', 'Odisha', 'Punjab',
    'Rajasthan', 'Sikkim', 'Tamil Nadu', 'Telangana', 'Tripura', 'Uttar Pradesh',
    'Uttarakhand', 'West Bengal'
  ];

  tamilNaduDistricts = [
    'Ariyalur', 'Chengalpattu', 'Chennai', 'Coimbatore', 'Cuddalore', 'Dharmapuri', 'Dindigul',
    'Erode', 'Kallakurichi', 'Kanchipuram', 'Kanyakumari', 'Karur', 'Krishnagiri', 'Madurai',
    'Mayiladuthurai', 'Nagapattinam', 'Namakkal', 'Nilgiris', 'Perambalur', 'Pudukkottai',
    'Ramanathapuram', 'Ranipet', 'Salem', 'Sivaganga', 'Tenkasi', 'Thanjavur', 'Theni',
    'Thoothukudi (Tuticorin)', 'Tiruchirappalli', 'Tirunelveli', 'Tirupathur', 'Tiruppur',
    'Tiruvallur', 'Tiruvannamalai', 'Tiruvarur', 'Vellore', 'Viluppuram', 'Virudhunagar'
  ];

  selectOptions: Record<string, string[]> = {
    'Crime Type': ['Theft', 'Assault', 'Homicide', 'Cybercrime', 'Fraud', 'Narcotics', 'Arson', 'Kidnapping', 'General', 'Other'],
    'Case Category': ['Property', 'Violent', 'Cyber', 'Financial', 'Public Order', 'Narcotics', 'Organized', 'General', 'Other'],
    'Number of Victims': ['0', '1', '2', '3', '4', '5+'],
    'Jurisdiction / PS': ['Central PS', 'East Division', 'West Division', 'Rural Unit', 'Cyber Cell', 'General'],
    'Scene Type': ['Residential', 'Commercial', 'Public Space', 'Vehicle', 'Rural', 'Online', 'General', 'Other'],
    'Witness Count': ['0', '1', '2', '3', '4', '5+'],
    'Victim Summary': ['Stable', 'Injured', 'Critical', 'Deceased', 'Unknown'],
    'Suspected Offender Known?': ['Yes', 'No', 'Unknown'],
    'Offence Category': ['Minor', 'Serious', 'Organized', 'Cyber', 'Financial', 'Violent', 'General', 'Other'],
    'Suspected Motive': ['Financial Gain', 'Revenge', 'Jealousy', 'Ideological', 'Political', 'Personal Dispute', 'Unknown', 'General', 'Other'],
    'Confirmed Motive': ['Financial Gain', 'Revenge', 'Jealousy', 'Ideological', 'Political', 'Personal Dispute', 'Unknown', 'General', 'Other'],
    'Weapon Involved': ['None', 'Knife', 'Firearm', 'Blunt Object', 'Explosive', 'Chemical', 'Other', 'Unknown', 'General'],
    'Property Loss / Damage': ['None', 'Minor', 'Moderate', 'Major', 'Severe', 'Unknown'],
    'Photos / Video?': ['Yes', 'No'],
    'CCTV Present?': ['Yes', 'No'],
    'Scene Condition': ['Intact', 'Disturbed', 'Contaminated', 'Secured', 'Compromised', 'General'],
    'Chain of Custody?': ['Initiated', 'Ongoing', 'Complete', 'Not Started'],
    'Forensic Tests Required': ['None', 'DNA', 'Fingerprints', 'Ballistics', 'Toxicology', 'Digital Forensics', 'Trace', 'General', 'Other'],
    'Arrest Made': ['Yes', 'No'],
    'risk Level': ['Low', 'Medium', 'High', 'Critical'],
    'Confidentiality': ['Internal', 'Restricted', 'Sensitive', 'Sealed'],
    'Initial Actions Taken': ['Scene Secured', 'Medical Aid', 'Evidence Logged', 'Witness Statements', 'Suspect Detained', 'General', 'Other'],
    'Investigative Status': ['Open', 'Active', 'Suspended', 'Closed', 'Archived'],
    'Case Priority': ['Low', 'Normal', 'High', 'Urgent', 'Critical'],
    'Gender': ['Male', 'Female', 'Other'],
    'Nationality': ['India'],
    'Languages': ['English', 'Hindi', 'Tamil', 'Telugu', 'Kannada', 'Malayalam', 'Bengali', 'Marathi', 'Gujarati', 'Other'],
    'Build': ['Slim', 'Average', 'Athletic', 'Heavy', 'Obese'],
    'Hair Color': ['Black', 'Brown', 'Blonde', 'Red', 'Grey', 'White', 'Dyed / Other', 'Unknown'],
    'Eye Color': ['Brown', 'Blue', 'Green', 'Hazel', 'Grey', 'Black', 'Unknown'],
    'Employment': ['Employed', 'Unemployed', 'Self-Employed', 'Student', 'Retired', 'Unknown'],
    'Skin Tone': ['Fair', 'Medium', 'Olive', 'Dark', 'Very Dark', 'Unknown'],
    'Facial Hair': ['Clean Shaven', 'Mustache', 'Beard', 'Goatee', 'Stubble', 'None'],
    'Handedness': ['Left-handed', 'Right-handed', 'Ambidextrous'],
    'Voice Characteristics': ['Deep', 'High-pitched', 'Normal', 'Raspy', 'Stutter'],
    'Education': ['None', 'Primary', 'Secondary', 'Diploma', 'Bachelor', 'Master', 'Doctorate', 'Other'],
    'Marital Status': ['Single', 'Married', 'Divorced', 'Separated', 'Widowed', 'Unknown'],
    'Known Habits': ['Smoking', 'Alcohol', 'Substance Use', 'Gambling', 'None', 'Unknown'],
    'Occupation': ['Unskilled', 'Skilled Labour', 'Professional', 'Executive', 'Military', 'Law Enforcement', 'IT', 'Healthcare', 'Education', 'Finance', 'Other'],
    'Known Financial Details': ['None', 'Low Income', 'Moderate Income', 'High Income', 'Wealthy', 'Unknown'],
    'Gang Affiliation': ['None', 'Local', 'Regional', 'International', 'Unknown'],
    'Criminal History': ['None', 'Minor', 'Multiple', 'Serious'],
    'Prior Arrests': ['0', '1', '2', '3', '4', '5+'],
    'Probation/Parole Status': ['None', 'On Probation', 'On Parole', 'Completed', 'Unknown'],
    'Status': ['Draft', 'In Progress', 'Completed', 'Archived'],
    // Additional field options for complete coverage
    'Arrest Count': ['0', '1', '2', '3', '4', '5+'],
    'Linked Cases': [], // Will be populated dynamically with existing case IDs
    'Suspect Link': [], // Will be populated dynamically with existing suspect IDs
    'Government ID': ['Aadhaar Card', 'PAN Card', 'Driving License', 'Passport', 'Voter ID', 'Other'],
    'Family Connections': ['Spouse', 'Parent', 'Child', 'Sibling', 'Relative', 'Friend', 'Other'],
    'Social Media Handles': [], // Text input field for multiple handles
    'Version History / Updates': [] // Text area for version tracking
  };

  // File upload fields
  fileFields = new Set<string>([
    'Photo Upload', 'Evidence Photos', 'Evidence Videos', 'Evidence Documents',
    'Evidence Files', 'Upload Evidence Files', 'Digital Evidence'
  ]);

  uploadedFiles: Record<string, File[]> = {};
  // Transient confirmation messages per upload field
  uploadConfirmations: Record<string, string> = {};

  // Section icons
  sectionIcons = {
    crime: 'fas fa-gavel',
    suspect: 'fas fa-user-secret',
    notes: 'fas fa-sticky-note'
  };

  sections: any = {
    crime: {
      title: 'Crime Details',
      subgroups: {
        'Identification & Timing': ['Case ID', 'FIR / Ref #', 'Crime Type', 'Case Category', 'Date & Time (Entry)', 'Occurred From', 'Occurred To', 'Time Reported', 'Time Discovered', 'Country', 'State', 'District', 'Number of Victims', 'Brief Description'],
        'Location & Involved Persons': ['Location', 'Jurisdiction / PS', 'Scene Type', 'Reported By', 'Reporter Phone', 'Reporter Email', 'Witness Count', 'Witness Phone', 'Witness Email', 'Victim Name', 'Victim Phone', 'Victim Email', 'Victim Summary', 'Suspected Offender Known?', 'Suspect Link'],
        'Offence & Context': ['Legal Sections / Charges', 'Offence Category', 'Offence Description', 'Suspected Motive', 'Confirmed Motive', 'Weapon Involved', 'Property Loss / Damage'],
        'Evidence & Scene': ['Evidence Collected', 'Physical Evidence List', 'Evidence Storage Reference', 'Evidence Collected By', 'Evidence Bag / Seal Number', 'Scene Secured Time', 'Photos / Video?', 'CCTV Present?', 'CCTV Sources / IDs', 'Forensic Tests Required', 'Chain of Custody?', 'Scene Condition'],
        'Operational Notes': ['Investigating Officer', 'Duty Person', 'Supervising Officer', 'Patrol Notes', 'Arrest Made', 'Arrest Location', 'Initial Actions Taken', 'risk Level', 'Confidentiality'],
        'Status & Linkage': ['Biometric / Forensic IDs', 'DNA Ref ID', 'Fingerprint ID', 'Investigative Status', 'Linked Cases', 'Arrest Count', 'Case Priority', 'Follow-up Date', 'Court Case ID', 'Next Hearing Date', 'Final Summary'],
        'Remark': ['Remark']
      }
    },
    suspect: {
      title: 'Suspect Details',
      subgroups: {
        'Identity': ['Suspect ID', 'Suspect Name', 'Suspect Email', 'Suspect Phone', 'Alias / Nickname', 'Age', 'Gender', 'Nationality', 'Nationality ID / Passport Number', 'Languages', 'Address', 'Known Aliases', 'Government ID'],
        'Physical Description': ['Height (cm)', 'Weight (kg)', 'Build', 'Skin Tone', 'Hair Color', 'Eye Color', 'Facial Hair', 'Handedness', 'Tattoo Details', 'Scar Details', 'Distinguishing Marks', 'Voice Characteristics', 'Photo Upload'],
        'Background': ['Employment', 'Education', 'Occupation', 'Company', 'Workplace Address', 'Marital Status', 'Known Habits', 'Known Financial Details'],
        'Known Associates': ['Associate Names', 'Gang Affiliation', 'Family Connections', 'Social Media Handles'],
        'Prior Records': ['Criminal History', 'Prior Arrests', 'Probation/Parole Status'],
        'Remark': ['Remark']
      }
    },
    notes: {
      title: 'Evidence and Documents',
      subgroups: {
        'Investigation Notes': ['Initial Findings', 'Detailed Notes', 'Status', 'Version History / Updates'],
        'Evidence Files': ['Evidence Photos', 'Evidence Videos', 'Evidence Documents', 'Digital Evidence'],
        'Links and Recommendation': ['Links to Evidence', 'Final Recommendations'],
        'Remark': ['Remark']
      }
    }
  };

  // Complete field descriptions
  fieldDescriptions: Record<string, string> = {
    // Crime: Identification & Timing
    'Case ID': 'Unique internal tracking identifier for this case.',
    'FIR / Ref #': 'Official First Information Report or reference number.',
    'Crime Type': 'Primary legal / investigative classification of the offence.',
    'Case Category': 'Broader grouping used for analytics and reporting.',
    'Date & Time (Entry)': 'Timestamp when the case was first registered in the system.',
    'Occurred From': 'Start of the known / suspected offence time window.',
    'Occurred To': 'End of the known / suspected offence time window.',
    'Time Reported': 'When it was first reported to authorities.',
    'Time Discovered': 'When the incident was first discovered (may differ from reported).',
    'Country': 'Country where the offence occurred.',
    'State': 'State / province of occurrence.',
    'District': 'Administrative district of occurrence (Tamil Nadu districts supported).',
    'Number of Victims': 'Total count of direct victims involved.',
    'Brief Description': 'Short narrative summary for quick reference.',

    // Crime: Location & People
    'Location': 'Exact address / geo description of the scene.',
    'Jurisdiction / PS': 'Police Station or jurisdiction handling the investigation.',
    'Scene Type': 'Type of environment where the offence occurred.',
    'Reported By': 'Name of the reporting individual / entity.',
    'Reporter Phone': 'Primary phone number for the reporting party (include country code if known).',
    'Reporter Email': 'Email address for the reporting party, if available.',
    'Witness Count': 'Number of identified witnesses so far.',
    'Witness Phone': 'Primary phone number for the witness (include country code if known).',
    'Witness Email': 'Email address for the witness, if available.',
    'Victim Name': 'Primary victim name (or placeholder if protected).',
    'Victim Phone': 'Primary phone number for the victim (include country code if known).',
    'Victim Email': 'Email address for the victim, if available.',
    'Victim Summary': 'Short summary of victim condition or status.',
    'Suspected Offender Known?': 'Whether victim / witnesses know the offender.',
    'Suspect Link': 'Internal reference to related suspect record.',

    // Crime: Offence & Context
    'Legal Sections / Charges': 'Applicable statutory sections / penal codes.',
    'Offence Category': 'Higher level grouping (e.g., violent, cyber).',
    'Offence Description': 'Detailed narrative of what occurred.',
    'Suspected Motive': 'Preliminary perceived motive (subject to change).',
    'Confirmed Motive': 'Validated motive after evidence review.',
    'Weapon Involved': 'Weapon(s) used or suspected; choose Unknown if unclear.',
    'Property Loss / Damage': 'Summary / valuation of property loss or damage.',

    // Crime: Evidence & Scene
    'Evidence Collected': 'General list of all evidentiary items gathered.',
    'Forensic Tests Required': 'Pending or requested forensic examinations.',
    'Scene Condition': 'Condition of scene upon first secure entry.',
    'Photos / Video?': 'Whether any media was captured.',
    'CCTV Present?': 'If relevant CCTV sources exist.',
    'CCTV Sources / IDs': 'Identifiers / locations for each CCTV source.',
    'Physical Evidence list': 'Individual tangible exhibits (bagged / tagged).',
    'Chain of Custody?': 'Status of formal evidence transfer logging.',
    'Digital Evidence': 'Electronic sources: phones, email dumps, logs, socials.',
    'Evidence Storage Reference': 'Locker / repository / digital vault reference ID.',
    'Evidence Collected By': 'Name / identifier of the person who collected the evidence.',
    'Evidence Bag / Seal Number': 'Chain of custody bag or seal identifier assigned to collected evidence.',
    'Scene Secured Time': 'Timestamp when the scene was first secured and access restricted.',

    // Crime: Operational Notes
    'Investigating Officer': 'Lead officer responsible for case progress.',
    'Duty Person': 'Officer / staff who received the report.',
    'Supervising Officer': 'Oversight / escalation point for the case.',
    'Patrol Notes': 'First responder observations / scene notes.',
    'Arrest Made': 'Indicates whether an arrest has occurred.',
    'Arrest Location': 'Location at which arrest was executed.',
    'Initial Actions Taken': 'Immediate remedial or containment actions.',
    'risk Level': 'Risk classification influencing priority.',
    'Confidentiality': 'Access / visibility level of case records.',

    // Crime: Status & Linkage
    'Biometric / Forensic IDs': 'External forensic system identifiers (AFIS, DNA DB).',
    'DNA Ref ID': 'Laboratory DNA reference identifier.',
    'Fingerprint ID': 'Fingerprint database reference.',
    'Investigative Status': 'Lifecycle status (Open / Active / Closed etc.).',
    'Linked Cases': 'Related or associated case identifiers.',
    'Arrest Count': 'Total arrests associated with this case.',
    'Case Priority': 'Operational prioritisation level.',
    'Follow-up Date': 'Next scheduled investigative review date.',
    'Court Case ID': 'Judicial / docket identifier once filed.',
    'Next Hearing Date': 'Date of next scheduled court proceeding.',
    'Final Summary': 'Closure narrative entered at completion.',

    // Suspect: Identity
    'Suspect ID': 'Internal unique suspect identifier.',
    'Suspect Name': 'Full legal or recorded name.',
    'Suspect Email': 'Primary email address for the suspect, if available.',
    'Suspect Phone': 'Primary phone number for the suspect, including country code if known.',
    'Alias / Nickname': 'Commonly used alternative names.',
    'Age': 'Approximate or confirmed age.',
    'Gender': 'Recorded gender descriptor.',
    'Nationality': 'Country of citizenship.',
    'Nationality ID / Passport Number': 'Official national ID / passport number.',
    'Languages': 'Languages spoken or understood by suspect.',
    'Address': 'Primary last known address.',
    'Known Aliases': 'Additional identity variations.',
    'Government ID': 'Government issued identification (license / ID card).',

    // Suspect: Physical Description
    'Height (cm)': 'Height in centimetres measured or estimated.',
    'Weight (kg)': 'Weight in kilograms measured or estimated.',
    'Build': 'General body build classification.',
    'Hair Color': 'Observed or recorded hair colour.',
    'Eye Color': 'Observed or recorded eye colour.',
    'Distinguishing Marks': 'Unique visible physical markers.',
    'Tattoo Details': 'Location and description of tattoos.',
    'Scar Details': 'Location and description of scars.',
    'Photo Upload': 'Most recent or relevant facial photograph.',
    'Skin Tone': 'Approximate skin tone (e.g., Fair, Medium, Olive, Dark).',
    'Facial Hair': 'Facial hair description (Mustache, Beard, Goatee, etc.).',
    'Handedness': 'Primary dominant hand (Left/Right/Ambidextrous).',
    'Voice Characteristics': 'Notable voice traits (Deep, Raspy, Stutter, etc.).',

    // Suspect: Background
    'Employment': 'Current employment status.',
    'Education': 'Highest completed education level.',
    'Occupation': 'Primary occupation / role.',
    'Company': 'Employer / organisation name.',
    'Workplace Address': 'Physical address of workplace.',
    'Marital Status': 'Current marital / relationship status.',
    'Known Habits': 'Behavioural patterns (substances, gambling, etc.).',
    'Known Financial Details': 'Financial profile relevant to investigation.',

    // Suspect: Known Associates
    'Associate Names': 'Key associate individuals linked to suspect.',
    'Gang Affiliation': 'Known gang or group membership.',
    'Family Connections': 'Notable family relational links.',
    'Social Media Handles': 'Identifiers used on social platforms.',

    // Suspect: Prior Records
    'Criminal History': 'Summary of prior criminal involvement.',
    'Prior Arrests': 'Number / list of previous arrests.',
    'Probation/Parole Status': 'Current supervision / release status.',

    // Notes: Investigation Notes
    'Initial Findings': 'Early observations at investigation start.',
    'Detailed Notes': 'Progressive narrative & analytical details.',
    'Status': 'Progress state category for notes.',
    'Version History / Updates': 'Chronological changes & authorship log.',

    // Notes: Evidence Files
    'Evidence Photos': 'Photographic evidence references.',
    'Evidence Videos': 'Video evidence references.',
    'Evidence Documents': 'Document / PDF evidence references.',

    // Notes: Links and Recommendation
    'Links to Evidence': 'External or internal reference links to sources.',
    'Final Recommendations': 'Closing recommendations / actions summary.'
  };

  // update subgroup icons mapping
  subgroupIcons: any = {
    'Identification & Timing': 'fas fa-clock',
    'Location & Involved Persons': 'fas fa-map-marker-alt',
    'Offence & Context': 'fas fa-gavel',
    'Evidence & Scene': 'fas fa-search',
    'Operational Notes': 'fas fa-clipboard',
    'Status & Linkage': 'fas fa-link',
    'Identity': 'fas fa-id-card',
    'Physical Description': 'fas fa-user',
    'Background': 'fas fa-user-graduate',
    'Known Associates': 'fas fa-users',
    'Prior Records': 'fas fa-file-alt',
    'Investigation Notes': 'fas fa-sticky-note',
    'Evidence Files': 'fas fa-folder',
    'Links and Recommendation': 'fas fa-link',
    'Recommendations': 'fas fa-thumbs-up'
  };

  ngOnInit(): void {
    // Load current user profile (if available)
    this.loadCurrentUser();

    // Set up autosave
    this.autoSave$.pipe(debounceTime(2000), takeUntil(this.destroy$)).subscribe(() => {
      this.performAutoSave();
    });

    // Load field selections
    this.loadFieldSelections();

    // Initialize formData empty
    this.formData = {};
    this.completedFields.clear();
    this.completedSubgroups.clear();
    this.completedSections.clear();

    // Handle navigation state/params to prefill when editing a case
    this.handleNavigationPrefill();
  }

  ngAfterViewInit(): void { }
  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
    if (this.submitInterval) {
      clearInterval(this.submitInterval);
    }
  }

  // Progress
  get progressPercentage(): number {
    const totalFields = this.getAllFields().length;
    const completedFields = this.completedFields.size;
    return totalFields > 0 ? Math.round((completedFields / totalFields) * 100) : 0;
  }

  private getAllFields(): string[] {
    let allFields: string[] = [];
    for (const section of this.sectionKeys) {
      for (const subgroup of Object.keys(this.sections[section].subgroups)) {
        allFields = allFields.concat(this.sections[section].subgroups[subgroup]);
      }
    }
    return allFields;
  }

  // Helper method to check if we're in Identification & Timing
  private isIdentificationAndTimingPage(): boolean {
    return this.currentSubgroup === 'Identification & Timing';
  }

  // Helper method to check if we're in Location & Involved Persons
  private isLocationAndPeoplePage(): boolean {
    return this.currentSubgroup === 'Location & Involved Persons';
  }

  // Helper method to check if we need compact layout (applies to all pages now)
  private needsCompactLayout(): boolean {
    return true; // Apply compact layout to all pages to prevent main page scroll
  }

  // Check if current page is Physical Description
  isPhysicalDescriptionPage(): boolean {
    return this.currentSection === 'suspect' && this.currentSubgroup === 'Physical Description';
  }

  // Card Management - Updated for single card layout across ALL pages
  showSecondaryCard(): boolean {
    return false; // No secondary card for any page - single card layout for all
  }

  showTertiaryCard(): boolean {
    return false; // No tertiary card for any page - single card layout for all
  }

  getPrimaryFields(): string[] {
    // Return selected fields for display instead of all fields
    return this.getSelectedFieldsForDisplay();
  }

  private getCurrentFields(): string[] {
    return this.sections[this.currentSection].subgroups[this.currentSubgroup] || [];
  }

  toggleCardMinimize(card: 'primary' | 'secondary' | 'tertiary'): void {
    this.isCardMinimized[card] = !this.isCardMinimized[card];
  }

  // Field Management
  isFieldRequired(field: string): boolean {
    return this.requiredFields.has(field);
  }

  isCompactField(field: string): boolean {
    return this.compactFields.has(field);
  }

  getInputType(field: string): string {
    if (this.numericFields.has(field)) return 'number';
    if (this.dateTimeFields.has(field)) return 'datetime-local';
    if (this.dateFields.has(field)) return 'date';
    if (field.toLowerCase().includes('email')) return 'email';
    if (field.toLowerCase().includes('phone') || field.toLowerCase().includes('contact')) return 'tel';
    if (field.toLowerCase().includes('url') || field.toLowerCase().includes('link')) return 'url';
    if (field.toLowerCase().includes('description')) return 'textarea';
    return 'text';
  }

  getFieldPlaceholder(field: string): string {
    if (field === 'Age') return 'Enter age (18-99)';
    if (field === 'Height (cm)') return 'Height in cm';
    if (field === 'Weight (kg)') return 'Weight in kg';
    if (this.dateTimeFields.has(field)) return 'dd-mm-yyyy --:--';
    if (this.dateFields.has(field)) return 'dd-mm-yyyy';
    if (field.toLowerCase().includes('email')) return 'Enter email address';
    if (field.toLowerCase().includes('phone')) return 'Enter phone number';
    if (field === 'Initial Findings') return 'Summary of first observations...';
    if (field === 'Detailed Notes') return 'Detailed analysis and observations...';
    if (field.toLowerCase().includes('description')) return 'Enter detailed description...';
    return `Enter ${field.toLowerCase()}`;
  }

  getMaxLength(field: string): number {
    if (field === 'Age') return 2;
    if (field === 'Gender') return 10;
    if (field === 'Height (cm)') return 3;
    if (field === 'Weight (kg)') return 3;
    if (this.compactFields.has(field)) return 20;
    return 500;
  }

  // Validation
  validateField(field: string): void {
    const value = this.formData[field];
    let hasError = false;
    let isValid = false;
    let message = '';

    if (this.isFieldRequired(field) && (!value || value.toString().trim() === '')) {
      hasError = true;
      message = `${field} is required`;
    } else if (value && value.toString().trim() !== '') {
      // Field-specific validation
      if (field === 'Age') {
        const age = parseInt(value);
        if (isNaN(age) || age < 1 || age > 120) {
          hasError = true;
          message = 'Age must be a valid number between1 and 120';
        } else {
          isValid = true;
        }
      } else if (field === 'Email') {
        // Basic email pattern; improve with regex if needed
        const emailPattern = /\S+@\S+\.\S+/;
        isValid = emailPattern.test(value);
        if (!isValid) {
          hasError = true;
          message = 'Invalid email address format';
        }
      } else if (field === 'Case ID') {
        // Check for duplicate Case ID (compare numeric parts when possible)
        const input = String(value).trim();
        const inputNumeric = this.extractNumericId(input);
        const existing = this.caseStore.getPoliceCases().find(c => {
          const existingVal = c.caseId || '';
          const existingNumeric = this.extractNumericId(existingVal);
          if (inputNumeric && existingNumeric) {
            return inputNumeric === existingNumeric; // numeric match
          }
          // fallback to full string match (case-insensitive)
          return existingVal.toLowerCase() === input.toLowerCase();
        });

        // If editing an existing case, ignore match against the same case
        if (existing && existing.caseId !== this.editingCaseId) {
          hasError = true;
          message = `Case ID \"${input}\" already exists`;
          this.caseIdExistsMessage = message;
          this.showCaseIdExistsPopup = true;
        } else {
          isValid = true;
        }
      } else {
        // Generic validation for other fields (extend as needed)
        isValid = true;
      }
    }

    // Update field validation state
    this.fieldValidation[field] = { hasError, isValid, message };

    // Update overall form completion status
    this.updateCompletionStatus();
  }

  // Extract first numeric sequence from a case id string (e.g., 'CASE-001' -> '001', '001' -> '001')
  private extractNumericId(val: string): string | null {
    if (!val) return null;
    const m = String(val).match(/(\d+)/);
    return m ? m[1].replace(/^0+(?=\d)/, '') : null; // strip leading zeros but keep '0' if that's all
  }

  // Close duplicate popup
  closeCaseIdPopup(): void {
    this.showCaseIdExistsPopup = false;
  }

  // Close no-data popup
  closeNoDataPopup(): void {
    this.showNoDataPopup = false;
  }

  private updateCompletionStatus(): void {
    this.completedFields.clear();

    for (const field of Object.keys(this.formData)) {
      if (this.formData[field] !== null && this.formData[field] !== undefined && this.formData[field] !== '') {
        this.completedFields.add(field);
      }
    }

    // Update completed subgroups and sections
    this.updateCompletedGroupsAndSections();
  }

  private updateCompletedGroupsAndSections(): void {
    this.completedSubgroups.clear();
    this.completedSections.clear();

    for (const section of this.sectionKeys) {
      const subgroups = Object.keys(this.sections[section].subgroups);
      for (const subgroup of subgroups) {
        const fields = this.sections[section].subgroups[subgroup];
        const allFieldsCompleted = fields.every((field: string) => this.completedFields.has(field));

        if (allFieldsCompleted) {
          this.completedSubgroups.add(subgroup);
        }
      }

      if (this.completedSubgroups.size === subgroups.length) {
        this.completedSections.add(section);
      }
    }
  }

  // Field selection functionality - Updated to allow all fields by default
  selectedFields: Record<string, string[]> = {}; // Store selected fields per subgroup
  showFieldSelector: string | null = null; // Track which field selector is open
  readonly maxSelectableFields = 50; // Increased limit to allow more fields

  // Get all available fields for current subgroup
  getAvailableFields(): string[] {
    return this.getCurrentFields();
  }

  // Get total available fields count dynamically
  getTotalAvailableFieldsCount(): number {
    return this.getAvailableFields().length;
  }

  // Get currently selected fields for display (default to ALL fields if none selected)
  getSelectedFieldsForDisplay(): string[] {
    const subgroupKey = `${this.currentSection}-${this.currentSubgroup}`;
    if (this.selectedFields[subgroupKey] && this.selectedFields[subgroupKey].length >= 0) {
      return this.selectedFields[subgroupKey];
    }
    // Default to ALL fields if no selection made
    return this.getCurrentFields();
  }

  // Toggle field selection with enhanced debugging
  toggleFieldSelection(field: string, event?: Event): void {
    if (event) {
      event.preventDefault();
      event.stopPropagation();
    }

    console.log('Toggling field selection for:', field);

    const subgroupKey = `${this.currentSection}-${this.currentSubgroup}`;
    if (!this.selectedFields[subgroupKey]) {
      // Initialize with all fields selected by default
      this.selectedFields[subgroupKey] = [...this.getCurrentFields()];
    }

    const currentSelection = this.selectedFields[subgroupKey];
    const fieldIndex = currentSelection.indexOf(field);

    console.log('Current selection:', currentSelection);
    console.log('Field index:', fieldIndex);

    if (fieldIndex > -1) {
      // Remove field if already selected
      currentSelection.splice(fieldIndex, 1);
      console.log('Removed field:', field);
    } else {
      // Add field if not selected and under limit
      if (currentSelection.length < this.maxSelectableFields) {
        currentSelection.push(field);
        console.log('Added field:', field);
      } else {
        console.log('Selection limit reached, cannot add:', field);
      }
    }

    // Trigger change detection
    this.selectedFields = { ...this.selectedFields };
    this.saveFieldSelections();
    // Do NOT close the popup here; just update selection and save
  }

  // Check if field is currently selected
  isFieldSelected(field: string): boolean {
    const subgroupKey = `${this.currentSection}-${this.currentSubgroup}`;
    const selections = this.selectedFields[subgroupKey];
    if (!selections) {
      // If no selections made, all fields are selected by default
      return true;
    }
    return selections.includes(field);
  }

  getSelectedFieldCount(): number {
    const subgroupKey = `${this.currentSection}-${this.currentSubgroup}`;
    const selections = this.selectedFields[subgroupKey];
    if (!selections) return this.getCurrentFields().length;
    return selections.length;
  }

  isSelectionLimitReached(): boolean {
    return this.getSelectedFieldCount() >= this.maxSelectableFields;
  }

  resetFieldSelection(event?: Event): void {
    if (event) {
      event.preventDefault();
      event.stopPropagation();
    }
    const subgroupKey = `${this.currentSection}-${this.currentSubgroup}`;
    this.selectedFields[subgroupKey] = [];
    this.selectedFields = { ...this.selectedFields };
    this.saveFieldSelections();
  }

  selectAllFields(event?: Event): void {
    if (event) {
      event.preventDefault();
      event.stopPropagation();
    }
    const subgroupKey = `${this.currentSection}-${this.currentSubgroup}`;
    const allFields = this.getCurrentFields();
    this.selectedFields[subgroupKey] = [...allFields];
    this.selectedFields = { ...this.selectedFields };
    this.saveFieldSelections();
  }

  selectDefaultFields(event?: Event): void {
    if (event) {
      event.preventDefault();
      event.stopPropagation();
    }
    const subgroupKey = `${this.currentSection}-${this.currentSubgroup}`;
    const allFields = this.getCurrentFields();
    this.selectedFields[subgroupKey] = allFields.slice(0, Math.min(10, allFields.length));
    this.selectedFields = { ...this.selectedFields };
    this.saveFieldSelections();
  }

  getDynamicMaxSelectable(): number {
    const totalFields = this.getTotalAvailableFieldsCount();
    return Math.min(this.maxSelectableFields, totalFields);
  }

  areAllFieldsSelected(): boolean {
    const subgroupKey = `${this.currentSection}-${this.currentSubgroup}`;
    const selections = this.selectedFields[subgroupKey];
    const totalFields = this.getCurrentFields().length;
    if (!selections) return true;
    return selections.length === totalFields;
  }

  areNoFieldsSelected(): boolean {
    const subgroupKey = `${this.currentSection}-${this.currentSubgroup}`;
    const selections = this.selectedFields[subgroupKey];
    if (!selections) return false;
    return selections.length === 0;
  }

  getSubgroups(): string[] {
    return Object.keys(this.sections[this.currentSection].subgroups);
  }

  showSection(section: 'crime' | 'suspect' | 'notes'): void {
    this.closeFieldSelector();
    this.currentSection = section;
    this.currentSubgroup = Object.keys(this.sections[this.currentSection].subgroups)[0];
    this.showHelpFor = null;
    this.triggerAutoSave();
  }

  @HostListener('document:click', ['$event'])
  handleDoc(event: Event): void {
    this.showHelpFor = null;
    const target = event.target as HTMLElement;
    if (this.showFieldSelector && !target.closest('.field-selector-container')) this.closeFieldSelector();
    if (this.showProfileMenu && !target.closest('.profile-display')) this.showProfileMenu = false;
  }

  setSubgroup(key: string): void {
    this.closeFieldSelector();
    this.currentSubgroup = key;
    this.showHelpFor = null;
    this.triggerAutoSave();
  }

  isSectionCompleted(section: string): boolean {
    return this.completedSections.has(section);
  }

  isSubgroupCompleted(subgroup: string): boolean {
    return this.completedSubgroups.has(subgroup);
  }

  getSectionDescription(section: string): string {
    const descriptions = {
      crime: 'Capture comprehensive crime intelligence, including timing, location, evidence, and operational context. Use predefined dropdown values for consistency and upload supporting documents and materials.',
      suspect: 'Document a comprehensive suspect profile, including identity, physical characteristics, background, associations, and criminal history. Include recent photographs when available.',
      notes: 'Maintain detailed investigative records, including findings, evidence files, reference materials, and final recommendations, with proper version control.'
    };
    return descriptions[section as keyof typeof descriptions] || '';
  }

  onFieldChange(field: string): void {
    this.validateField(field);
    this.triggerAutoSave();
  }

  private triggerAutoSave(): void {
    this.autoSave$.next();
  }

  private performAutoSave(): void {
    this.isAutoSaving = true;
    this.autoSaveStatus = 'Saving...';
    this.saveFormData();
    setTimeout(() => {
      this.isAutoSaving = false;
      this.autoSaveStatus = 'Saved';
      setTimeout(() => {
        this.autoSaveStatus = 'Auto-save';
      }, 2000);
    }, 500);
  }

  private saveFormData(): void {
    const saveData = {
      formData: this.formData,
      completedFields: Array.from(this.completedFields),
      completedSubgroups: Array.from(this.completedSubgroups),
      completedSections: Array.from(this.completedSections),
      currentSection: this.currentSection,
      currentSubgroup: this.currentSubgroup
    };
    localStorage.setItem('pydetect-form-data', JSON.stringify(saveData));
  }

  private loadFormData(): void {
    const savedData = localStorage.getItem('pydetect-form-data');
    if (savedData) {
      const data = JSON.parse(savedData);
      this.formData = data.formData || {};
      this.completedFields = new Set(data.completedFields || []);
      this.completedSubgroups = new Set(data.completedSubgroups || []);
      this.completedSections = new Set(data.completedSections || []);
      this.currentSection = data.currentSection || 'crime';
      this.currentSubgroup = data.currentSubgroup || 'Identification & Timing';
    }
  }

  getOptions(field: string): string[] | undefined {
    if (field === 'Country') return this.countries;
    if (field === 'State') return (this.selectedValues['Country'] === 'India' || !this.selectedValues['Country']) ? this.indiaStates : [];
    if (field === 'District') {
      if (this.selectedValues['State'] === 'Tamil Nadu') return this.tamilNaduDistricts;
      return [];
    }
    return this.selectOptions[field];
  }

  onSelectChange(field: string, event: Event): void {
    const value = (event.target as HTMLSelectElement).value;
    this.selectedValues[field] = value;
    this.formData[field] = value;
    if (field === 'Country') {
      delete this.selectedValues['State'];
      delete this.selectedValues['District'];
      delete this.formData['State'];
      delete this.formData['District'];
    }
    if (field === 'State') {
      delete this.selectedValues['District'];
      delete this.formData['District'];
    }
    this.validateField(field);
    this.triggerAutoSave();
  }

  toggleFieldInfo(field: string, ev: MouseEvent): void {
    ev.stopPropagation();
    this.showHelpFor = this.showHelpFor === field ? null : field;
  }

  closeFieldInfo(): void {
    this.showHelpFor = null;
  }

  onFileChange(field: string, event: Event): void {
    const input = event.target as HTMLInputElement;
    const files = input.files ? Array.from(input.files) : [];
    if (files.length) {
      this.uploadedFiles[field] = (this.uploadedFiles[field] || []).concat(files);
      this.validateField(field);
      this.triggerAutoSave();
      const total = this.uploadedFiles[field].length;
      const message = total > 1 ? `${total} files uploaded` : 'Upload successful';
      this.uploadConfirmations[field] = message;
      setTimeout(() => delete this.uploadConfirmations[field], 4000);
    }
  }

  onDragOver(event: DragEvent): void {
    event.preventDefault();
    this.isDragOver = true;
  }

  onDragLeave(event: DragEvent): void {
    event.preventDefault();
    this.isDragOver = false;
  }

  onFileDrop(field: string, event: DragEvent): void {
    event.preventDefault();
    this.isDragOver = false;
    const files = event.dataTransfer?.files ? Array.from(event.dataTransfer.files) : [];
    if (files.length) {
      this.uploadedFiles[field] = (this.uploadedFiles[field] || []).concat(files);
      this.validateField(field);
      this.triggerAutoSave();
      const total = this.uploadedFiles[field].length;
      const message = total > 1 ? `${total} files uploaded` : 'Upload successful';
      this.uploadConfirmations[field] = message;
      setTimeout(() => delete this.uploadConfirmations[field], 4000);
    }
  }

  removeFile(field: string, file: File): void {
    if (this.uploadedFiles[field]) {
      this.uploadedFiles[field] = this.uploadedFiles[field].filter(f => f !== file);
      this.triggerAutoSave();
    }
  }

  getAcceptedFileTypes(field: string): string {
    return this.fileTypeConfig[field] || '*';
  }

  getAcceptedDisplay(field: string): string {
    const accept = (this.fileTypeConfig && this.fileTypeConfig[field]) || '';
    if (!accept || accept === '*') return 'Any file type';
    if (accept.includes('.') || accept.includes(',')) {
      const parts = accept.split(',').map(p => p.trim()).filter(Boolean);
      return parts.map(p => p.startsWith('.') ? p : (p.includes('/') ? this._mimeToExtList(p) : '.' + p)).flat().join(', ');
    }
    if (accept.includes('image/')) return '.jpg, .jpeg, .png, .gif';
    if (accept.includes('video/')) return '.mp4, .mov, .avi';
    if (accept.includes('audio/')) return '.mp3, .wav';
    return accept;
  }

  private _mimeToExtList(mime: string): string[] {
    mime = mime.trim();
    if (mime === 'image/*') return ['.jpg', '.jpeg', '.png', '.gif'];
    if (mime === 'video/*') return ['.mp4', '.mov', '.avi'];
    if (mime === 'audio/*') return ['.mp3', '.wav'];
    if (mime === '.pdf' || mime === 'application/pdf') return ['.pdf'];
    if (mime === '.doc' || mime === '.docx' || mime === 'application/msword' || mime === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') return ['.doc', '.docx'];
    return [mime];
  }

  private saveFieldSelections(): void {
    try { localStorage.setItem('pydetect-field-selections', JSON.stringify(this.selectedFields)); } catch (error) { console.warn('Could not save field selections to localStorage:', error); }
  }

  private loadFieldSelections(): void {
    try {
      const savedSelections = localStorage.getItem('pydetect-field-selections');
      if (savedSelections) this.selectedFields = JSON.parse(savedSelections);
    } catch (error) {
      console.warn('Could not load field selections from localStorage:', error);
      this.selectedFields = {};
    }
  }

  closeFieldSelector(): void { this.showFieldSelector = null; }

  goToRecords(): void { this.router.navigate(['/record']); }

  toggleFieldSelector(event?: Event): void {
    if (event) { event.preventDefault(); event.stopPropagation(); }
    const subgroupKey = `${this.currentSection}-${this.currentSubgroup}`;
    this.showFieldSelector = this.showFieldSelector === subgroupKey ? null : subgroupKey;
  }

  trackByField(index: number, field: string): string { return field; }

  toggleRecording(field?: string) {
    if (field) {
      if (this.recordingField === field) { this.recordingField = null; this.isRecording = false; }
      else { this.recordingField = field; this.isRecording = true; }
    } else {
      this.isRecording = !this.isRecording;
      if (!this.isRecording) this.recordingField = null;
    }
  }

  getUploadZoneIcon(field: string): string {
    const imageFields = new Set(['Photo Upload', 'Evidence Photos']);
    const videoFields = new Set(['Evidence Videos']);
    const documentFields = new Set(['Evidence Documents']);
    if (imageFields.has(field)) return 'fas fa-file-image';
    if (videoFields.has(field)) return 'fas fa-file-video';
    if (documentFields.has(field)) return 'fas fa-file-alt';
    const accept = (this.fileTypeConfig && this.fileTypeConfig[field]) || '';
    if (accept.includes('image/')) return 'fas fa-file-image';
    if (accept.includes('video/')) return 'fas fa-file-video';
    if (accept.includes('.pdf') || accept.includes('.doc')) return 'fas fa-file-alt';
    return 'fas fa-cloud-upload-alt';
  }

  getFileIcon(filename: string): string {
    const ext = filename.split('.').pop()?.toLowerCase();
    switch (ext) {
      case 'pdf': return 'fas fa-file-pdf';
      case 'doc':
      case 'docx': return 'fas fa-file-word';
      case 'jpg':
      case 'jpeg':
      case 'png':
      case 'gif': return 'fas fa-file-image';
      case 'mp4':
      case 'avi':
      case 'mov': return 'fas fa-file-video';
      default: return 'fas fa-file';
    }
  }

  isLastSubgroup(): boolean { const list = this.getSubgroups(); return list.indexOf(this.currentSubgroup) === list.length - 1; }

  canNextSubgroup(): boolean {
    if (this.isLastSubgroup()) return !(this.currentSection === 'notes' && this.currentSubgroup === 'Remark');
    return true;
  }

  canPrevSubgroup(): boolean {
    const subgroups = this.getSubgroups();
    const currentIndex = subgroups.indexOf(this.currentSubgroup);
    if (currentIndex > 0) return true;
    const sectionIndex = this.sectionKeys.indexOf(this.currentSection);
    return sectionIndex > 0;
  }

  previousSubgroup(): void {
    const subgroups = this.getSubgroups();
    const currentIndex = subgroups.indexOf(this.currentSubgroup);
    if (currentIndex > 0) { this.setSubgroup(subgroups[currentIndex - 1]); return; }
    const sectionIndex = this.sectionKeys.indexOf(this.currentSection);
    if (sectionIndex > 0) {
      const prevSection = this.sectionKeys[sectionIndex - 1];
      this.currentSection = prevSection;
      const prevSubgroups = Object.keys(this.sections[prevSection].subgroups);
      this.currentSubgroup = prevSubgroups[prevSubgroups.length - 1];
      this.showHelpFor = null;
      this.triggerAutoSave();
    }
  }

  nextSubgroup(): void {
    const subgroups = this.getSubgroups();
    const currentIndex = subgroups.indexOf(this.currentSubgroup);
    if (currentIndex < subgroups.length - 1) { this.setSubgroup(subgroups[currentIndex + 1]); return; }
    const sectionIndex = this.sectionKeys.indexOf(this.currentSection);
    if (sectionIndex < this.sectionKeys.length - 1) {
      const nextSection = this.sectionKeys[sectionIndex + 1];
      this.currentSection = nextSection;
      this.currentSubgroup = Object.keys(this.sections[nextSection].subgroups)[0];
      this.showHelpFor = null;
      this.triggerAutoSave();
    }
  }

  isSubmitting: boolean = false;
  submitProgress: number = 0;
  submitInterval: any;

  submitCurrentSection(): void {
    // Prevent submission if no data entered at all
    const hasFormData = Object.keys(this.formData).some(k => {
      const v = this.formData[k];
      return v !== null && v !== undefined && String(v).trim() !== '';
    });
    const hasUploadedFiles = Object.keys(this.uploadedFiles).some(k => (this.uploadedFiles[k] || []).length >0);
    if (!hasFormData && !hasUploadedFiles) {
      // Show non-blocking popup instead of alert
      this.showNoDataPopup = true;
      return;
    }

    const currentFields = this.getCurrentFields();
    const requiredFields = currentFields.filter(f => this.isFieldRequired(f));
    const missingFields = requiredFields.filter(f => !this.completedFields.has(f));
    if (missingFields.length >0) {
      alert(`Please complete the following required fields: ${missingFields.join(', ')}`);
      return;
    }
    // Prevent submission if Case ID duplicate exists
    if (this.fieldValidation['Case ID'] && this.fieldValidation['Case ID'].hasError) {
      this.showCaseIdExistsPopup = true;
      return;
    }

    // Start loading state
    this.isSubmitting = true;
    this.submitProgress =0;

    // Simulate progress (you can adjust timing as needed)
    this.submitInterval = setInterval(() => {
      this.submitProgress += Math.random() *30;
      if (this.submitProgress >=100) {
        this.submitProgress =100;
        clearInterval(this.submitInterval);

        // Simulate processing delay
        setTimeout(() => {
          this.finalizeSubmission();
        },500);
      }
    },200);
  }

  // Add a new method to finalize submission after loading:
  private finalizeSubmission(): void {
    // Save data first
    this.performAutoSave();

    
    const crime = {
      caseId: this.formData['Case ID'] || '',
      dateTime: this.formData['Date & Time (Entry)'] || '',
      crimeType: this.formData['Crime Type'] || '',
      location: this.formData['Location'] || '',
      victimName: this.formData['Victim Name'] || '',
      caseCategory: this.formData['Case Category'] || '',
      reportedBy: this.formData['Reported By'] || '',
      briefDescription: this.formData['Brief Description'] || '',
      'FIR / Ref #': this.formData['FIR / Ref #'] || '',
      'Occurred From': this.formData['Occurred From'] || '',
      'Occurred To': this.formData['Occurred To'] || '',
      'Jurisdiction / PS': this.formData['Jurisdiction / PS'] || '',
      'Scene Type': this.formData['Scene Type'] || ''
    };
    const suspect = {
      fullName: this.formData['Suspect Name'] || '',
      age: this.formData['Age'] || '',
      gender: this.formData['Gender'] || '',
      address: this.formData['Address'] || '',
      alias: this.formData['Alias / Nickname'] || ''
    };

    const notes = {
      status: this.formData['Investigative Status'] || this.formData['Status'] || 'Open',
      officerInCharge: this.formData['Investigating Officer'] || '',
      initialFindings: this.formData['Initial Findings'] || '',
      verifiedBy: this.formData['Verified By'] || ''
    };

    const legal = {
      witnessStatements: this.formData['Witness Statements'] || '',
      confessions: this.formData['Confessions'] || '',
      evidence: this.uploadedFiles['Evidence Files'] || []
    };
    this.caseStore.addOrUpdateFromInfoForm({ crime, suspect, notes, legal, formData: this.formData });
    /* this.showSubmitPopup = true;*/
    // Hide loader and show success popup
    this.isSubmitting = false;
    this.submitProgress = 0;
    this.showSubmitPopup = true;
  }
  

  onSubmitPopupClose(): void {
    this.showSubmitPopup = false;
    this.router.navigate(['/record'], { state: { formData: this.formData } });
  }

  // Load current user profile from localStorage key 'pydetect-current-user'
  private loadCurrentUser(): void {
    try {
      const raw = localStorage.getItem('pydetect-current-user');
      if (raw) this.currentUser = JSON.parse(raw);
      else this.currentUser = { name: 'Admin User', email: 'admin@gmail.com' };
    } catch (e) {
      this.currentUser = { name: 'Admin User' };
    }
  }

  getUserInitials(): string {
    if (!this.currentUser || !this.currentUser.name) return 'A';
    const parts = this.currentUser.name.trim().split(/\s+/);
    const first = parts[0] ? parts[0].charAt(0).toUpperCase() : 'A';
    const second = parts.length > 1 ? (parts[1].charAt(0) || '').toUpperCase() : '';
    return `${first}${second}`;
  }

  // Toggle profile menu (attached to template)
  toggleProfileMenu(ev?: Event): void {
    if (ev) ev.stopPropagation();
    this.showProfileMenu = !this.showProfileMenu;
    if (this.showProfileMenu) {
      try {
        const el = this.profileDisplayRef && this.profileDisplayRef.nativeElement;
        if (el) {
          const rect = el.getBoundingClientRect();
          const menuWidth = 260; // desired menu width
          const gap = 12; // gap between icon bottom and menu
          // Align menu right edge with icon right edge, clamp within viewport
          const leftUnclamped = Math.round(rect.right - menuWidth);
          const left = Math.min(Math.max(leftUnclamped, 8), Math.max(window.innerWidth - menuWidth - 8, 8));
          const top = Math.round(rect.bottom + gap);
          this.profileMenuStyle = {
            position: 'fixed',
            top: `${top}px`,
            left: `${left}px`,
            'min-width': `${menuWidth}px`,
            'z-index': '9999',
            padding: '10px'
          };
        }
      } catch (e) { /* ignore */ }
    } else {
      this.profileMenuStyle = {};
    }
  }

  logout(): void {
    try { localStorage.removeItem('pydetect-current-user'); } catch { }
    this.showProfileMenu = false;
    this.router.navigate(['/']);
  }

  // Handle navigation prefilling when routed from record page
  private handleNavigationPrefill(): void {
    try {
      // First try router navigation extras state (works during direct navigation)
      const nav = (this.router as any).getCurrentNavigation && (this.router as any).getCurrentNavigation();
      const state = nav && nav.extras && nav.extras.state ? nav.extras.state : (history && (history.state as any) ? (history.state as any) : null);

      const routeId = this.route.snapshot.paramMap.get('id') || this.route.snapshot.paramMap.get('caseId');

      if (state && state.prefillFormData) {
        // Use provided prefillFormData from recordpage
        this.formData = { ...(state.prefillFormData || {}) };
        if (state.case && state.case.caseId) this.editingCaseId = state.case.caseId;
        this.currentSection = 'crime';
        this.currentSubgroup = 'Identification & Timing';
        this.updateCompletionStatus();
      } else if (routeId) {
        // Try to load case by id from store
        const cases = this.caseStore.getPoliceCases();
        const found = cases.find((c: any) => (c.caseId || '') === routeId);
        if (found) {
          this.populateFromCaseObject(found);
        }
      } else if (state && state.case) {
        // fallback if only case object passed
        this.populateFromCaseObject(state.case);
      }
    } catch (e) {
      // ignore
    }
  }

  // Populate formData from a case object structure
  private populateFromCaseObject(c: any): void {
    try {
      this.formData = {};
      // If formData is already an object, copy values
      if (c.formData && typeof c.formData === 'object' && !Array.isArray(c.formData)) {
        Object.assign(this.formData, c.formData);
      }

      // If formData is an array of key/value pairs
      if (c.formData && Array.isArray(c.formData)) {
        (c.formData as Array<any>).forEach(kv => { if (kv && kv.key) this.formData[kv.key] = kv.value; });
      }

      // Map some top-level fields into formData for editing convenience
      if (c.caseId) this.formData['Case ID'] = c.caseId;
      if (c.crime) this.formData['Crime Type'] = c.crime;
      if (c.dateTime) this.formData['Date & Time (Entry)'] = c.dateTime;
      if (c.police && c.police.address) this.formData['Location'] = c.police.address;
      if (c.police && c.police.name) this.formData['Investigating Officer'] = c.police.name;
      if (c.accused && c.accused.name) this.formData['Suspect Name'] = c.accused.name;

      // mark editing id to avoid duplicate detection against itself
      if (c.caseId) this.editingCaseId = c.caseId;

      // Update selected values for Country/State/District if present
      if (this.formData['Country']) this.selectedValues['Country'] = this.formData['Country'];
      if (this.formData['State']) this.selectedValues['State'] = this.formData['State'];
      if (this.formData['District']) this.selectedValues['District'] = this.formData['District'];

      // Update completion state and validations
      this.updateCompletionStatus();
      for (const f of Object.keys(this.formData)) {
        this.validateField(f);
      }
    } catch (e) {
      // ignore
    }
  }

}