File size: 46,545 Bytes
0dcd2ca
 
 
 
6f093ab
463dbc3
 
73566f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
463dbc3
0dcd2ca
73566f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f093ab
463dbc3
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
import { Component, HostListener, ElementRef, ViewChild, AfterViewInit, OnInit, OnDestroy } from '@angular/core';
import { trigger, state, style, transition, animate } from '@angular/animations';
import { Subject, debounceTime, takeUntil } from 'rxjs';
import { Router } 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;
 constructor(private router: Router, 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 - Reverted to original values except for Identification & Timing
 readonly sectionKeys: ('crime' | 'suspect' | 'notes')[] = ['crime', 'suspect', 'notes'];
 readonly maxFieldsPerCard =8; // Reverted to original
 readonly maxFieldsPerSecondaryCard =8; // Reverted to original
 readonly maxFieldsPerCardIdentificationTiming =6; // Special for Identification & Timing
 readonly maxFieldsPerSecondaryCardIdentificationTiming =6; // Special for Identification & Timing
 
 @ViewChild('formCard1') formCard1!: ElementRef<HTMLDivElement>;
 @ViewChild('formCard2') formCard2!: ElementRef<HTMLDivElement>;
 @ViewChild('formCard3') formCard3!: ElementRef<HTMLDivElement>;

 // 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', 'Case 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'
 ]);

 // File type configurations
 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': '*'
 };

 // Track selected values (cascading dropdown logic)
 selectedValues: Record<string, string> = {};

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

 // Country/State/District data
 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'
 ];

 // Enhanced select options - Added missing field options
 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'],
 'riskLevel': ['Low', 'Medium', 'High', 'Critical'],
 'Confidentiality': ['Internal', 'Restricted', 'Sensitive', 'Sealed'],
 'Initial Actions Taken': ['Scene Secured', 'Medical Aid', 'Evidence Logged', 'Witness Statements', 'Suspect Detained', 'General', 'Other'],
 'Case 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'],
 '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
 'arrestCount': ['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[]> = {};

 // 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 & People': ['Location', 'Jurisdiction / PS', 'Scene Type', 'Reported By', 'Reported Contact', 'Witness Count', 'Victim Name', 'Victim Contact', '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', 'Evidence Storage Reference', 'Photos / Video?', 'CCTV Present?', 'CCTV Sources / IDs', 'Forensic Tests Required', 'Chain of Custody?', 'Scene Condition', 'Digital Evidence'], 
 'Operational Notes': ['Investigating Officer', 'Duty Person', 'Supervising Officer', 'Patrol Notes', 'Arrest Made', 'Arrest Location', 'Initial Actions Taken', 'riskLevel', 'Confidentiality'], 
 'Status & Linkage': ['Biometric / Forensic IDs', 'DNA Ref ID', 'Fingerprint ID', 'Case Status', 'Linked Cases', 'arrestCount', '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', 'Alias / Nickname', 'Age', 'Gender', 'Nationality', 'Nationality ID / Passport Number', 'Languages', 'Address', 'Known Aliases', 'Government ID'], 
   'Physical Description': ['Height (cm)', 'Weight (kg)', 'Tattoo Details', 'Hair Color', 'Scar Details', 'Distinguishing Marks', 'Build', 'Eye Color', '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'], 
 '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.',
 'Reported Contact': 'Contact details for the reporting party.',
 'Witness Count': 'Number of identified witnesses so far.',
 'Victim Name': 'Primary victim name (or placeholder if protected).',
 'Victim Contact': 'Phone / email / other contact channel for victim.',
 '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.',

 // 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.',
 'riskLevel': '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.',
 'Case Status': 'Lifecycle status (Open / Active / Closed etc.).',
 'Linked Cases': 'Related or associated case identifiers.',
 'arrestCount': '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.',
 '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.',

 // 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.'
 };

 subgroupIcons: any = {
 'Identification & Timing': 'fas fa-clock',
 'Location & People': '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 {
 // Set up autosave
 this.autoSave$.pipe(
 debounceTime(2000),
 takeUntil(this.destroy$)
 ).subscribe(() => {
 this.performAutoSave();
 });
 
 // Do NOT auto-load saved form data on page load/refresh to keep the form empty by default.
 // Load only field selections (UI prefs)
 this.loadFieldSelections();
 
 // If navigation state contains prefillFormData (when editing a case), merge it into formData.
 try {
 const navState = (history && (history as any).state) || null;
 const statePrefill = navState && navState.prefillFormData ? navState.prefillFormData : null;
 if (statePrefill && typeof statePrefill === 'object') {
 // Merge saved values into current formData
 this.formData = { ...(this.formData || {}), ...statePrefill };
 // Restore cascading dropdown selections 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'];
 // Recompute completion status
 this.updateCompletionStatus();
 } else {
 // Ensure form is empty when arriving without prefill (fresh/new case or refresh)
 this.formData = {};
 this.completedFields.clear();
 this.completedSubgroups.clear();
 this.completedSections.clear();
 }
 } catch (e) {
 // ignore
 }
 }

 ngAfterViewInit(): void {
 // No special scroll handling needed anymore
 }

 ngOnDestroy(): void {
 this.destroy$.next();
 this.destroy$.complete();
 }

 // Progress Calculation
 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 & People
 private isLocationAndPeoplePage(): boolean {
 return this.currentSubgroup === 'Location & People';
 }

 // 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
 }

 // 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();
 }

 getSecondaryFields(): string[] {
 // Return empty array for single card layout across all pages
 return [];
 }

 getTertiaryFields(): string[] {
 // Return empty array for single card layout across all pages
 return [];
 }
 
 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.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 and120';
 } 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 {
 // 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();
 }

 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);
 }

 // Get count of selected fields
 getSelectedFieldCount(): number {
 const subgroupKey = `${this.currentSection}-${this.currentSubgroup}`;
 const selections = this.selectedFields[subgroupKey];
 if (!selections) {
 return this.getCurrentFields().length; // All fields selected by default
 }
 return selections.length;
 }

 // Check if selection limit is reached
 isSelectionLimitReached(): boolean {
 return this.getSelectedFieldCount() >= this.maxSelectableFields;
 }

 // Reset field selection for current subgroup (clear all)
 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();
 // Do NOT close the popup here; keep it open for further selection
 }

 // Select all fields
 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();
 }

 // Select default fields (first10 or all if less than10) - Renamed for clarity
 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();
 }

 // Get dynamic max selectable based on available fields
 getDynamicMaxSelectable(): number {
 const totalFields = this.getTotalAvailableFieldsCount();
 return Math.min(this.maxSelectableFields, totalFields);
 }

 // Check if all fields are selected
 areAllFieldsSelected(): boolean {
 const subgroupKey = `${this.currentSection}-${this.currentSubgroup}`;
 const selections = this.selectedFields[subgroupKey];
 const totalFields = this.getCurrentFields().length;
 
 if (!selections) {
 return true; // All fields selected by default
 }
 
 return selections.length === totalFields;
 }

 // Check if no fields are selected
 areNoFieldsSelected(): boolean {
 const subgroupKey = `${this.currentSection}-${this.currentSubgroup}`;
 const selections = this.selectedFields[subgroupKey];
 
 if (!selections) {
 return false; // All fields selected by default
 }
 
 return selections.length ===0;
 }

 // Navigation and section management methods
 getSubgroups(): string[] {
 return Object.keys(this.sections[this.currentSection].subgroups);
 }

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

 // Enhanced document click handler
 @HostListener('document:click', ['$event'])
 handleDoc(event: Event): void {
 this.showHelpFor = null;
 // Only close field selector if click is outside the popup
 const target = event.target as HTMLElement;
 if (this.showFieldSelector && !target.closest('.field-selector-container')) {
 this.closeFieldSelector();
 }
 }

 // Handle section/subgroup changes to refresh field selector
 setSubgroup(key: string): void {
 // Close field selector when changing subgroups
 this.closeFieldSelector();
 this.currentSubgroup = key;
 this.showHelpFor = null;
 this.triggerAutoSave();
 }

 // Section and subgroup completion status
 isSectionCompleted(section: string): boolean {
 return this.completedSections.has(section);
 }

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

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

 // Field handling and validation
 onFieldChange(field: string): void {
 this.validateField(field);
 this.triggerAutoSave();
 }

 // Auto-save functionality
 private triggerAutoSave(): void {
 this.autoSave$.next();
 }

 private performAutoSave(): void {
 this.isAutoSaving = true;
 this.autoSaveStatus = 'Saving...';
 
 // Save to localStorage
 this.saveFormData();
 
 // Simulate save delay
 setTimeout(() => {
 this.isAutoSaving = false;
 this.autoSaveStatus = 'Saved';
 
 // Reset status after a moment
 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';
 }
 }

 // Dropdown options and cascading logic
 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;
 } else if (this.selectedValues['State']) {
 return [];
 } else {
 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;
 
 // Clear dependent fields
 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();
 }

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

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

 // File upload functionality
 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();
 }
 }

 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();
 }
 }

 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] || '*';
 }

 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';
 }
 }

 // Navigation helper methods for floating buttons
 getPreviousSubgroup(): string {
 const list = this.getSubgroups();
 const currentIndex = list.indexOf(this.currentSubgroup);
 return currentIndex >0 ? list[currentIndex -1] : '';
 }

 getNextSubgroup(): string {
 const subgroups = this.getSubgroups();
 const currentIndex = subgroups.indexOf(this.currentSubgroup);
 if (currentIndex < subgroups.length -1) {
 return subgroups[currentIndex +1];
 }
 // If last subgroup, return first subgroup of next section if exists
 const sectionIndex = this.sectionKeys.indexOf(this.currentSection);
 if (sectionIndex < this.sectionKeys.length -1) {
 const nextSection = this.sectionKeys[sectionIndex +1];
 return Object.keys(this.sections[nextSection].subgroups)[0];
 }
 return '';
 }

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

 canNextSubgroup(): boolean {
 // Enable Next on last subgroup if not notes section
 if (this.isLastSubgroup()) {
 return !(this.currentSection === 'notes' && this.currentSubgroup === 'Remark');
 }
 return true;
 }

 nextSubgroup(): void {
 const subgroups = this.getSubgroups();
 const currentIndex = subgroups.indexOf(this.currentSubgroup);
 // If not last subgroup, go to next subgroup
 if (currentIndex < subgroups.length -1) {
 this.setSubgroup(subgroups[currentIndex +1]);
 return;
 }
 // If last subgroup, go to first subgroup of next section (if exists)
 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();
 }
 }

 prevSubgroup(): void {
 const subgroups = this.getSubgroups();
 const currentIndex = subgroups.indexOf(this.currentSubgroup);
 if (currentIndex >0) {
 this.setSubgroup(subgroups[currentIndex -1]);
 return;
 }
 // If first subgroup, go to last subgroup of previous section (if exists)
 const sectionIndex = this.sectionKeys.indexOf(this.currentSection);
 if (sectionIndex >0) {
 const prevSection = this.sectionKeys[sectionIndex -1];
 const prevSubgroups = Object.keys(this.sections[prevSection].subgroups);
 this.currentSection = prevSection;
 this.currentSubgroup = prevSubgroups[prevSubgroups.length -1];
 this.showHelpFor = null;
 this.triggerAutoSave();
 }
 }

 submitCurrentSection(): void {
 // Perform final validation
 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;
 }

 this.performAutoSave();

 // Map flat formData to nested structure expected by addOrUpdateFromInfoForm
 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['Case 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'] || []
 };

 // Pass the full flat formData object so CaseStoreService can save raw inputs
 this.caseStore.addOrUpdateFromInfoForm({ crime, suspect, notes, legal, formData: this.formData });
 // Show popup first
 this.showSubmitPopup = true;
 }

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

 // Keyboard navigation
 @HostListener('document:keydown', ['$event'])
 handleKeydown(event: KeyboardEvent): void {
 // Keyboard navigation
 if (event.ctrlKey && event.key === 'ArrowRight') {
 event.preventDefault();
 this.nextSubgroup();
 } else if (event.ctrlKey && event.key === 'ArrowLeft') {
 event.preventDefault();
 this.prevSubgroup();
 } else if (event.ctrlKey && event.key === 's') {
 event.preventDefault();
 this.performAutoSave();
 } else if (event.key === 'Escape') {
 this.closeFieldInfo();
 }
 }

 // Toggle field selector visibility
 toggleFieldSelector(event?: Event): void {
 if (event) {
 event.preventDefault();
 event.stopPropagation();
 }

 const subgroupKey = `${this.currentSection}-${this.currentSubgroup}`;
 this.showFieldSelector = this.showFieldSelector === subgroupKey ? null : subgroupKey;
 }

 // Close field selector
 closeFieldSelector(): void {
 this.showFieldSelector = null;
 }

 // Save field selections to localStorage
 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);
 }
 }

 // Load field selections from localStorage
 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 = {};
 }
 }

 // Track by function for ngFor optimization
 trackByField(index: number, field: string): string {
 return field;
 }

 toggleRecording() {
 this.isRecording = !this.isRecording;
 // Add actual recording logic here if needed
 // For now, just toggles the state
 }

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

}