File size: 42,703 Bytes
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ee381
 
 
 
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ee381
 
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ee381
 
 
 
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8885c59
38fa174
 
 
8885c59
38fa174
8885c59
 
38fa174
 
 
 
 
 
 
8885c59
 
 
38fa174
 
 
8885c59
38fa174
 
 
8885c59
38fa174
 
 
 
 
 
 
 
8885c59
38fa174
 
 
8885c59
38fa174
 
 
8885c59
38fa174
 
 
8885c59
38fa174
 
 
 
 
8885c59
38fa174
 
 
 
8885c59
 
 
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ee381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38fa174
 
d1ee381
38fa174
d1ee381
38fa174
 
 
 
 
d1ee381
38fa174
d1ee381
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ee381
 
 
 
 
 
 
 
 
 
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ee381
 
 
 
 
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ee381
 
 
 
 
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ee381
 
 
 
 
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ee381
 
 
 
 
 
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ee381
 
 
 
 
 
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
d1ee381
 
 
 
 
 
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
d1ee381
 
 
 
 
 
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
d1ee381
 
 
 
 
 
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
d1ee381
 
 
 
 
 
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
d1ee381
 
 
 
 
 
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ee381
 
 
 
38fa174
 
 
 
d1ee381
 
 
 
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ee381
 
 
 
 
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ee381
 
 
 
 
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1ee381
38fa174
 
 
d1ee381
38fa174
 
d1ee381
 
 
 
38fa174
 
 
 
 
 
 
 
d1ee381
 
 
 
 
 
 
 
 
 
 
 
 
38fa174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Component, OnInit, OnDestroy, ChangeDetectorRef, Injector, HostListener } from '@angular/core';
import { Router, RouterOutlet, NavigationEnd } from '@angular/router';
import { CommonModule } from '@angular/common';
import { Subscription } from 'rxjs';
import { SignupService } from './auth/sign-up/sign-up.service';
import { AuthService } from './services/auth.service';
import { SignInComponent } from './auth/sign-in/sign-in.component';
import { SignUpComponent } from './auth/sign-up/sign-up.component';
import { LlmQaService } from './services/llm-qa.service';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, CommonModule, SignInComponent, SignUpComponent],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  title = 'py-match';
  showMarriageSubnav = false;
  showRoleSubnav = false;
  activeRoleMenu: string | null = null;
  isSignedIn = false;
  authModal: 'signin' | 'signup' | null = null;
  userFullName: string = '';
  userInitials: string = '';
  showChatbot = false;

  // Progress tracking properties
  profileCompleted = false;
  expectationsCompleted = false;
  assessmentCompleted = false;
  matchingCompleted = false;

  // Assessment popup state
  showAssessmentPopup = false;

  // NEW: Sign out confirmation popup
  showSignOutPopup = false;

  // Mobile menu properties
  showMobileNav = false;
  activeRoleMenuMobile: string | null = null;

  private authSubscription!: Subscription;
  private routerEventsSub!: Subscription;

  constructor(

    private router: Router,

    private signupService: SignupService,

    private authService: AuthService,

    private changeDetectorRef: ChangeDetectorRef,

    private injector: Injector

  ) {
    // Expose component instance for direct access
    (window as any).appComponentRef = this;
  }

  ngOnInit() {
    // Listen for auth state changes from other components
    window.addEventListener('authStateChanged', () => {
      console.log('?? Auth state change detected in AppComponent');
      this.changeDetectorRef.detectChanges();
    });

    // Subscribe to authentication state changes from AuthService
    this.authSubscription = this.authService.userId$.subscribe(userId => {
      this.isSignedIn = !!userId;
      if (userId) {
        this.loadUserData(userId);
        console.log('? User signed in, loading data for user:', userId);
      } else {
        this.userFullName = '';
        this.userInitials = '';
        // Load progress from localStorage when signed out
        this.loadProgressFromAnySource();
        console.log('?? User signed out, loading preserved progress from localStorage');
      }
      // Force UI update when auth state changes
      this.changeDetectorRef.detectChanges();
    });

    // Listen for progress updates from other components
    this.setupProgressListeners();

    // Also listen for storage events to sync across tabs
    window.addEventListener('storage', (event) => {
      if (event.key?.startsWith('user_progress_')) {
        this.syncProgressFromStorage();
      }
    });

    // Load progress from localStorage on initial app load (for returning users)
    this.loadInitialProgress();

    // Expose methods globally for direct access
    (window as any).markProfileCompleted = () => {
      this.markStepCompleted('profile');
    };
    (window as any).markExpectationsCompleted = () => {
      this.markStepCompleted('expectations');
    };
    (window as any).markAssessmentCompleted = () => {
      this.markStepCompleted('assessment');
    };
    (window as any).markMatchingCompleted = () => {
      this.markStepCompleted('matching');
    };

    // Listen to router events to toggle body scroll
    this.routerEventsSub = this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        this.toggleBodyScroll();
        // Close mobile nav on navigation
        this.showMobileNav = false;
      }
    });
    // Initial check
    this.toggleBodyScroll();
  }

  ngOnDestroy() {
    if (this.authSubscription) {
      this.authSubscription.unsubscribe();
    }
    // Clean up global methods
    if ((window as any).markProfileCompleted) {
      delete (window as any).markProfileCompleted;
    }
    if ((window as any).markExpectationsCompleted) {
      delete (window as any).markExpectationsCompleted;
    }
    if ((window as any).markAssessmentCompleted) {
      delete (window as any).markAssessmentCompleted;
    }
    if ((window as any).markMatchingCompleted) {
      delete (window as any).markMatchingCompleted;
    }
    if ((window as any).appComponentRef) {
      delete (window as any).appComponentRef;
    }
    if (this.routerEventsSub) {
      this.routerEventsSub.unsubscribe();
    }

    // Remove event listeners
    window.removeEventListener('authStateChanged', () => { });
    window.removeEventListener('storage', () => { });
  }

  // NEW: Load progress on initial app load (for returning users)
  private loadInitialProgress(): void {
    // Always load progress on app initialization, regardless of auth state
    this.loadProgressFromAnySource();
    console.log('?? Initial progress loaded:', {
      profile: this.profileCompleted,
      expectations: this.expectationsCompleted,
      assessment: this.assessmentCompleted,
      matching: this.matchingCompleted,
      isSignedIn: this.isSignedIn
    });
  }

  // NEW: Try to load progress from any user in localStorage
  private tryToLoadProgressFromAnyUser(): void {
    // Look for any user progress in localStorage
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key?.startsWith('user_progress_')) {
        try {
          const progressData = JSON.parse(localStorage.getItem(key) || '{}');
          this.profileCompleted = progressData.profileCompleted || false;
          this.expectationsCompleted = progressData.expectationsCompleted || false;
          this.assessmentCompleted = progressData.assessmentCompleted || false;
          this.matchingCompleted = progressData.matchingCompleted || false;
          console.log('?? Loaded progress from localStorage (no user):', progressData);
          break;
        } catch (e) {
          console.error('Error parsing progress data:', e);
        }
      }
    }
  }

  private syncProgressFromStorage(): void {
    const userId = this.authService.userId;
    if (userId) {
      const progressData = localStorage.getItem(`user_progress_${userId}`);
      if (progressData) {
        try {
          const progress = JSON.parse(progressData);
          this.profileCompleted = progress.profileCompleted || false;
          this.expectationsCompleted = progress.expectationsCompleted || false;
          this.assessmentCompleted = progress.assessmentCompleted || false;
          this.matchingCompleted = progress.matchingCompleted || false;
          console.log('?? Progress synced from localStorage:', progress);
        } catch (e) {
          console.error('Error parsing progress data:', e);
        }
      } else {
        console.log('?? No progress data found in localStorage for user:', userId);
      }
    }
  }

  private setupProgressListeners(): void {
    // Listen for profile completion events
    window.addEventListener('profileCompleted', (event: any) => {
      console.log('?? PROFILE COMPLETED EVENT RECEIVED - AppComponent');
      console.log('?? Event details:', event.detail);

      this.profileCompleted = true;
      this.saveProgress();

      console.log('? Progress after update:', {
        profile: this.profileCompleted,
        expectations: this.expectationsCompleted,
        assessment: this.assessmentCompleted,
        matching: this.matchingCompleted
      });

      // Force UI update
      this.changeDetectorRef.detectChanges();
    });

    // Listen for expectations completion events
    window.addEventListener('expectationsCompleted', (event: any) => {
      console.log('?? EXPECTATIONS COMPLETED EVENT RECEIVED - AppComponent');
      this.expectationsCompleted = true;
      this.saveProgress();
      this.changeDetectorRef.detectChanges();
    });

    // Listen for assessment completion events
    window.addEventListener('assessmentCompleted', (event: any) => {
      console.log('?? ASSESSMENT COMPLETED EVENT RECEIVED - AppComponent');
      this.assessmentCompleted = true;
      this.saveProgress();
      this.changeDetectorRef.detectChanges();
    });

    // Listen for matching completion events
    window.addEventListener('matchingCompleted', (event: any) => {
      console.log('?? MATCHING COMPLETED EVENT RECEIVED - AppComponent');
      this.matchingCompleted = true;
      this.saveProgress();
      this.changeDetectorRef.detectChanges();
    });
  }

  // UPDATED: Load user data and check database progress
  private loadUserData(userId: number): void {
    this.getUserInfo(userId);
    this.checkDatabaseProgress(userId);
  }

  private getUserInfo(userId: number): void {
    const userData = sessionStorage.getItem('user_data');
    if (userData) {
      try {
        const user = JSON.parse(userData);
        this.userFullName = user.name || '';
        this.userInitials = this.getInitials(this.userFullName);
        return;
      } catch (e) {
        console.error('Error parsing user data from storage:', e);
      }
    }

    this.userFullName = 'User';
    this.userInitials = 'US';
  }

  private getInitials(fullName: string): string {
    if (!fullName) return 'US';

    const names = fullName.trim().split(' ');
    if (names.length === 1) {
      return names[0].substring(0, 2).toUpperCase();
    } else {
      return (names[0].substring(0, 1) + names[names.length - 1].substring(0, 1)).toUpperCase();
    }
  }

  // UPDATED: Check database progress for all steps - FIXED to properly handle responses
  private checkDatabaseProgress(userId: number): void {
    if (!userId) return;

    console.log('?? Checking database progress for user:', userId);

    // 1. Check Marriage profile completion
    this.signupService.checkMarriageProfile(userId).subscribe({
      next: (profileRes: any) => {
        const profileExists = profileRes.exists || false;
        console.log('? Marriage profile check response:', profileExists);

        // Only change state if the database explicitly confirms completion
        // We do NOT set it to false here to prevent UI locking during network lag
        if (profileExists) {
          this.profileCompleted = true;
          this.saveProgress();
          this.changeDetectorRef.detectChanges();
        }
      },
      error: (err: any) => {
        // In production (Hugging Face), requests may timeout or fail due to CORS/Latency
        // We keep the local state (from localStorage) instead of forcing it to false
        console.error('? Marriage profile check API error:', err);
      }
    });

    // 2. Check Expectations completion
    this.signupService.checkExpectations(userId).subscribe({
      next: (expectationsRes: any) => {
        const expectationsExists = expectationsRes.exists || false;
        console.log('? Expectations check response:', expectationsExists);

        if (expectationsExists) {
          this.expectationsCompleted = true;
          this.saveProgress();
          this.changeDetectorRef.detectChanges();
        }
      },
      error: (err: any) => {
        console.error('? Expectations check API error:', err);
      }
    });

    // 3. Check Assessment completion
    this.signupService.checkAssessment(userId).subscribe({
      next: (assessmentRes: any) => {
        const assessmentExists = assessmentRes.exists || false;
        console.log('? Assessment check response:', assessmentExists);

        if (assessmentExists) {
          this.assessmentCompleted = true;
          this.matchingCompleted = true;
          this.saveProgress();
          this.changeDetectorRef.detectChanges();
        }
      },
      error: (err: any) => {
        console.error('? Assessment check API error:', err);
      }
    });
  }




  private saveProgress(): void {
    const userId = this.authService.userId;

    const progressData = {
      profileCompleted: this.profileCompleted,
      expectationsCompleted: this.expectationsCompleted,
      assessmentCompleted: this.assessmentCompleted,
      matchingCompleted: this.matchingCompleted,
      lastUpdated: new Date().toISOString()
    };

    if (userId) {
      // Save user-specific progress
      localStorage.setItem(`user_progress_${userId}`, JSON.stringify(progressData));
      console.log('?? Progress saved to user localStorage:', progressData);
    } else {
      // Save anonymous progress
      localStorage.setItem('anonymous_progress', JSON.stringify(progressData));
      console.log('?? Progress saved to anonymous localStorage:', progressData);
    }
  }

  get isIntroPage(): boolean {
    const url = (this.router.url || '').split('?')[0];
    return url === '/' || url.startsWith('/intro');
  }

  get isMatchingPage(): boolean {
    const url = (this.router.url || '').split('?')[0];
    return url.startsWith('/matchinglist');
  }

  // ? ADDED: Calculate progress percentage
  getProgressPercentage(): number {
    const totalSteps = 4;
    const completedSteps = [
      this.profileCompleted,
      this.expectationsCompleted,
      this.assessmentCompleted,
      this.matchingCompleted
    ].filter(Boolean).length;

    return (completedSteps / totalSteps) * 100;
  }

  // ? ADDED: Navigation methods
  goHome(): void {
    // If already on intro/home page, just scroll to top smoothly
    if (this.isIntroPage) {
      try {
        window.scrollTo({ top: 0, behavior: 'smooth' });
      } catch (e) {
        // fallback
        window.scrollTo(0, 0);
      }
      return;
    }

    this.router.navigate(['/']);
  }

  // Scroll methods
  scrollToFeatures(): void {
    const featuresElement = document.getElementById('features');
    if (featuresElement) {
      featuresElement.scrollIntoView({ behavior: 'smooth' });
    }
  }

  scrollToJourney(): void {
    const journeyElement = document.getElementById('journey');
    if (journeyElement) {
      journeyElement.scrollIntoView({ behavior: 'smooth' });
    }
  }

  /**

   * Scroll to FAQ section (specialTitle) from any page.

   * If not on intro page, navigate to intro then scroll.

   */
  scrollToFAQ(): void {
    const scrollToFaqElement = (el: Element | null) => {
      if (!el) return;
      try {
        el.scrollIntoView({ behavior: 'smooth', block: 'start' });
      } catch (e) {
        // fallback
        (el as HTMLElement).scrollIntoView();
      }
    };

    const findFaqTarget = (): Element | null => {
      // Prefer the section container over the heading
      const sectionEl = document.querySelector('.special-content');
      if (sectionEl) return sectionEl;
      // fallback to heading id if present
      return document.getElementById('specialTitle');
    };

    // If already on intro page, scroll directly
    if (this.isIntroPage) {
      const faqSection = findFaqTarget();
      if (faqSection) {
        scrollToFaqElement(faqSection);
      }
    } else {
      // Navigate to intro page, then scroll after navigation
      this.router.navigate(['/']).then(() => {
        setTimeout(() => {
          const faqSection = findFaqTarget();
          if (faqSection) {
            scrollToFaqElement(faqSection);
          }
        }, 300);
      });
    }
  }

  // Role subnavigation methods
  toggleRoleSubnav(): void {
    this.showRoleSubnav = !this.showRoleSubnav;
    if (!this.showRoleSubnav) {
      this.activeRoleMenu = null;
    }
  }

  hideRoleSubnav(): void {
    this.showRoleSubnav = false;
    this.activeRoleMenu = null;
  }

  toggleRoleMenu(menu: string): void {
    this.activeRoleMenu = this.activeRoleMenu === menu ? null : menu;
  }

  // Mobile menu methods
  toggleRoleMenuMobile(menu: string): void {
    this.activeRoleMenuMobile = this.activeRoleMenuMobile === menu ? null : menu;
  }

  closeMobileNav(): void {
    this.showMobileNav = false;
    this.activeRoleMenuMobile = null;
  }

  // UPDATED: Progress step validation - FIXED to properly check database progress
  isStepEnabled(step: string): boolean {
    console.log(`?? Checking if step "${step}" is enabled:`, {
      profile: this.profileCompleted,
      expectations: this.expectationsCompleted,
      assessment: this.assessmentCompleted,
      matching: this.matchingCompleted,
      isSignedIn: this.isSignedIn
    });

    // If user is not signed in, only allow profile step
    if (!this.isSignedIn) {
      return step === 'profile';
    }

    // For signed-in users, steps remain enabled once completed
    switch (step) {
      case 'profile':
        return true; // Always enabled for signed-in users

      case 'expectations':
        // Enabled if profile is completed OR if expectations were already completed
        return this.profileCompleted || this.expectationsCompleted;

      case 'assessment':
        // Enabled if expectations are completed OR if assessment was already completed
        return this.expectationsCompleted || this.assessmentCompleted;

      case 'matching':
        // Enabled if assessment is completed OR if matching was already completed
        return this.assessmentCompleted || this.matchingCompleted;

      default:
        return false;
    }
  }

  // UPDATED: Navigation method that directly navigates to profile
  navigateToProfile(role: string): void {
    const userId = this.authService.userId;
    if (!userId) {
      this.authModal = 'signin';
      return;
    }

    // Close mobile nav if open
    if (this.showMobileNav) {
      this.showMobileNav = false;
    }

    // Directly navigate to profile, don't use next step logic
    console.log('?? AppComponent - Direct navigation to profile for role:', role);

    this.router.navigate(['/question-answer'], {
      queryParams: {
        role: role,
        user_id: userId
      }
    });
  }

  // Helper method to determine next step (same logic as IntroPageComponent)
  private getNextAvailableStep(): string {
    console.log('?? AppComponent - Progress data for navigation:', {
      profile: this.profileCompleted,
      expectations: this.expectationsCompleted,
      assessment: this.assessmentCompleted,
      matching: this.matchingCompleted
    });

    // Use the same logic as sub-nav to determine next step
    if (this.isStepEnabled('profile') && !this.profileCompleted) {
      console.log('?? Next step: Profile (enabled and not completed)');
      return 'profile';
    } else if (this.isStepEnabled('expectations') && !this.expectationsCompleted) {
      console.log('?? Next step: Expectations (enabled and not completed)');
      return 'expectations';
    } else if (this.isStepEnabled('assessment') && !this.assessmentCompleted) {
      console.log('?? Next step: Assessment (enabled and not completed)');
      return 'assessment';
    } else if (this.isStepEnabled('matching') && !this.matchingCompleted) {
      console.log('?? Next step: Matching (enabled and not completed)');
      return 'matching';
    } else {
      // If all steps are completed, default to matching
      console.log('?? Next step: Matching (all steps completed or default)');
      return 'matching';
    }
  }

  // Helper method to navigate to specific step
  private navigateToStep(step: string, role: string): void {
    const userId = this.authService.userId;
    if (!userId) return;

    switch (step) {
      case 'profile':
        this.router.navigate(['/question-answer'], {
          queryParams: {
            role: role,
            user_id: userId
          }
        });
        break;

      case 'expectations':
        this.router.navigate(['/userpreferences'], {
          queryParams: { user_id: userId }
        });
        break;

      case 'assessment':
        // Direct navigation to assessment without checking completion
        this.router.navigate(['/llmquiz'], {
          queryParams: {
            user_id: userId,
            show_welcome: 'true'
          }
        });
        break;

      case 'matching':
        this.router.navigate(['/matchinglist'], {
          queryParams: { user_id: userId }
        });
        break;

      default:
        // Default to profile if something goes wrong
        this.router.navigate(['/question-answer'], {
          queryParams: {
            role: role,
            user_id: userId
          }
        });
    }
  }

  navigateToExpectations(role: string): void {
    const userId = this.authService.userId;
    console.log('?? Navigate to expectations - User ID:', userId);

    if (!userId) {
      console.log('User not authenticated, showing signin modal');
      this.authModal = 'signin';
      return;
    }

    if (!this.isStepEnabled('expectations')) {
      alert('Please complete your Profile first before setting expectations.');
      return;
    }

    console.log('? Navigating to user preferences...');
    this.hideRoleSubnav();

    // Close mobile nav if open
    if (this.showMobileNav) {
      this.showMobileNav = false;
    }

    this.router.navigate(['/userpreferences'], {
      queryParams: { user_id: userId }
    }).then(success => {
      console.log('? Navigation successful:', success);
    }).catch(error => {
      console.error('? Navigation failed:', error);
    });
  }

  // UPDATED: navigateToAssessment method to show popup instead of direct navigation
  navigateToAssessment(role: string): void {
    const userId = this.authService.userId;
    if (!userId) {
      this.authModal = 'signin';
      return;
    }

    if (!this.isStepEnabled('assessment')) {
      alert('Please complete Your Expectations first before taking the assessment.');
      return;
    }

    // Close mobile nav if open
    if (this.showMobileNav) {
      this.showMobileNav = false;
    }

    // ? FIXED: Use injected LlmQaService
    const llmQaService = this.injector.get(LlmQaService);

    llmQaService.checkAssessmentCompletion(userId.toString()).subscribe({
      next: (response: any) => {
        if (response.has_taken_assessment) {
          // User already took assessment, show popup instead of navigating
          console.log('?? User has already taken assessment, showing popup');
          this.showAssessmentPopup = true;
          this.hideRoleSubnav();
        } else {
          // User hasn't taken assessment, proceed to quiz
          this.hideRoleSubnav();
          this.router.navigate(['/llmquiz'], {
            queryParams: {
              user_id: userId,
              show_welcome: 'true'
            }
          });
        }
      },
      error: (err: any) => {
        console.error('Error checking assessment completion:', err);
        // If check fails, allow navigation to quiz
        this.hideRoleSubnav();
        this.router.navigate(['/llmquiz'], {
          queryParams: {
            user_id: userId,
            show_welcome: 'true'
          }
        });
      }
    });
  }

  navigateToMatchingProfile(role: string): void {
    const userId = this.authService.userId;
    if (!userId) {
      this.authModal = 'signin';
      return;
    }

    if (!this.isStepEnabled('matching')) {
      alert('Please complete the Assessment first to view your matching profile.');
      return;
    }

    this.hideRoleSubnav();

    // Close mobile nav if open
    if (this.showMobileNav) {
      this.showMobileNav = false;
    }

    this.router.navigate(['/matchinglist'], {
      queryParams: { user_id: userId }
    });
  }

  // NEW: Method to handle popup actions
  closeAssessmentPopup(): void {
    this.showAssessmentPopup = false;
  }

  navigateToMatchingFromPopup(): void {
    this.showAssessmentPopup = false;
    const userId = this.authService.userId;
    if (userId) {
      this.router.navigate(['/matchinglist'], {
        queryParams: { user_id: userId }
      });
    }
  }

  goHomeFromPopup(): void {
    this.showAssessmentPopup = false;
    this.goHome();
  }

  // Other navigation methods remain the same...
  navigateToJobRequirements(): void {
    const userId = this.authService.userId;
    if (!userId) {
      this.authModal = 'signin';
      return;
    }
    this.hideRoleSubnav();

    // Close mobile nav if open
    if (this.showMobileNav) {
      this.showMobileNav = false;
    }

    console.log('Navigate to job requirements');
    this.router.navigate(['/job-requirements'], {
      queryParams: { user_id: userId }
    });
  }

  navigateToInterviewAssessment(): void {
    const userId = this.authService.userId;
    if (!userId) {
      this.authModal = 'signin';
      return;
    }
    this.hideRoleSubnav();

    // Close mobile nav if open
    if (this.showMobileNav) {
      this.showMobileNav = false;
    }

    console.log('Navigate to interview assessment');
    this.router.navigate(['/interview-assessment'], {
      queryParams: { user_id: userId }
    });
  }

  navigateToCandidateMatching(): void {
    const userId = this.authService.userId;
    if (!userId) {
      this.authModal = 'signin';
      return;
    }
    this.hideRoleSubnav();

    // Close mobile nav if open
    if (this.showMobileNav) {
      this.showMobileNav = false;
    }

    console.log('Navigate to candidate matching');
    this.router.navigate(['/candidate-matching'], {
      queryParams: { user_id: userId }
    });
  }

  navigateToBusinessGoals(): void {
    const userId = this.authService.userId;
    if (!userId) {
      this.authModal = 'signin';
      return;
    }
    this.hideRoleSubnav();

    // Close mobile nav if open
    if (this.showMobileNav) {
      this.showMobileNav = false;
    }

    console.log('Navigate to business goals');
    this.router.navigate(['/business-goals'], {
      queryParams: { user_id: userId }
    });
  }

  navigateToPartnershipAssessment(): void {
    const userId = this.authService.userId;
    if (!userId) {
      this.authModal = 'signin';
      return;
    }
    this.hideRoleSubnav();

    // Close mobile nav if open
    if (this.showMobileNav) {
      this.showMobileNav = false;
    }

    console.log('Navigate to partnership assessment');
    this.router.navigate(['/partnership-assessment'], {
      queryParams: { user_id: userId }
    });
  }

  navigateToPartnerMatching(): void {
    const userId = this.authService.userId;
    if (!userId) {
      this.authModal = 'signin';
      return;
    }
    this.hideRoleSubnav();

    // Close mobile nav if open
    if (this.showMobileNav) {
      this.showMobileNav = false;
    }

    console.log('Navigate to partner matching');
    this.router.navigate(['/partner-matching'], {
      queryParams: { user_id: userId }
    });
  }

  // Legacy methods
  toggleMarriageSubnav(): void {
    this.showMarriageSubnav = !this.showMarriageSubnav;
  }

  hideMarriageSubnav(): void {
    this.showMarriageSubnav = false;
  }

  onSelectRole(role: string): void {
    const userId = this.authService.userId;
    if (!userId) {
      this.authModal = 'signin';
      return;
    }

    if (role === 'marriage') {
      this.router.navigate(['/question-answer'], {
        queryParams: {
          role: 'marriage',
          user_id: userId
        }
      });
    } else {
      this.router.navigate(['/question-answer'], {
        queryParams: {
          role,
          user_id: userId
        }
      });
    }
    this.hideMarriageSubnav();
  }

  // Auth methods
  onOpenSignIn(): void {
    this.authModal = 'signin';
    // Close mobile nav if open
    if (this.showMobileNav) {
      this.showMobileNav = false;
    }
  }

  onOpenSignUp(): void {
    this.authModal = 'signup';
    // Close mobile nav if open
    if (this.showMobileNav) {
      this.showMobileNav = false;
    }
  }

  closeAuthModal(evt?: MouseEvent): void {
    if (evt && (evt.target as HTMLElement).classList.contains('modal-backdrop')) {
      this.authModal = null;
    } else if (!evt) {
      this.authModal = null;
    }
  }

  // Replace the existing onSignOut method with this:
  onSignOut(): void {
    console.log('?? Saving progress before sign out...');
    this.saveProgress();

    // Close mobile nav if open
    if (this.showMobileNav) {
      this.showMobileNav = false;
    }

    // Show the sign-out popup first
    this.showSignOutPopup = true;
    this.hideMarriageSubnav();
    this.hideRoleSubnav();

    console.log('?? Showing sign out popup, will logout after animation');
    console.log('?? Current progress state:', {
      profile: this.profileCompleted,
      expectations: this.expectationsCompleted,
      assessment: this.assessmentCompleted,
      matching: this.matchingCompleted
    });

    // Wait for the tick animation to complete (4 seconds) before actually logging out
    setTimeout(() => {
      this.showSignOutPopup = false;

      // Now perform the actual logout
      this.authService.logout();
      this.isSignedIn = false;
      this.userFullName = '';
      this.userInitials = '';

      this.changeDetectorRef.detectChanges();
      console.log('? Sign out completed after animation');
    }, 4000);

    this.changeDetectorRef.detectChanges();
  }

  // UPDATED: Auth success handlers
  onSignInSuccess(): void {
    this.isSignedIn = true;
    this.authModal = null;

    const userId = this.authService.userId;
    if (userId) {
      this.loadUserData(userId);
      this.mergeProgressOnSignIn(userId);
    }

    this.router.navigate(['/']);
  }

  onSignUpSuccess(): void {
    // After a successful sign-up, prompt the user to sign in.
    // Navigate home then open the sign-in modal so the user can complete authentication.
    this.router.navigate(['/']).then(() => {
      this.authModal = 'signin';
      // Ensure UI updates
      this.changeDetectorRef.detectChanges();
    });
  }

  // Legacy navigation methods
  navigateToProfileLegacy(): void {
    this.navigateToProfile('marriage');
  }

  navigateToExpectationsLegacy(): void {
    this.navigateToExpectations('marriage');
  }

  navigateToAssessmentLegacy(): void {
    this.navigateToAssessment('marriage');
  }

  navigateToMatchingProfileLegacy(): void {
    this.navigateToMatchingProfile('marriage');
  }

  navigateToLikedProfiles(): void {
    const userId = this.authService.userId;
    if (!userId) {
      this.authModal = 'signin';
      return;
    }
    this.router.navigate(['/matchinglist'], {
      queryParams: {
        user_id: userId,
        view: 'liked'
      }
    });
  }

  // Role selection
  selectRole(role: string): void {
    const userId = this.authService.userId;
    if (!userId) {
      this.authModal = 'signin';
      return;
    }
    this.signupService.assignRole(userId, role).subscribe({
      next: (res: any) => {
        console.log('Role saved:', res);
        this.router.navigate(['/question-answer'], {
          queryParams: {
            role,
            user_id: userId
          }
        });
      },
      error: (err: any) => {
        console.error('Role assign failed:', err);
        alert('Failed to assign role.');
      }
    });
  }

  // UPDATED: Chatbot methods to match IntroPageComponent functionality
  openChatbot(): void {
    // Close mobile nav if open
    if (this.showMobileNav) {
      this.showMobileNav = false;
    }

    this.showChatbot = true;
    document.body.style.overflow = 'hidden';
    this.changeDetectorRef.detectChanges();
  }

  closeChatbot(evt?: MouseEvent): void {
    if (evt && (evt.target as HTMLElement).classList.contains('modal-backdrop')) {
      this.showChatbot = false;
    } else if (!evt) {
      this.showChatbot = false;
    }

    if (!this.authModal) {
      document.body.style.overflow = '';
    }
    this.changeDetectorRef.detectChanges();
  }

  askQuickQuestion(question: string): void {
    console.log('Quick question asked:', question);
    this.addUserMessage(question);

    // Simulate bot response after delay
    setTimeout(() => {
      let response = '';

      switch (question) {
        case 'How does the matching process work?':
          response = 'Our matching process uses adaptive assessment technology combined with established psychological frameworks. You\'ll complete a 15-20 minute assessment, and our system analyzes your responses to find compatible matches based on behavioral patterns and compatibility factors.';
          break;
        case 'What personality models do you use?':
          response = 'We use several established psychological frameworks including the Big Five personality model (Openness, Conscientiousness, Extraversion, Agreeableness, Neuroticism), along with complementary models for specific contexts like marriage compatibility and workplace dynamics.';
          break;
        case 'How do I reset my password?':
          response = 'To reset your password, click on the "Sign In" button, then select "Forgot Password" on the login screen. You\'ll receive an email with instructions to reset your password. If you need further assistance, contact our support team at support@pykara.com.';
          break;
        case 'Contact support team':
          response = 'You can reach our human support team by emailing info@pykara.ai or calling +91 99941 90964. Our support hours are Monday-Friday, 9 AM - 6 PM EST. For urgent matters, please include "URGENT" in your email subject line.';
          break;
        default:
          response = 'Thank you for your question. Our support team will get back to you shortly. For immediate assistance, please contact us at support@pykara.com';
      }

      this.addBotMessage(response);
    }, 1000);
  }

  sendMessage(chatInput: any): void {
    const message = chatInput.value.trim();
    if (message) {
      console.log('Message sent:', message);
      this.addUserMessage(message);

      setTimeout(() => {
        this.addBotMessage('Thank you for your message. Our support team will review your question and get back to you within 24 hours. For immediate assistance, please contact us at info@pykara.ai or call +91 99941 90964.');
      }, 1000);

      chatInput.value = '';
    }
  }

  private addUserMessage(message: string): void {
    const chatMessages = document.querySelector('.chat-messages');
    if (chatMessages) {
      const userMessage = document.createElement('div');
      userMessage.className = 'message user-message';
      userMessage.innerHTML = `

        <div class="message-avatar">

          <i class="fa-solid fa-user"></i>

        </div>

        <div class="message-content">

          <p>${message}</p>

        </div>

      `;
      chatMessages.appendChild(userMessage);
      this.scrollToBottom();
    }
  }

  private addBotMessage(message: string): void {
    const chatMessages = document.querySelector('.chat-messages');
    if (chatMessages) {
      const botMessage = document.createElement('div');
      botMessage.className = 'message bot-message';
      botMessage.innerHTML = `

        <div class="message-avatar">

          <i class="fa-solid fa-robot"></i>

        </div>

        <div class="message-content">

          <p>${message}</p>

        </div>

      `;
      chatMessages.appendChild(botMessage);
      this.scrollToBottom();
    }
  }

  private scrollToBottom(): void {
    setTimeout(() => {
      const chatMessages = document.querySelector('.chat-messages');
      if (chatMessages) {
        chatMessages.scrollTop = chatMessages.scrollHeight;
      }
    }, 100);
  }

  // CORRECTED: Single onEsc method that handles all cases
  // Update onEsc method to close mobile nav
  @HostListener('document:keydown.escape')
  onEsc(): void {
    if (this.showSignOutPopup) {
      return;
    }

    if (this.showMobileNav) {
      this.showMobileNav = false;
      this.activeRoleMenuMobile = null;
    } else if (this.showChatbot) {
      this.closeChatbot();
    } else if (this.authModal) {
      this.closeAuthModal();
    } else if (this.showAssessmentPopup) {
      this.showAssessmentPopup = false;
    }
  }

  // Add click outside to close mobile nav
  @HostListener('document:click', ['$event'])
  onClickOutside(event: MouseEvent): void {
    const target = event.target as HTMLElement;
    if (this.showMobileNav &&
      !target.closest('.mobile-nav-overlay') &&
      !target.closest('.mobile-menu-toggle') &&
      !target.closest('.mobile-nav-link')) {
      this.showMobileNav = false;
      this.activeRoleMenuMobile = null;
    }
  }

  // Method to manually update progress
  updateProgress(step: string, completed: boolean): void {
    console.log(`?? Updating progress: ${step} = ${completed}`);
    switch (step) {
      case 'profile':
        this.profileCompleted = completed;
        break;
      case 'expectations':
        this.expectationsCompleted = completed;
        break;
      case 'assessment':
        this.assessmentCompleted = completed;
        break;
      case 'matching':
        this.matchingCompleted = completed;
        break;
    }
    this.saveProgress();
    this.changeDetectorRef.detectChanges();
  }

  // Add this method to trigger progress updates from other components
  markStepCompleted(step: string): void {
    console.log(`?? Marking step as completed: ${step}`);

    this.updateProgress(step, true);
    this.saveProgress();
    this.changeDetectorRef.detectChanges();

    const event = new CustomEvent(`${step}Completed`, {
      detail: { timestamp: Date.now() }
    });
    window.dispatchEvent(event);

    console.log(`? Step ${step} marked as completed`);
  }

  // Add a method to force progress refresh
  refreshProgress(): void {
    this.syncProgressFromStorage();
    this.changeDetectorRef.detectChanges();
  }

  // Debug method to check current state
  debugProgress(): void {
    console.log('?? DEBUG - Current Progress State:', {
      profileCompleted: this.profileCompleted,
      expectationsCompleted: this.expectationsCompleted,
      assessmentCompleted: this.assessmentCompleted,
      matchingCompleted: this.matchingCompleted,
      userId: this.authService.userId,
      localStorage: localStorage.getItem(`user_progress_${this.authService.userId}`)
    });
  }

  // NEW: Load progress from any available source (user-specific or general)
  private loadProgressFromAnySource(): void {
    const currentUserId = this.authService.userId;

    if (currentUserId) {
      this.syncProgressFromStorage();
    } else {
      const genericProgress = localStorage.getItem('anonymous_progress');
      if (genericProgress) {
        try {
          const progressData = JSON.parse(genericProgress);
          this.profileCompleted = progressData.profileCompleted || false;
          this.expectationsCompleted = progressData.expectationsCompleted || false;
          this.assessmentCompleted = progressData.assessmentCompleted || false;
          this.matchingCompleted = progressData.matchingCompleted || false;
          console.log('?? Loaded anonymous progress from localStorage:', progressData);
        } catch (e) {
          console.error('Error parsing anonymous progress data:', e);
        }
      } else {
        this.tryToLoadProgressFromAnyUser();
      }
    }
  }

  // NEW: Merge anonymous progress with user progress when signing in
  private mergeProgressOnSignIn(userId: number): void {
    const anonymousProgress = localStorage.getItem('anonymous_progress');
    let anonymousData: any = {};

    if (anonymousProgress) {
      try {
        anonymousData = JSON.parse(anonymousProgress);
        console.log('?? Found anonymous progress to merge:', anonymousData);
      } catch (e) {
        console.error('Error parsing anonymous progress:', e);
      }
    }

    const userProgress = localStorage.getItem(`user_progress_${userId}`);
    let userData: any = {};

    if (userProgress) {
      try {
        userData = JSON.parse(userProgress);
        console.log('?? Found existing user progress:', userData);
      } catch (e) {
        console.error('Error parsing user progress:', e);
      }
    }

    const mergedProgress = {
      profileCompleted: userData.profileCompleted || anonymousData.profileCompleted || false,
      expectationsCompleted: userData.expectationsCompleted || anonymousData.expectationsCompleted || false,
      assessmentCompleted: userData.assessmentCompleted || anonymousData.assessmentCompleted || false,
      matchingCompleted: userData.matchingCompleted || anonymousData.matchingCompleted || false,
      lastUpdated: new Date().toISOString()
    };

    localStorage.setItem(`user_progress_${userId}`, JSON.stringify(mergedProgress));

    this.profileCompleted = mergedProgress.profileCompleted;
    this.expectationsCompleted = mergedProgress.expectationsCompleted;
    this.assessmentCompleted = mergedProgress.assessmentCompleted;
    this.matchingCompleted = mergedProgress.matchingCompleted;

    localStorage.removeItem('anonymous_progress');

    console.log('? Progress merged after sign in:', mergedProgress);
    this.changeDetectorRef.detectChanges();
  }

  private toggleBodyScroll(): void {
    const url = (this.router.url || '').split('?')[0];
    if (url === '/' || url.startsWith('/intro')) {
      document.body.classList.add('body-scrollable');
    } else {
      document.body.classList.remove('body-scrollable');
    }
  }
}