File size: 110,313 Bytes
2406314
 
 
 
 
 
 
 
 
 
 
 
6cda4c0
 
2406314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6cda4c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2406314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
852e112
2406314
852e112
2406314
 
 
 
 
 
852e112
2406314
 
 
 
 
 
 
 
 
 
1550538
72b7ea3
 
 
 
2406314
 
 
452995f
2406314
 
852e112
434db75
 
852e112
434db75
 
 
21baed4
 
 
 
 
 
 
 
 
 
2406314
 
6499dd2
21baed4
452995f
1550538
72b7ea3
1550538
 
72b7ea3
 
 
1550538
2406314
 
6499dd2
 
 
 
 
feb8ed0
 
72b7ea3
 
6499dd2
72b7ea3
 
 
 
 
6499dd2
 
 
 
72b7ea3
 
 
 
a4f79b5
72b7ea3
 
 
 
 
 
 
feb8ed0
72b7ea3
 
 
 
 
 
feb8ed0
72b7ea3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
486da52
72b7ea3
486da52
72b7ea3
 
 
 
 
 
 
 
 
 
 
feb8ed0
72b7ea3
 
 
 
 
 
486da52
 
6499dd2
feb8ed0
 
 
 
 
 
72b7ea3
 
 
 
feb8ed0
 
 
 
 
 
 
 
 
72b7ea3
 
feb8ed0
72b7ea3
 
486da52
 
72b7ea3
 
 
 
 
 
 
 
 
 
a4f79b5
72b7ea3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6499dd2
 
452995f
1550538
 
 
 
452995f
 
 
 
 
2406314
1550538
 
 
 
 
 
 
4b917a8
 
 
 
1550538
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2406314
 
bac80cb
 
ef811a0
bac80cb
72b7ea3
 
bac80cb
 
 
 
 
 
2406314
 
 
1550538
bac80cb
2406314
 
 
 
 
 
 
 
 
 
 
 
21baed4
 
 
 
 
 
 
 
 
 
2406314
 
bac80cb
434db75
 
 
 
2406314
 
 
 
 
 
 
 
 
21baed4
 
2406314
 
 
434db75
 
 
 
21baed4
434db75
 
 
21baed4
434db75
 
 
 
 
 
 
 
2406314
434db75
21baed4
434db75
21baed4
2406314
 
 
 
 
ef811a0
2406314
 
bac80cb
 
2406314
 
 
 
 
 
 
 
 
852e112
2406314
 
 
 
 
e4a03b0
bcf5331
 
 
 
 
 
 
 
 
 
 
 
 
 
2406314
 
 
 
 
21baed4
2406314
 
 
 
 
c4e260a
 
2406314
 
 
c4e260a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
852e112
 
 
 
 
 
 
 
 
 
2406314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21baed4
2406314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21baed4
2406314
 
 
 
 
 
 
 
 
 
e4a03b0
9cb0593
2406314
 
 
 
50c2c98
 
 
 
 
e4a03b0
 
 
 
2406314
 
 
 
9cb0593
ceb28b9
9cb0593
 
 
 
 
 
ceb28b9
 
 
 
9cb0593
2406314
 
 
 
4fa59bf
2406314
 
275ae3a
2406314
e4a03b0
 
275ae3a
 
2406314
786e284
 
 
 
 
 
 
 
 
 
 
 
e4a03b0
275ae3a
 
 
 
 
 
 
 
 
 
 
 
 
e4a03b0
2406314
 
 
50c2c98
e4a03b0
 
50c2c98
 
e4a03b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2406314
 
 
e4a03b0
2406314
 
 
 
 
 
 
786e284
2406314
786e284
 
2406314
786e284
2406314
 
 
 
8549507
 
2406314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8549507
 
2406314
9cb0593
 
 
2406314
8549507
2406314
ceb28b9
 
 
65414d9
9cb0593
8549507
65414d9
 
 
9cb0593
ceb28b9
9cb0593
 
65414d9
 
 
 
 
2406314
8549507
9cb0593
 
2406314
 
8549507
2406314
 
 
 
9cb0593
 
 
 
 
 
 
 
 
 
65414d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8549507
 
 
 
 
e5cac10
8549507
 
 
 
2406314
 
 
2f0c7ec
 
9cb0593
2f0c7ec
1c911a4
2406314
 
8549507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c911a4
8549507
 
 
 
 
2406314
 
2f0c7ec
 
 
1c911a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fa59bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9cb0593
275ae3a
4fa59bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f0c7ec
fa9794c
 
 
2f0c7ec
 
65414d9
8549507
65414d9
2f0c7ec
 
 
 
1c911a4
8549507
1c911a4
8549507
2f0c7ec
1c911a4
8549507
 
2f0c7ec
1c911a4
 
 
 
 
 
65414d9
1c911a4
 
 
 
 
 
2f0c7ec
1c911a4
 
 
 
 
 
2f0c7ec
1c911a4
8549507
2f0c7ec
 
 
 
 
8549507
2f0c7ec
65414d9
8549507
fa9794c
8549507
2f0c7ec
 
2406314
 
 
 
 
 
 
 
 
 
8549507
2406314
 
 
 
 
 
 
 
 
 
 
 
 
 
2f0c7ec
2406314
 
 
8549507
2406314
8549507
 
 
 
 
 
 
 
2406314
1c911a4
2f0c7ec
 
 
 
 
2406314
 
 
 
 
 
 
 
ceb28b9
 
 
fa9794c
 
 
 
 
 
ceb28b9
 
 
fa9794c
 
 
ceb28b9
 
fa9794c
 
 
ceb28b9
fa9794c
ceb28b9
fa9794c
 
 
ceb28b9
 
275ae3a
fa9794c
 
 
 
 
 
 
 
 
 
 
 
 
 
ceb28b9
 
 
 
 
2406314
 
 
 
 
5f55975
 
2406314
 
b3df41b
dc5f42d
 
f8801bf
dab5d13
2406314
5f55975
 
2e35766
5f55975
 
 
 
 
 
 
2e35766
5f55975
 
 
 
6449691
 
 
 
 
 
2e575ed
 
6449691
1d280c3
0a62ad4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6449691
2406314
b3df41b
 
 
 
 
 
 
 
 
 
 
a4f79b5
 
2e575ed
f8801bf
 
a4f79b5
 
 
 
5f55975
dc5f42d
5f55975
b3df41b
 
 
 
 
2406314
 
b3df41b
 
 
 
 
 
 
 
 
 
 
2406314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b3df41b
 
 
d0dc58f
 
 
 
b3df41b
 
 
d0dc58f
 
b3df41b
 
 
2406314
5f55975
2406314
 
 
 
 
 
 
 
b3df41b
2406314
 
 
 
b3df41b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6cda4c0
 
 
 
 
 
b3df41b
 
 
 
 
 
 
6cda4c0
 
 
 
b3df41b
 
 
 
 
 
 
2406314
 
 
 
b3df41b
 
 
 
2406314
 
b3df41b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2406314
 
 
b3df41b
2406314
 
 
b3df41b
 
 
 
 
 
 
 
 
 
 
2406314
b3df41b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6cda4c0
 
b3df41b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2406314
 
 
d0dc58f
 
 
 
 
 
 
 
 
 
 
1294a80
 
d0dc58f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6cda4c0
1294a80
6cda4c0
1294a80
 
6cda4c0
 
d0dc58f
 
 
47ec8c1
1294a80
47ec8c1
 
1294a80
 
 
47ec8c1
d0dc58f
1294a80
 
 
 
 
 
47ec8c1
d0dc58f
47ec8c1
d0dc58f
 
 
 
 
 
 
 
 
 
b3df41b
2406314
 
 
b3df41b
 
 
 
 
2406314
 
b3df41b
 
2406314
 
 
b3df41b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f55975
 
 
0a2a220
 
5f55975
0a2a220
 
 
 
 
 
 
 
6449691
0a2a220
 
 
5f55975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a2a220
 
 
 
6449691
 
0a2a220
 
6449691
 
0a2a220
5f55975
 
6449691
0a62ad4
 
 
6449691
 
 
 
 
 
 
 
 
a4f79b5
6449691
1d280c3
 
 
 
 
 
 
6449691
 
 
 
0a62ad4
 
 
 
 
 
 
 
 
 
6449691
a4f79b5
6449691
 
1d280c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f55975
0a2a220
 
 
 
 
 
 
 
1d280c3
0a2a220
 
5f55975
 
 
 
 
0a2a220
 
 
 
 
 
 
 
5f55975
 
 
 
 
 
 
0a2a220
5f55975
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a2a220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc5f42d
 
 
 
 
 
 
e2c3c45
 
 
 
dc5f42d
e2c3c45
dc5f42d
 
 
 
 
 
e2c3c45
 
 
 
 
 
 
 
 
 
 
 
 
 
dc5f42d
 
 
 
 
 
 
 
 
 
 
 
 
 
2406314
 
 
 
5f55975
 
 
aedfc98
dc5f42d
5f55975
 
dab5d13
 
 
5f55975
b3df41b
 
ef811a0
af38f77
84e20ed
 
 
2e575ed
84e20ed
 
b3df41b
 
2406314
84e20ed
dab5d13
 
 
 
dc5f42d
e2c3c45
2406314
 
b3df41b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bac80cb
 
 
 
 
af38f77
 
 
 
2e575ed
 
 
 
 
 
433dee5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af38f77
 
 
 
2e575ed
 
 
 
 
 
 
 
 
 
433dee5
f8801bf
 
 
 
2e575ed
f8801bf
 
 
2e575ed
 
 
 
 
 
f8801bf
 
 
 
2e575ed
f8801bf
 
2e575ed
 
 
433dee5
2e575ed
 
433dee5
f8801bf
 
 
 
 
 
 
 
 
 
 
2e575ed
 
f8801bf
2e575ed
 
 
 
 
f8801bf
 
 
 
 
 
2e575ed
f8801bf
 
af38f77
 
 
 
 
 
f8801bf
2e575ed
f8801bf
 
 
 
 
af38f77
 
 
f8801bf
af38f77
 
 
2e575ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
433dee5
 
 
 
2e575ed
 
 
 
 
 
 
 
dab5d13
 
 
 
 
 
 
 
e2c3c45
dab5d13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aedfc98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dab5d13
aedfc98
b3df41b
5f55975
b3df41b
84e20ed
 
 
2e35766
84e20ed
 
 
 
 
 
 
 
 
 
 
 
 
bac80cb
84e20ed
 
b3df41b
 
 
 
 
 
 
 
 
 
 
 
 
2406314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59e06b1
 
 
 
 
 
 
 
 
 
 
 
 
 
bcf5331
59e06b1
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
/**
 * Explorer Consultant Bot -- Frontend JavaScript
 * Covers: Consultants, Browse, Analytics, Admin
 */

'use strict';

// =============================================================================
// SHARED UTILITIES
// =============================================================================

document.addEventListener('DOMContentLoaded', () => {
  initPageTransitions();

  document.querySelectorAll('.alert').forEach(el => {
    if (el.hidden) return;
    setTimeout(() => {
      el.style.transition = 'opacity 0.4s';
      el.style.opacity = '0';
      setTimeout(() => el.remove(), 400);
    }, 5000);
  });

  const path = window.location.pathname;
  if (path === '/consultants')  initConsultants();
  if (path === '/browse')       initBrowse();
  if (path === '/analytics')    initAnalytics();
  if (path === '/admin')        initAdmin();
});

window.addEventListener('pageshow', () => {
  document.body.classList.remove('page-leaving');
});

function initPageTransitions() {
  const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const transitionMs = reduceMotion ? 0 : 180;

  document.addEventListener('click', (event) => {
    if (!(event.target instanceof Element)) return;
    const link = event.target.closest('a[href]');
    if (!link || event.defaultPrevented) return;
    if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
    if (link.target && link.target !== '_self') return;
    if (link.hasAttribute('download') || link.dataset.noTransition === 'true') return;

    const url = new URL(link.href, window.location.href);
    if (url.origin !== window.location.origin) return;
    if (!/^https?:$/.test(url.protocol)) return;
    if (url.pathname === '/logout') return;
    if (url.pathname === window.location.pathname && url.search === window.location.search) return;

    event.preventDefault();
    document.body.classList.add('page-leaving');
    window.setTimeout(() => {
      window.location.assign(url.href);
    }, transitionMs);
  });
}

async function postJSON(url, data) {
  const r = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });
  const json = await r.json().catch(() => ({}));
  if (!r.ok) throw { status: r.status, detail: json.detail || r.statusText };
  return json;
}

function esc(s) {
  if (s === null || s === undefined) return '';
  return String(s)
    .replace(/&/g, '&')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}

function severityBadge(sev) {
  const cls = sev === 'High' ? 'pill-red' : sev === 'Medium' ? 'pill-orange' : sev === 'Low' ? 'pill-green' : 'pill-neutral';
  return sev
    ? '<span class="pill pill-dot ' + cls + '">' + esc(sev) + '</span>'
    : '<span class="text-muted">--</span>';
}

function confBar(val) {
  if (val == null) return '';
  const pct = Math.round(val * 100);
  return '<div class="consultant-confidence"><div><span>Confidence</span><strong>' + pct + '%</strong></div><div class="consultant-confidence-track"><span style="width:' + pct + '%"></span></div></div>';
}

// =============================================================================
// CONSULTANTS PAGE
// =============================================================================

// Globals injected by Jinja template:
//   SERVICES_MAP, TYPE_CLUSTER, GROUP_INTERNAL

let _lastPrediction = null;
let _consultantServices = [];
let _consultantDatePicker = {
  input: null,
  viewDate: new Date(),
};

function initConsultants() {
  _buildTypeOptions();
  resetConsultantServiceSelection();
  const ta = document.getElementById('quote');
  const cc = document.getElementById('char-counter');
  const ready = document.getElementById('quote-readiness');
  if (ta && cc) ta.addEventListener('input', () => {
    cc.textContent = ta.value.length + ' / 2000';
    if (ready) ready.textContent = ta.value.trim().length >= 10 ? 'Ready to analyze' : 'Minimum 10 characters';
    const noObj = document.getElementById('no-objection-panel');
    if (noObj) noObj.hidden = true;
  });
  document.querySelectorAll('.consultant-example').forEach(btn => {
    btn.addEventListener('click', () => {
      const quote = btn.dataset.example || btn.textContent || '';
      if (ta) {
        ta.value = quote.trim().replace(/^"|"$/g, '');
        ta.dispatchEvent(new Event('input'));
        ta.focus();
      }
    });
  });
  const grpSel = document.getElementById('customer-group');
  if (grpSel) grpSel.addEventListener('change', updateServiceDropdown);
  initConsultantDatePickers();
  updateServiceDropdown();
  window.addEventListener('pageshow', resetConsultantServiceSelection);
  document.addEventListener('click', (event) => {
    if (!(event.target instanceof Element)) return;
    const combo = document.getElementById('service-combobox');
    if (combo && !combo.contains(event.target)) closeServiceOptions();
    if (!event.target.closest('.consultant-date-popover') && !event.target.closest('[data-themed-date="true"]')) {
      closeConsultantDatePicker();
    }
  });
}

function initConsultantDatePickers() {
  ['first-contact-date', 'objection-date'].forEach(id => {
    const input = document.getElementById(id);
    if (!input || input.dataset.datePickerBound === 'true') return;
    input.dataset.datePickerBound = 'true';
    const field = input.closest('.field');
    if (field) field.classList.add('consultant-date-field');
    input.addEventListener('click', () => openConsultantDatePicker(input));
    input.addEventListener('focus', () => openConsultantDatePicker(input));
    input.addEventListener('keydown', event => {
      if (event.key === 'Enter' || event.key === ' ') {
        event.preventDefault();
        openConsultantDatePicker(input);
      }
      if (event.key === 'Escape') closeConsultantDatePicker();
    });
  });
}

function openConsultantDatePicker(input) {
  if (!input || input.disabled) return;
  const selected = parseConsultantDate(input.dataset.isoDate || input.value);
  _consultantDatePicker.input = input;
  _consultantDatePicker.mode = input.dataset.datePickerMode || 'consultant';
  _consultantDatePicker.viewDate = selected || new Date();
  renderConsultantDatePicker();
}

function closeConsultantDatePicker() {
  const popover = document.getElementById('consultant-date-popover');
  if (popover) popover.hidden = true;
  document.querySelectorAll('.consultant-date-field.is-open').forEach(field => field.classList.remove('is-open'));
  _consultantDatePicker.input = null;
}

function renderConsultantDatePicker() {
  const input = _consultantDatePicker.input;
  if (!input) return;
  const popover = ensureConsultantDatePopover(input);
  const view = _consultantDatePicker.viewDate;
  const year = view.getFullYear();
  const month = view.getMonth();
  const selected = parseConsultantDate(input.dataset.isoDate || input.value);
  const today = stripTime(new Date());
  const firstOfMonth = new Date(year, month, 1);
  const start = new Date(year, month, 1 - firstOfMonth.getDay());
  const monthLabel = view.toLocaleDateString(undefined, { month: 'long', year: 'numeric' });
  const dayCells = Array.from({ length: 42 }, (_, i) => {
    const date = new Date(start.getFullYear(), start.getMonth(), start.getDate() + i);
    const iso = formatConsultantISODate(date);
    const isOutside = date.getMonth() !== month;
    const isSelected = selected && sameConsultantDate(date, selected);
    const isToday = sameConsultantDate(date, today);
    return '<button type="button" class="consultant-date-day' +
      (isOutside ? ' is-outside' : '') +
      (isToday ? ' is-today' : '') +
      (isSelected ? ' is-selected' : '') +
      '" data-date="' + iso + '" onclick="selectConsultantDate(this.dataset.date)">' +
      date.getDate() + '</button>';
  }).join('');

  popover.innerHTML =
    '<div class="consultant-date-head">' +
      '<button type="button" class="consultant-date-nav" onclick="shiftConsultantDateMonth(-1, event)" aria-label="Previous month">&lsaquo;</button>' +
      '<div><strong>' + esc(monthLabel) + '</strong><span>Select a tracking date</span></div>' +
      '<button type="button" class="consultant-date-nav" onclick="shiftConsultantDateMonth(1, event)" aria-label="Next month">&rsaquo;</button>' +
    '</div>' +
    '<div class="consultant-date-weekdays"><span>Sun</span><span>Mon</span><span>Tue</span><span>Wed</span><span>Thu</span><span>Fri</span><span>Sat</span></div>' +
    '<div class="consultant-date-grid">' + dayCells + '</div>' +
    '<div class="consultant-date-actions">' +
      '<button type="button" onclick="clearConsultantDate()">Clear</button>' +
      '<button type="button" onclick="selectConsultantDate(formatConsultantISODate(new Date()))">Today</button>' +
    '</div>';
  positionConsultantDatePopover(popover, input);
  popover.hidden = false;
}

function ensureConsultantDatePopover(input) {
  let popover = document.getElementById('consultant-date-popover');
  if (!popover) {
    popover = document.createElement('div');
    popover.id = 'consultant-date-popover';
    popover.className = 'consultant-date-popover';
    popover.hidden = true;
    popover.addEventListener('click', event => event.stopPropagation());
    popover.addEventListener('pointerdown', event => event.stopPropagation());
  }
  const field = input && input.closest('.field');
  if (field && popover.parentElement !== field) field.appendChild(popover);
  document.querySelectorAll('.consultant-date-field.is-open').forEach(openField => {
    if (openField !== field) openField.classList.remove('is-open');
  });
  if (field) field.classList.add('is-open');
  return popover;
}

function positionConsultantDatePopover(popover, input) {
  const field = input.closest('.field');
  const boundary = input.closest('.consultant-input-card') || field || document.body;
  const inputRect = input.getBoundingClientRect();
  const fieldRect = (field || input).getBoundingClientRect();
  const boundaryRect = boundary.getBoundingClientRect();
  const width = Math.max(300, Math.min(340, inputRect.width + 48));
  const minLeft = boundaryRect.left - fieldRect.left + 8;
  const maxLeft = boundaryRect.right - fieldRect.left - width - 8;
  const left = Math.max(minLeft, Math.min(0, maxLeft));
  popover.style.width = width + 'px';
  popover.style.left = left + 'px';
  popover.style.top = (input.offsetTop + input.offsetHeight + 8) + 'px';
}

function shiftConsultantDateMonth(delta, event) {
  if (event) event.stopPropagation();
  const view = _consultantDatePicker.viewDate || new Date();
  _consultantDatePicker.viewDate = new Date(view.getFullYear(), view.getMonth() + delta, 1);
  renderConsultantDatePicker();
}

function selectConsultantDate(isoDate) {
  const input = _consultantDatePicker.input;
  const date = parseConsultantDate(isoDate);
  if (!input || !date) return;
  input.dataset.isoDate = formatConsultantISODate(date);
  input.value = _consultantDatePicker.mode === 'analytics-filter' ? formatConsultantISODate(date) : formatConsultantDisplayDate(date);
  input.dispatchEvent(new Event('change', { bubbles: true }));
  closeConsultantDatePicker();
}

function clearConsultantDate() {
  const input = _consultantDatePicker.input;
  if (!input) return;
  input.dataset.isoDate = '';
  input.value = '';
  input.dispatchEvent(new Event('change', { bubbles: true }));
  closeConsultantDatePicker();
}

function consultantDateValue(id) {
  const input = document.getElementById(id);
  return ((input && (input.dataset.isoDate || input.value)) || '').trim();
}

function parseConsultantDate(value) {
  const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(value || '').trim());
  if (!match) return null;
  const date = new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3]));
  return Number.isNaN(date.getTime()) ? null : date;
}

function stripTime(date) {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate());
}

function sameConsultantDate(a, b) {
  return a && b && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
}

function formatConsultantISODate(date) {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  return y + '-' + m + '-' + d;
}

function formatConsultantDisplayDate(date) {
  return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
}

function resetConsultantServiceSelection() {
  const svcValue = document.getElementById('visa-service');
  const svcInput = document.getElementById('visa-service-search');
  if (svcValue) svcValue.value = '';
  if (svcInput) svcInput.value = '';
}

function updateServiceDropdown() {
  const grpLabel = document.getElementById('customer-group').value;
  resetConsultantServiceSelection();
  const internalKey = (typeof GROUP_INTERNAL !== 'undefined' && GROUP_INTERNAL[grpLabel]) || grpLabel;
  _consultantServices = (typeof SERVICES_MAP !== 'undefined' && SERVICES_MAP[internalKey]) || [];
  renderServiceOptions(_consultantServices);
}

function openServiceOptions() {
  const options = document.getElementById('visa-service-options');
  if (!options) return;
  const svcValue = (document.getElementById('visa-service') || {}).value || '';
  const svcInput = (document.getElementById('visa-service-search') || {}).value || '';
  const hasSelectedService = svcValue && svcInput && svcValue === svcInput;
  renderServiceOptions(hasSelectedService ? _consultantServices : filterServicesByInput());
  options.hidden = false;
}

function closeServiceOptions() {
  const options = document.getElementById('visa-service-options');
  if (options) options.hidden = true;
}

function filterServiceOptions() {
  const svcValue = document.getElementById('visa-service');
  if (svcValue) svcValue.value = '';
  renderServiceOptions(filterServicesByInput());
  openServiceOptions();
}

function filterServicesByInput() {
  const input = (document.getElementById('visa-service-search') || {}).value || '';
  const needle = input.trim().toLowerCase();
  if (!needle) return _consultantServices;
  return _consultantServices.filter(service => String(service).toLowerCase().includes(needle));
}

function renderServiceOptions(services) {
  const options = document.getElementById('visa-service-options');
  if (!options) return;
  const unique = Array.from(new Set(services || []));
  if (!unique.length) {
    options.innerHTML = '<div class="service-option service-option-empty">No matching services</div>';
    return;
  }
  options.innerHTML = unique.slice(0, 80).map(service =>
    '<button type="button" class="service-option" data-service="' + esc(service) +
    '" onclick="selectServiceOption(this.dataset.service)">' + esc(service) + '</button>'
  ).join('');
}

function selectServiceOption(service) {
  const svcValue = document.getElementById('visa-service');
  const svcInput = document.getElementById('visa-service-search');
  if (svcValue) svcValue.value = service;
  if (svcInput) svcInput.value = service;
  closeServiceOptions();
}

function selectedServiceValue() {
  const svcValue = (document.getElementById('visa-service') || {}).value || '';
  if (svcValue) return svcValue;
  const typed = ((document.getElementById('visa-service-search') || {}).value || '').trim();
  if (!typed) return '';
  const exact = _consultantServices.find(service => String(service).toLowerCase() === typed.toLowerCase());
  return exact || '';
}

function getConsultantTrackingFields() {
  return {
    customer_name:         ((document.getElementById('customer-name') || {}).value || '').trim(),
    objection_status:      ((document.getElementById('objection-status') || {}).value || '').trim(),
    first_contact_date:    consultantDateValue('first-contact-date'),
    objection_date:        consultantDateValue('objection-date'),
    main_contact_platform: ((document.getElementById('main-contact-platform') || {}).value || '').trim(),
    ad_source:             ((document.getElementById('ad-source') || {}).value || '').trim(),
    lead_quality:          ((document.getElementById('lead-quality') || {}).value || '').trim(),
  };
}

async function runPredict() {
  const quote = (document.getElementById('quote').value || '').trim();
  const group = document.getElementById('customer-group').value;
  const svc   = selectedServiceValue();
  const tracking = getConsultantTrackingFields();
  const errEl = document.getElementById('input-error');
  if (errEl) errEl.hidden = true;

  if (quote.length < 10) {
    if (errEl) {
      errEl.textContent = 'Please enter at least 10 characters.';
      errEl.hidden = false;
    }
    return;
  }

  const btn = document.getElementById('analyze-btn');
  btn.disabled = true; btn.textContent = 'Analyzing...';
  const placeholder = document.getElementById('result-placeholder');
  const noObjPanel = document.getElementById('no-objection-panel');
  const resultPanel = document.getElementById('result-panel');
  if (placeholder) {
    placeholder.hidden = false;
    placeholder.classList.add('is-loading');
  }
  if (noObjPanel) noObjPanel.hidden = true;
  if (resultPanel) resultPanel.hidden = true;

  try {
    const data = await postJSON('/api/predict', { quote, customer_group: group, service: svc, ...tracking });
    if (data.no_objection) {
      renderNoObjection(data);
      return;
    }
    _lastPrediction = data;
    renderResult(data);
  } catch (e) {
    if (errEl) {
      errEl.textContent = e.detail || 'Server error. Please try again.';
      errEl.hidden = false;
    }
    console.error('Prediction failed', e);
  } finally {
    if (placeholder) placeholder.classList.remove('is-loading');
    btn.disabled = false; btn.textContent = 'Analyze objection';
  }
}

function renderNoObjection(d) {
  _lastPrediction = null;
  const resultPanel = document.getElementById('result-panel');
  const noObjPanel = document.getElementById('no-objection-panel');
  const placeholder = document.getElementById('result-placeholder');
  const msg = document.getElementById('no-objection-message');
  const quote = document.getElementById('no-objection-quote');
  if (resultPanel) resultPanel.hidden = true;
  if (placeholder) placeholder.hidden = true;
  if (msg) msg.textContent = d.message || 'This quote does not contain a customer objection.';
  if (quote) quote.textContent = d.quote || '';
  if (noObjPanel) {
    noObjPanel.hidden = false;
    noObjPanel.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
  }
}

function renderResult(d) {
  const noObjPanel = document.getElementById('no-objection-panel');
  const placeholder = document.getElementById('result-placeholder');
  if (noObjPanel) noObjPanel.hidden = true;
  if (placeholder) placeholder.hidden = true;
  document.getElementById('correction-banner').hidden = !d.from_correction;
  document.getElementById('result-quote-text').textContent = d.quote;

  const badges = document.getElementById('result-badges');
  badges.innerHTML = '';
  if (d.customer_name) badges.innerHTML += '<span class="result-badge">' + esc(d.customer_name) + '</span>';
  if (d.customer_group) badges.innerHTML += '<span class="result-badge">' + esc(d.customer_group) + '</span>';
  if (d.service)        badges.innerHTML += '<span class="result-badge">' + esc(d.service) + '</span>';
  if (d.objection_status) badges.innerHTML += '<span class="result-badge">' + esc(d.objection_status) + '</span>';
  if (d.lead_quality) badges.innerHTML += '<span class="result-badge">' + esc(d.lead_quality) + '</span>';

  document.getElementById('result-type').textContent    = d.objection_type || '--';
  document.getElementById('result-type-conf').innerHTML = confBar(d.objection_type_confidence);
  document.getElementById('result-cluster').textContent    = d.cluster || '--';
  document.getElementById('result-cluster-conf').innerHTML = confBar(d.cluster_confidence);
  document.getElementById('result-severity').innerHTML  = severityBadge(d.severity);

  const vidEl = document.getElementById('result-video');
  if (d.video_id) {
    vidEl.innerHTML = '<a class="consultant-video-link" href="https://www.youtube.com/watch?v=' + esc(d.video_id) + '" target="_blank" rel="noopener">&#9654; Watch training video</a><div class="consultant-video-caption">2:14 · Handling price objections</div>';
  } else { vidEl.innerHTML = ''; }

  document.getElementById('result-response').innerHTML = bilingualHTML(d.perfect_response, d.perfect_response_km);
  document.getElementById('result-solution').innerHTML = bilingualHTML(d.solution, d.solution_km);
  document.getElementById('result-followup').innerHTML = bilingualHTML(d.follow_up_question, d.follow_up_question_km);
  const hasAnyResponse = !!(d.perfect_response || d.perfect_response_km || d.solution || d.solution_km || d.follow_up_question || d.follow_up_question_km);
  const serviceMismatch = d.service_objection_exists === false;
  const noResponseWarn = document.getElementById('no-response-warn');
  const serviceWarn = document.getElementById('service-objection-warn');
  const perfectCard = document.querySelector('.consultant-perfect-card');
  const details = document.querySelector('.consultant-extra-details');
  const feedback = document.getElementById('feedback-section');
  if (serviceWarn) {
    serviceWarn.textContent = d.service_objection_message || 'This objection does not exist for this visa service';
    serviceWarn.hidden = !serviceMismatch;
  }
  if (noResponseWarn) noResponseWarn.hidden = serviceMismatch || (d.response_lookup_succeeded !== false && hasAnyResponse);
  if (perfectCard) perfectCard.hidden = serviceMismatch;
  if (details) details.hidden = serviceMismatch;
  if (feedback) feedback.hidden = serviceMismatch;

  document.getElementById('feedback-btns').hidden   = false;
  document.getElementById('feedback-msg').hidden    = true;
  document.getElementById('correction-form').hidden = true;
  document.getElementById('result-panel').hidden    = false;
  document.getElementById('result-panel').scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

function bilingualHTML(en, km) {
  if (!en && !km) return '<span class="text-muted">--</span>';
  let html = '';
  if (en) html += responseCopyBlock(en, 'response-en');
  if (km) html += responseCopyBlock(km, 'response-km');
  return html;
}

function responseCopyBlock(text, cls) {
  return '<div class="response-block ' + cls + '">' +
    '<button type="button" class="response-copy-btn" data-copy-text="' + esc(text) + '" onclick="copyResponseBlock(this)">Copy</button>' +
    '<div class="response-copy">' + esc(text) + '</div>' +
    '</div>';
}

async function copyResponseBlock(btn) {
  const text = btn?.dataset?.copyText || '';
  if (!text.trim()) return;
  const original = btn.textContent;
  try {
    await navigator.clipboard.writeText(text);
    btn.textContent = 'Copied';
    btn.classList.add('is-copied');
    setTimeout(() => {
      btn.textContent = original || 'Copy';
      btn.classList.remove('is-copied');
    }, 1200);
  } catch (_) {
    btn.textContent = 'Copy failed';
    setTimeout(() => { btn.textContent = original || 'Copy'; }, 1200);
  }
}

async function copyPerfectResponse() {
  const text = document.getElementById('result-response')?.innerText || '';
  if (!text.trim()) return;
  try {
    await navigator.clipboard.writeText(text);
  } catch (_) {
    // Clipboard can be unavailable in some embedded browsers.
  }
}

function feedbackYes() {
  document.getElementById('feedback-btns').hidden = true;
  const msg = document.getElementById('feedback-msg');
  msg.innerHTML = '<span style="color:var(--green,#4caf50);">Thanks for confirming!</span>';
  msg.hidden = false;
}

function feedbackNo() {
  document.getElementById('feedback-btns').hidden = true;
  document.getElementById('correction-form').hidden = false;
}

function cancelCorrection() {
  document.getElementById('correction-form').hidden = true;
  document.getElementById('feedback-btns').hidden = false;
}

function _buildTypeOptions() {
  const typeSel = document.getElementById('correct-type');
  if (!typeSel || typeof TYPE_CLUSTER === 'undefined') return;
  typeSel.innerHTML = '';
  Object.keys(TYPE_CLUSTER).sort().forEach(t => {
    const o = document.createElement('option');
    o.value = t; o.textContent = t;
    typeSel.appendChild(o);
  });
  updateClusterOptions();
}

function updateClusterOptions() {
  const typeSel    = document.getElementById('correct-type');
  const clusterSel = document.getElementById('correct-cluster');
  if (!typeSel || !clusterSel || typeof TYPE_CLUSTER === 'undefined') return;
  const clusters = TYPE_CLUSTER[typeSel.value] || [];
  clusterSel.innerHTML = '';
  clusters.forEach(c => {
    const o = document.createElement('option');
    o.value = c; o.textContent = c;
    clusterSel.appendChild(o);
  });
}

async function submitCorrection() {
  if (!_lastPrediction) return;
  const corrType    = document.getElementById('correct-type').value;
  const corrCluster = document.getElementById('correct-cluster').value;
  if (!corrType || !corrCluster) { alert('Please select both a type and a cluster.'); return; }

  const btn = document.querySelector('#correction-form .btn-primary');
  if (btn) { btn.disabled = true; btn.textContent = 'Saving...'; }

  try {
    await postJSON('/api/correction', {
      quote:             _lastPrediction.quote,
      original_type:     _lastPrediction.objection_type || '',
      original_cluster:  _lastPrediction.cluster || '',
      corrected_type:    corrType,
      corrected_cluster: corrCluster,
      customer_group:    _lastPrediction.customer_group || '',
      destination:       '',
      service:           _lastPrediction.service || '',
    });
    document.getElementById('correction-form').hidden = true;
    const msg = document.getElementById('feedback-msg');
    msg.innerHTML = '<span style="color:var(--gold);">Correction submitted -- thank you!</span>';
    msg.hidden = false;
    document.getElementById('correction-banner').hidden = false;
  } catch (e) {
    alert(e.detail || 'Failed to submit correction.');
  } finally {
    if (btn) { btn.disabled = false; btn.textContent = 'Submit correction'; }
  }
}

// =============================================================================
// BROWSE PAGE
// =============================================================================

// Globals: ALL_ROWS, CAN_EDIT, SERVICES_MAP, GROUP_INTERNAL

let _browseEditRow = null;
let _browseServices = [];
let _browseViewRows = new Set();

function initBrowse() {
  const grpSel = document.getElementById('browse-group');
  if (grpSel) grpSel.addEventListener('change', _updateBrowseServices);
  const svcInput = document.getElementById('browse-service-search');
  if (svcInput && !svcInput.dataset.browseClickBound) {
    svcInput.addEventListener('click', () => openBrowseServiceOptions({ showAll: true }));
    svcInput.dataset.browseClickBound = 'true';
  }
  document.addEventListener('click', (event) => {
    const combo = document.getElementById('browse-service-combobox');
    if (combo && !combo.contains(event.target)) closeBrowseServiceOptions();
  });
  const results = document.getElementById('browse-results');
  if (results && !results.dataset.editBound) {
    results.addEventListener('click', (event) => {
      const btn = event.target.closest('.js-edit-response');
      const viewBtn = event.target.closest('.js-view-response');
      const deleteBtn = event.target.closest('.js-delete-response');
      if (btn) {
        openEditModal(Number(btn.dataset.rowId));
        return;
      }
      if (viewBtn) {
        toggleBrowseResponseView(Number(viewBtn.dataset.rowId));
        return;
      }
      if (deleteBtn) {
        deleteBrowseResponseRow(Number(deleteBtn.dataset.rowId));
      }
    });
    results.dataset.editBound = 'true';
  }
  _updateBrowseServices();
  updateBrowseDeleteOptions();
}

function _updateBrowseServices(optionsConfig = {}) {
  const grpLabel = document.getElementById('browse-group').value;
  const svcValue = document.getElementById('browse-service');
  const svcInput = document.getElementById('browse-service-search');
  const previousService = ((svcValue && svcValue.value) || '').trim();
  const previousText = ((svcInput && svcInput.value) || '').trim();
  const key = (typeof GROUP_INTERNAL !== 'undefined' && GROUP_INTERNAL[grpLabel]) || grpLabel;
  let services = [];
  if (typeof ALL_ROWS !== 'undefined') {
    const groupKey = (key || '').toLowerCase();
    services = ALL_ROWS
      .filter(r => !groupKey || (r.customer_group || '').toLowerCase() === groupKey)
      .map(r => r.service || '')
      .filter(Boolean);
  }
  if (!services.length) {
    services = (typeof SERVICES_MAP !== 'undefined' && (key ? SERVICES_MAP[key] : null))
      || (typeof SERVICES_MAP !== 'undefined' ? Object.values(SERVICES_MAP).flat() : []);
  }
  _browseServices = Array.from(new Set(services)).sort();
  if (optionsConfig.preserveSelection) {
    const exact = _browseServices.find(service => String(service).toLowerCase() === previousService.toLowerCase());
    if (exact) {
      if (svcValue) svcValue.value = exact;
      if (svcInput) svcInput.value = exact;
    } else if (svcValue) {
      svcValue.value = '';
      if (svcInput && !previousText) svcInput.value = '';
    }
  } else {
    if (svcValue) svcValue.value = '';
    if (svcInput) svcInput.value = '';
  }
  renderBrowseServiceOptions(_browseServices);
  browseFilter();
}

function openBrowseServiceOptions(optionsConfig = {}) {
  const options = document.getElementById('browse-service-options');
  if (!options) return;
  const services = optionsConfig.showAll ? _browseServices : filterBrowseServicesByInput();
  renderBrowseServiceOptions(services);
  options.hidden = false;
}

function closeBrowseServiceOptions() {
  const options = document.getElementById('browse-service-options');
  if (options) options.hidden = true;
}

function filterBrowseServiceOptions() {
  const svcValue = document.getElementById('browse-service');
  if (svcValue) svcValue.value = '';
  renderBrowseServiceOptions(filterBrowseServicesByInput());
  openBrowseServiceOptions();
  browseFilter();
}

function filterBrowseServicesByInput() {
  const input = (document.getElementById('browse-service-search') || {}).value || '';
  const needle = input.trim().toLowerCase();
  if (!needle) return _browseServices;
  return _browseServices.filter(service => String(service).toLowerCase().includes(needle));
}

function renderBrowseServiceOptions(services) {
  const options = document.getElementById('browse-service-options');
  if (!options) return;
  const unique = Array.from(new Set(services || []));
  const allButton = '<button type="button" class="service-option" data-service="" onclick="selectBrowseServiceOption(\'\')">All services</button>';
  if (!unique.length) {
    options.innerHTML = allButton + '<div class="service-option service-option-empty">No matching services</div>';
    return;
  }
  options.innerHTML = allButton + unique.slice(0, 120).map(service =>
    '<button type="button" class="service-option" data-service="' + esc(service) +
    '" onclick="selectBrowseServiceOption(this.dataset.service)">' + esc(service) + '</button>'
  ).join('');
}

function selectBrowseServiceOption(service) {
  const svcValue = document.getElementById('browse-service');
  const svcInput = document.getElementById('browse-service-search');
  if (svcValue) svcValue.value = service || '';
  if (svcInput) svcInput.value = service || '';
  closeBrowseServiceOptions();
  browseFilter();
}

function selectedBrowseServiceValue() {
  const svcValue = (document.getElementById('browse-service') || {}).value || '';
  if (svcValue) return svcValue;
  const typed = ((document.getElementById('browse-service-search') || {}).value || '').trim();
  const exact = _browseServices.find(service => String(service).toLowerCase() === typed.toLowerCase());
  return exact || '';
}

function browseFilter() {
  if (typeof ALL_ROWS === 'undefined') return;
  const grpLabel  = (document.getElementById('browse-group') && document.getElementById('browse-group').value || '').toLowerCase();
  const svc       = selectedBrowseServiceValue().toLowerCase();
  const searchRaw = (document.getElementById('browse-search') && document.getElementById('browse-search').value || '').toLowerCase();
  const grpInternal = (typeof GROUP_INTERNAL !== 'undefined' && grpLabel)
    ? ((GROUP_INTERNAL[document.getElementById('browse-group').value] || '')).toLowerCase()
    : '';
  const filtered = ALL_ROWS.filter(r => {
    const rowGroup = (r.customer_group || '').toLowerCase();
    const rowDest = (r.destination || '').toLowerCase();
    const rowService = (r.service || '').toLowerCase();
    if (grpInternal && rowGroup && rowGroup !== grpInternal) return false;
    if (svc && rowService && rowService !== svc) return false;
    if (svc && !rowService && rowDest && rowDest !== _destFromService(svc)) return false;
    if (searchRaw) {
      const hay = [r.service, r.objection_type, r.cluster, r.perfect_response, r.perfect_response_km, r.solution].join(' ').toLowerCase();
      if (!hay.includes(searchRaw)) return false;
    }
    return true;
  });
  const countEl = document.getElementById('browse-count');
  if (countEl) countEl.textContent = filtered.length.toLocaleString();
  _renderBrowseCards(filtered);
}

function _destFromService(svcLower) {
  const m = svcLower.match(/visa\s*-\s*([a-z]+)/);
  return m ? m[1] : svcLower;
}

function _renderBrowseCards(rows) {
  const container = document.getElementById('browse-results');
  const empty     = document.getElementById('browse-empty');
  if (!container) return;
  if (!rows.length) { container.innerHTML = ''; empty.hidden = false; return; }
  empty.hidden = true;

  const grouped = {};
  rows.forEach(r => {
    const t = r.objection_type || 'Uncategorised';
    if (!grouped[t]) grouped[t] = [];
    grouped[t].push(r);
  });

  let html = '';
  Object.keys(grouped).sort().forEach(type => {
    html += '<article class="browse-type-section">';
    html += '<div class="browse-type-heading"><h2>' + esc(type) + '</h2><span>' + grouped[type].length + '</span></div>';
    grouped[type].forEach((r, i) => {
      const isViewed = _browseViewRows.has(Number(r.row_id));
      const isEditing = _browseEditRow && Number(_browseEditRow.row_id) === Number(r.row_id);
      const viewBtn = '<button type="button" class="btn btn-outline btn-sm browse-view-btn js-view-response" data-row-id="' + esc(r.row_id) + '">' + (isViewed ? 'Hide' : 'View') + '</button>';
      const editBtn = (typeof CAN_EDIT !== 'undefined' && CAN_EDIT)
        ? '<button type="button" class="btn btn-outline btn-sm browse-edit-btn js-edit-response" data-row-id="' + esc(r.row_id) + '">Edit</button>'
        : '';
      const deleteBtn = (typeof CAN_EDIT !== 'undefined' && CAN_EDIT)
        ? '<button type="button" class="btn btn-danger btn-sm browse-delete-row-btn js-delete-response" data-row-id="' + esc(r.row_id) + '">Delete</button>'
        : '';
      const filledClass = r.perfect_response || r.perfect_response_km ? ' is-filled' : ' is-empty';
      html += '<div class="browse-response-card' + (i === 0 ? ' is-first' : '') + filledClass + (isViewed ? ' is-view-open' : '') + (isEditing ? ' is-edit-open' : '') + '">';
      html += '<div class="browse-response-main">';
      html += '<div class="browse-row-head">';
      html += '<div><h3>' + esc(r.cluster || 'Unclustered') + '</h3><div class="browse-response-meta">' + esc(_browseScopeLabel(r)) + '</div></div>';
      html += '</div>';
      html += '</div>';
      html += '<div class="browse-response-actions">' + severityBadge(r.severity) + '<div class="browse-row-buttons">' + viewBtn + editBtn + deleteBtn + '</div></div>';
      if (isViewed) {
        html += '<div class="browse-view-dropdown">';
      html += '<div class="browse-response-grid">';
      html += _browseResponseBlock('Perfect response', 'English', r.perfect_response, 'en');
      html += _browseResponseBlock('Perfect response', 'Khmer', r.perfect_response_km, 'km');
      html += _browseDetailBlock('Recommended solution', r.solution, r.solution_km);
      html += _browseDetailBlock('Follow-up question', r.follow_up_question, r.follow_up_question_km);
      html += '</div>';
      html += '</div>';
      }
      if (isEditing) html += _browseEditDropdownHTML(r);
      html += '</div>';
    });
    html += '</article>';
  });
  container.innerHTML = html;
}

function toggleBrowseResponseView(rowId) {
  const id = Number(rowId);
  if (_browseViewRows.has(id)) {
    _browseViewRows.delete(id);
  } else {
    _browseViewRows.add(id);
  }
  browseFilter();
}

function _browseTag(value) {
  return value ? '<span>' + esc(value) + '</span>' : '';
}

function _browseResponseBlock(title, language, value, langClass) {
  const content = value
    ? '<div class="browse-block-copy browse-' + langClass + '">' + esc(value) + '</div>'
    : '<div class="browse-block-empty">Not filled yet</div>';
  return '<section class="browse-response-block">' +
    '<div class="browse-block-label"><span>' + esc(title) + '</span><em>' + esc(language) + '</em></div>' +
    content +
    '</section>';
}

function _browseDetailBlock(title, en, km) {
  if (!en && !km) {
    return '<section class="browse-response-block browse-detail-block">' +
      '<div class="browse-block-label"><span>' + esc(title) + '</span></div>' +
      '<div class="browse-block-empty">Not filled yet</div>' +
      '</section>';
  }
  let html = '<section class="browse-response-block browse-detail-block">' +
    '<div class="browse-block-label"><span>' + esc(title) + '</span></div>';
  if (en) html += '<div class="browse-detail-copy">' + esc(en) + '</div>';
  if (km) html += '<div class="browse-detail-copy browse-km">' + esc(km) + '</div>';
  html += '</section>';
  return html;
}

function _browseScopeLabel(r) {
  const group = r.customer_group || '';
  const service = r.service || '';
  const destination = r.destination || '';
  const suffix = service || destination;
  if (service) return 'Service: ' + service;
  if (group && suffix) return group + ' - ' + suffix;
  return group || suffix || 'All services';
}

function openEditModal(rowId) {
  const r = ALL_ROWS.find(row => Number(row.row_id) === Number(rowId));
  if (!r) return;
  const isOpen = _browseEditRow && Number(_browseEditRow.row_id) === Number(rowId);
  _browseEditRow = isOpen ? null : r;
  if (!isOpen) _browseViewRows.delete(Number(rowId));
  browseFilter();
  initBrowseEditAutosize();
}

function openNewResponseModal() {
  _browseEditRow = {
    row_id: null,
    service: '',
    customer_group: '',
    destination: '',
    objection_type: '',
    cluster: '',
    severity: 'Medium',
    video_id: '',
    perfect_response: '',
    perfect_response_km: '',
    solution: '',
    solution_km: '',
    follow_up_question: '',
    follow_up_question_km: '',
    is_new: true,
  };
  const container = document.getElementById('browse-results');
  if (container) {
    container.querySelectorAll('.browse-new-section').forEach(el => el.remove());
    container.insertAdjacentHTML('afterbegin', '<article class="browse-type-section browse-new-section">' + _browseEditDropdownHTML(_browseEditRow) + '</article>');
    initBrowseEditAutosize();
    const form = document.getElementById('browse-edit-form');
    if (form) form.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }
}

function closeEditModal() {
  _browseEditRow = null;
  browseFilter();
}

function initBrowseEditAutosize() {
  window.requestAnimationFrame(() => {
    document.querySelectorAll('#browse-edit-form textarea[data-autosize="true"]').forEach(textarea => {
      const resize = () => {
        textarea.style.height = 'auto';
        textarea.style.height = Math.max(textarea.scrollHeight + 2, textarea.dataset.minHeight || 0) + 'px';
      };
      if (!textarea.dataset.autosizeBound) {
        textarea.addEventListener('input', resize);
        textarea.dataset.autosizeBound = 'true';
      }
      resize();
    });
  });
}

function toggleBrowseDeletePanel() {
  const panel = document.getElementById('browse-delete-panel');
  if (!panel) return;
  panel.hidden = !panel.hidden;
  if (!panel.hidden) updateBrowseDeleteOptions();
}

function _browseDeleteValues(scope) {
  if (typeof ALL_ROWS === 'undefined') return [];
  return Array.from(new Set(
    ALL_ROWS
      .map(row => (row && row[scope]) || '')
      .map(value => String(value).trim())
      .filter(Boolean)
  )).sort((a, b) => a.localeCompare(b));
}

function updateBrowseDeleteOptions() {
  const scopeEl = document.getElementById('browse-delete-scope');
  const valueEl = document.getElementById('browse-delete-value');
  if (!scopeEl || !valueEl) return;
  const values = _browseDeleteValues(scopeEl.value || 'service');
  valueEl.innerHTML = values.length
    ? values.map(value => '<option value="' + esc(value) + '">' + esc(value) + '</option>').join('')
    : '<option value="">No items available</option>';
}

async function deleteBrowseMatrixItem() {
  const scopeEl = document.getElementById('browse-delete-scope');
  const valueEl = document.getElementById('browse-delete-value');
  const msgEl = document.getElementById('browse-delete-message');
  if (!scopeEl || !valueEl || !valueEl.value) return;

  const scope = scopeEl.value;
  const value = valueEl.value;
  const label = scope === 'service' ? 'service' : scope === 'objection_type' ? 'objection type' : 'cluster';
  const affected = (typeof ALL_ROWS === 'undefined' ? [] : ALL_ROWS.filter(row => String(row[scope] || '') === value));
  if (!affected.length) return;
  if (!confirm('Delete ' + affected.length + ' row(s) for this ' + label + '?\n\n' + value)) return;

  const btn = document.querySelector('.browse-delete-btn');
  if (btn) { btn.disabled = true; btn.textContent = 'Deleting...'; }
  if (msgEl) msgEl.hidden = true;

  try {
    const data = await postJSON('/browse/delete', { scope, value });
    for (let i = ALL_ROWS.length - 1; i >= 0; i--) {
      if (String(ALL_ROWS[i][scope] || '') === value) ALL_ROWS.splice(i, 1);
    }
    if (_browseEditRow && String(_browseEditRow[scope] || '') === value) _browseEditRow = null;
    affected.forEach(row => _browseViewRows.delete(Number(row.row_id)));
    _updateBrowseServices({ preserveSelection: true });
    updateBrowseDeleteOptions();
    browseFilter();
    if (msgEl) {
      msgEl.textContent = 'Deleted ' + data.deleted + ' row(s).';
      msgEl.className = 'browse-delete-message is-success';
      msgEl.hidden = false;
    }
  } catch (e) {
    if (msgEl) {
      msgEl.textContent = e.detail || 'Delete failed.';
      msgEl.className = 'browse-delete-message is-error';
      msgEl.hidden = false;
    } else {
      alert(e.detail || 'Delete failed.');
    }
  } finally {
    if (btn) { btn.disabled = false; btn.textContent = 'Delete'; }
  }
}

function _browseEditDropdownHTML(r) {
  const deleteButton = r.is_new
    ? ''
    : '<button type="button" class="btn btn-danger" onclick="deleteEditRow()">Delete</button>';
  return '' +
    '<div id="browse-edit-form" class="browse-edit-dropdown">' +
      '<div class="browse-edit-head">' +
        '<div><div class="card-label">' + (r.is_new ? 'NEW RESPONSE' : 'EDIT RESPONSE') + '</div>' +
        '<div class="browse-edit-subtitle">' + esc(r.objection_type || 'Response') + ' - ' + esc(r.cluster || 'New cluster') + '</div></div>' +
        '<button type="button" class="modal-close" onclick="closeEditModal()">Close</button>' +
      '</div>' +
      '<div id="edit-error" class="alert alert-error" hidden></div>' +
      '<div id="edit-success" class="alert alert-success" hidden></div>' +
      '<div class="browse-edit-context-grid mb-2">' +
        '<div class="field"><label class="field-label">Customer Group</label><input class="input" type="text" id="edit-customer-group" value="' + esc(r.customer_group || '') + '" /></div>' +
        '<div class="field browse-edit-service-field"><label class="field-label">Service</label><input class="input" type="text" id="edit-service" value="' + esc(r.service || '') + '" /></div>' +
        '<div class="field"><label class="field-label">Destination</label><input class="input" type="text" id="edit-destination" value="' + esc(r.destination || '') + '" /></div>' +
      '</div>' +
      '<div class="browse-edit-meta-grid mb-2">' +
        '<div class="field"><label class="field-label">Objection Type</label><input class="input" type="text" id="edit-objection-type" value="' + esc(r.objection_type || '') + '" /></div>' +
        '<div class="field"><label class="field-label">Cluster</label><input class="input" type="text" id="edit-cluster" value="' + esc(r.cluster || '') + '" /></div>' +
      '</div>' +
      '<div class="browse-edit-section">' +
        '<div class="browse-edit-section-title">Perfect Response</div>' +
        '<div class="browse-edit-response-grid">' +
          '<div class="field browse-edit-field"><label class="field-label">English</label><textarea class="textarea browse-edit-textarea browse-edit-long" id="edit-pr-en" rows="7" data-autosize="true" data-min-height="150">' + esc(r.perfect_response || '') + '</textarea></div>' +
          '<div class="field browse-edit-field"><label class="field-label">Khmer</label><textarea class="textarea browse-edit-textarea browse-edit-long khmer-input" id="edit-pr-km" rows="7" data-autosize="true" data-min-height="150">' + esc(r.perfect_response_km || '') + '</textarea></div>' +
        '</div>' +
      '</div>' +
      '<div class="browse-edit-section">' +
        '<div class="browse-edit-section-title">Recommended Solution</div>' +
        '<div class="browse-edit-response-grid">' +
          '<div class="field browse-edit-field"><label class="field-label">English</label><textarea class="textarea browse-edit-textarea browse-edit-long" id="edit-sol-en" rows="8" data-autosize="true" data-min-height="190">' + esc(r.solution || '') + '</textarea></div>' +
          '<div class="field browse-edit-field"><label class="field-label">Khmer</label><textarea class="textarea browse-edit-textarea browse-edit-long khmer-input" id="edit-sol-km" rows="8" data-autosize="true" data-min-height="190">' + esc(r.solution_km || '') + '</textarea></div>' +
        '</div>' +
      '</div>' +
      '<div class="browse-edit-section">' +
        '<div class="browse-edit-section-title">Follow-Up Question</div>' +
        '<div class="browse-edit-response-grid">' +
          '<div class="field browse-edit-field"><label class="field-label">English</label><textarea class="textarea browse-edit-textarea browse-edit-short" id="edit-fup-en" rows="3" data-autosize="true" data-min-height="96">' + esc(r.follow_up_question || '') + '</textarea></div>' +
          '<div class="field browse-edit-field"><label class="field-label">Khmer</label><textarea class="textarea browse-edit-textarea browse-edit-short khmer-input" id="edit-fup-km" rows="3" data-autosize="true" data-min-height="96">' + esc(r.follow_up_question_km || '') + '</textarea></div>' +
        '</div>' +
      '</div>' +
      '<div class="browse-edit-meta-grid mb-2">' +
        '<div class="field"><label class="field-label">Severity</label><select class="select" id="edit-severity">' +
          '<option value=""' + (!(r.severity || '') ? ' selected' : '') + '>-- None --</option>' +
          '<option value="Low"' + ((r.severity || '') === 'Low' ? ' selected' : '') + '>Low</option>' +
          '<option value="Medium"' + ((r.severity || '') === 'Medium' ? ' selected' : '') + '>Medium</option>' +
          '<option value="High"' + ((r.severity || '') === 'High' ? ' selected' : '') + '>High</option>' +
        '</select></div>' +
        '<div class="field"><label class="field-label">Video ID (YouTube)</label><input class="input" type="text" id="edit-video-id" value="' + esc(r.video_id || '') + '" placeholder="e.g. dQw4w9WgXcQ" /></div>' +
      '</div>' +
      '<div class="browse-edit-actions">' +
        '<button type="button" class="btn btn-primary" onclick="saveEdit()">SAVE CHANGES</button>' +
        deleteButton +
        '<button type="button" class="btn btn-outline" onclick="closeEditModal()">Cancel</button>' +
      '</div>' +
    '</div>';
}

async function saveEdit() {
  if (!_browseEditRow) return;
  const errEl = document.getElementById('edit-error');
  const okEl  = document.getElementById('edit-success');
  errEl.hidden = true; okEl.hidden = true;

  const payload = {
    row_id:                _browseEditRow.row_id,
    service:               document.getElementById('edit-service').value,
    customer_group:        document.getElementById('edit-customer-group').value,
    destination:           document.getElementById('edit-destination').value,
    objection_type:        document.getElementById('edit-objection-type').value,
    cluster:               document.getElementById('edit-cluster').value,
    perfect_response:      document.getElementById('edit-pr-en').value,
    perfect_response_km:   document.getElementById('edit-pr-km').value,
    solution:              document.getElementById('edit-sol-en').value,
    solution_km:           document.getElementById('edit-sol-km').value,
    follow_up_question:    document.getElementById('edit-fup-en').value,
    follow_up_question_km: document.getElementById('edit-fup-km').value,
    severity:              document.getElementById('edit-severity').value,
    video_id:              document.getElementById('edit-video-id').value,
  };

  const btn = document.querySelector('#browse-edit-form .btn-primary');
  if (btn) { btn.disabled = true; btn.textContent = 'SAVING...'; }

  try {
    const data = await postJSON('/browse/edit', payload);
    const idx = ALL_ROWS.findIndex(r => Number(r.row_id) === Number(payload.row_id));
    if (idx !== -1) {
      Object.assign(ALL_ROWS[idx], payload);
      _browseEditRow = ALL_ROWS[idx];
    } else {
      const created = Object.assign({}, payload, { row_id: data.row_id });
      ALL_ROWS.unshift(created);
      _browseEditRow = created;
    }
    browseFilter();
    initBrowseEditAutosize();
    const freshOkEl = document.getElementById('edit-success');
    if (freshOkEl) {
      freshOkEl.textContent = 'Saved.';
      freshOkEl.hidden = false;
    }
  } catch (e) {
    errEl.textContent = e.detail || 'Save failed.';
    errEl.hidden = false;
  } finally {
    if (btn) { btn.disabled = false; btn.textContent = 'SAVE CHANGES'; }
  }
}

async function deleteBrowseResponseRow(rowId) {
  const row = ALL_ROWS.find(r => Number(r.row_id) === Number(rowId));
  if (!row) return;
  const errEl = document.getElementById('edit-error');
  const okEl  = document.getElementById('edit-success');
  if (errEl) errEl.hidden = true;
  if (okEl) okEl.hidden = true;

  const label = [
    row.service || row.destination || 'this service',
    row.objection_type || 'this objection',
    row.cluster || 'this cluster',
  ].join(' / ');
  if (!confirm('Delete this response row?\n\n' + label)) return;

  const btn = document.querySelector('.js-delete-response[data-row-id="' + CSS.escape(String(rowId)) + '"]')
    || document.querySelector('#browse-edit-form .btn-danger');
  if (btn) { btn.disabled = true; btn.textContent = 'Deleting...'; }

  try {
    await postJSON('/browse/delete-row', { row_id: rowId });
    for (let i = ALL_ROWS.length - 1; i >= 0; i--) {
      if (Number(ALL_ROWS[i].row_id) === Number(rowId)) {
        ALL_ROWS.splice(i, 1);
      }
    }
    _browseViewRows.delete(Number(rowId));
    if (_browseEditRow && Number(_browseEditRow.row_id) === Number(rowId)) _browseEditRow = null;
    _updateBrowseServices({ preserveSelection: true });
    updateBrowseDeleteOptions();
    browseFilter();
  } catch (e) {
    if (errEl) {
      errEl.textContent = e.detail || 'Delete failed.';
      errEl.hidden = false;
    } else {
      alert(e.detail || 'Delete failed.');
    }
  } finally {
    if (btn) { btn.disabled = false; btn.textContent = 'Delete'; }
  }
}

async function deleteEditRow() {
  if (!_browseEditRow || !_browseEditRow.row_id) return;
  await deleteBrowseResponseRow(Number(_browseEditRow.row_id));
}

// =============================================================================
// ANALYTICS PAGE
// =============================================================================

let _analyticsRows = [];
let _analyticsFilteredRows = [];
let _trackingFilters = {};
let _deleteMode    = false;
let _selectedIds   = new Set();
let _analyticsRange = '30d';
let _analyticsScrollSyncReady = false;
let _analyticsScrollSyncing = false;
let _statusMenuEl = null;
let _analyticsEditRowId = null;

const TRACKING_FILTER_COLUMNS = [
  ['user_name', 'Staff'],
  ['customer_name', 'Customer Name'],
  ['objection_status', 'Objection Status'],
  ['first_contact_date', 'First Contact Date'],
  ['objection_date', 'Objection Date'],
  ['main_contact_platform', 'Main Contact Platform'],
  ['lead_quality', 'Lead Quality'],
  ['service', 'Service'],
  ['ad_source', 'Ad Source'],
  ['objection_type', 'Objection Type'],
  ['cluster', 'Cluster'],
  ['severity', 'Severity'],
];

const TRACKING_FILTER_SELECT_OPTIONS = {
  objection_status: ['Solved', 'Unsolved'],
  main_contact_platform: ['Explorer Webapp', 'Explorer by SL', 'Explorer Travel Agency'],
  lead_quality: ['Qualified', 'Not Qualified', 'Lost', 'Converted', 'Intake', 'Awaiting Documents'],
};

const LEAD_QUALITY_OPTIONS = ['Qualified', 'Not Qualified', 'Lost', 'Converted', 'Intake', 'Awaiting Documents'];

const TRACKING_FILTER_DATE_COLUMNS = new Set(['first_contact_date', 'objection_date']);
const TRACKING_FILTER_AUTOCOMPLETE_COLUMNS = new Set(['service', 'objection_type', 'cluster']);
const TRACKING_FILTER_STAFF_FALLBACK = [
  'Rotha Munyputhida',
  'Oeun Sreyleak',
  'Ly Leapheng',
  'ATA Rosett',
  'Phath Socheata',
  'Vuthan Sokheng',
  'Leang Vannlay',
  'Ven Sophy',
  'Ly Sreypich',
  'Tang Techleng',
  'Chum Phalla',
  'Im Sreypin',
  'Steven Ly',
  'Vath Sreynorng',
  'Sakda',
];

function initAnalytics() {
  document.querySelectorAll('.analytics-range-tabs button').forEach(btn => {
    btn.addEventListener('click', () => {
      _analyticsRange = btn.dataset.range || '30d';
      document.querySelectorAll('.analytics-range-tabs button').forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      _setAnalyticsRange(_analyticsRange);
      loadAnalytics();
    });
  });
  const exportBtn = document.getElementById('analytics-export-btn');
  if (exportBtn) exportBtn.addEventListener('click', _exportAnalyticsCsv);
  document.addEventListener('click', event => {
    if (!(event.target instanceof Element)) return;
    if (!event.target.closest('.analytics-choice-menu') && !event.target.closest('.analytics-choice-toggle')) {
      closeObjectionStatusMenu();
    }
    if (!event.target.closest('.consultant-date-popover') && !event.target.closest('[data-themed-date="true"]')) {
      closeConsultantDatePicker();
    }
  });
  _renderTrackingFilterControls();
  _initAnalyticsTableScrollSync();
  _updateTrackingFilterSummary();
  _setAnalyticsRange(_analyticsRange);
  loadAnalytics();
}

function _setAnalyticsRange(range) {
  const today = new Date();
  const fromEl = document.getElementById('date-from');
  const toEl = document.getElementById('date-to');
  if (toEl) toEl.value = today.toISOString().slice(0, 10);
  if (!fromEl) return;
  if (range === 'all') {
    fromEl.value = '';
    return;
  }
  const days = Number(String(range).replace('d', '')) || 30;
  const from = new Date(today);
  from.setDate(today.getDate() - days);
  fromEl.value = from.toISOString().slice(0, 10);
}

async function loadAnalytics() {
  const from = (document.getElementById('date-from') || {}).value || '';
  const to   = (document.getElementById('date-to')   || {}).value || '';
  const params = new URLSearchParams();
  if (from) params.set('date_from', from);
  if (to)   params.set('date_to',   to);
  try {
    const data = await fetch('/api/analytics-data?' + params.toString()).then(r => r.json());
    _renderAnalytics(data);
  } catch (e) { console.error('Analytics load failed', e); }
}

function _renderAnalytics(d) {
  const setEl = (id, v) => { const el = document.getElementById(id); if (el) el.textContent = v; };
  const rows = d.rows || [];
  _analyticsRows = rows;
  setEl('metric-total', _formatNumber(d.total || 0));
  setEl('metric-common-type', d.most_common_type || '--');
  setEl('metric-common-destination', d.most_common_destination || '--');
  setEl('metric-common-service', d.most_common_service || 'No service data yet');
  setEl('metric-high-severity', _formatNumber(d.high_severity_count || 0));
  setEl('type-total', _formatNumber(d.total || 0));
  _renderMetricDeltas(d.metric_deltas || {});
  _drawDonutChart('chart-types', d.type_counts || {}, d.total || 0);
  _drawHorizontalBarChart('chart-services', d.service_counts || {});
  _drawHorizontalBarChart('chart-destinations', d.destination_counts || {});
  _drawMetricSparklines(d.weekly || {}, d);
  _renderTypeLegend(d.type_counts || {}, d.total || 0);
  _renderTopClusters(d.cluster_counts || {}, d.cluster_deltas || {});
  _analyticsRows = d.rows || [];
  _refreshTrackingTable();
  if (d.is_admin) {
    const ac = document.getElementById('admin-delete-controls');
    if (ac) ac.hidden = false;
    const bp = document.getElementById('bulk-delete-panel');
    if (bp) bp.hidden = false;
  }
}

const CHART_COLOURS = ['#FFD21A','#42C5F5','#FF9F4A','#9B78FF','#52BE8C','#9B9B9B','#80DEEA','#EF9A9A','#A5D6A7','#90CAF9'];

function _destroyChart(id) { if (window._explorerCharts && window._explorerCharts[id]) { window._explorerCharts[id].destroy(); delete window._explorerCharts[id]; } }
function _saveChart(id, chart) { if (!window._explorerCharts) window._explorerCharts = {}; window._explorerCharts[id] = chart; }

function _formatNumber(value) {
  return Number(value || 0).toLocaleString();
}

function _formatPercent(value) {
  const n = Number(value || 0);
  return (Number.isInteger(n) ? n.toFixed(0) : n.toFixed(1)) + '%';
}

function _formatDelta(value) {
  const n = Number(value || 0);
  const abs = Math.abs(n);
  const formatted = Number.isInteger(abs) ? abs.toFixed(0) : abs.toFixed(1);
  return (n > 0 ? '+' : n < 0 ? '-' : '') + formatted + '%';
}

function _setDelta(id, value) {
  const el = document.getElementById(id);
  if (!el) return;
  const n = Number(value || 0);
  el.textContent = _formatDelta(n);
  el.classList.toggle('negative', n < 0);
  el.classList.toggle('flat', n === 0);
}

function _renderMetricDeltas(deltas) {
  _setDelta('delta-total', deltas.total);
}

function _shortDateLabel(value) {
  const d = new Date(value + 'T00:00:00');
  if (Number.isNaN(d.getTime())) return value;
  return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
}

function _chartBaseOptions() {
  return {
    responsive: true,
    maintainAspectRatio: false,
    color: '#d8d8d8',
    font: {
      family: "'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
      size: 12,
      weight: '700',
    },
    plugins: {
      legend: { display: false },
      tooltip: {
        backgroundColor: '#111',
        borderColor: 'rgba(245,197,24,0.25)',
        borderWidth: 1,
        titleColor: '#fff',
        bodyColor: '#d6d6d6',
        titleFont: { size: 13, weight: '800' },
        bodyFont: { size: 12, weight: '650' },
        padding: 10,
        displayColors: false,
      },
    },
  };
}

function _drawDonutChart(canvasId, counts, total) {
  const canvas = document.getElementById(canvasId);
  if (!canvas || typeof Chart === 'undefined') return;
  _destroyChart(canvasId);
  const labels = Object.keys(counts), values = Object.values(counts);
  if (!labels.length) {
    _renderEmptyCanvas(canvas);
    return;
  }
  _saveChart(canvasId, new Chart(canvas, {
    type: 'doughnut',
    data: {
      labels,
      datasets: [{
        data: values,
        backgroundColor: CHART_COLOURS.slice(0, labels.length),
        borderColor: '#0a0a0a',
        borderWidth: 5,
        hoverOffset: 2,
      }],
    },
    options: {
      ..._chartBaseOptions(),
      cutout: '68%',
      layout: { padding: 6 },
    },
  }));
}

function _drawWeeklyAreaChart(canvasId, weekly) {
  const canvas = document.getElementById(canvasId);
  if (!canvas || typeof Chart === 'undefined') return;
  _destroyChart(canvasId);
  const labels = Object.keys(weekly).sort();
  const values = labels.map(k => weekly[k]);
  if (!labels.length) {
    _renderEmptyCanvas(canvas);
    return;
  }
  const ctx = canvas.getContext('2d');
  const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height || 260);
  gradient.addColorStop(0, 'rgba(245,197,24,0.36)');
  gradient.addColorStop(1, 'rgba(245,197,24,0.02)');
  const avg = values.length ? values.reduce((sum, n) => sum + Number(n || 0), 0) / values.length : 0;
  _saveChart(canvasId, new Chart(canvas, {
    type: 'line',
    data: {
      labels,
      datasets: [
        {
          label: 'Analyses',
          data: values,
          borderColor: '#F5C518',
          backgroundColor: gradient,
          pointBackgroundColor: '#050505',
          pointBorderColor: '#F5C518',
          pointBorderWidth: 2,
          pointRadius: 4,
          pointHoverRadius: 5,
          tension: 0.28,
          fill: true,
        },
        {
          label: 'Avg.',
          data: values.map(() => avg),
          borderColor: 'rgba(255,255,255,0.22)',
          borderDash: [5, 6],
          pointRadius: 0,
          fill: false,
        },
      ],
    },
    options: {
      ..._chartBaseOptions(),
      scales: {
        x: {
          ticks: {
            color: 'rgba(255,255,255,0.68)',
            font: { size: 12, weight: '750' },
            maxRotation: 0,
            callback: function(value, index) {
              if (labels.length <= 6 || index % Math.ceil(labels.length / 5) === 0) return _shortDateLabel(labels[index]);
              return '';
            },
          },
          grid: { display: false },
          border: { display: false },
        },
        y: {
          beginAtZero: true,
          ticks: { display: false },
          grid: { color: 'rgba(255,255,255,0.055)', borderDash: [2, 6] },
          border: { display: false },
        },
      },
    },
  }));
}

function _drawHorizontalBarChart(canvasId, counts) {
  const canvas = document.getElementById(canvasId);
  if (!canvas || typeof Chart === 'undefined') return;
  _destroyChart(canvasId);
  const entries = Object.entries(counts || {}).filter(([label]) => label).slice(0, 10);
  if (!entries.length) {
    _renderEmptyCanvas(canvas);
    return;
  }
  const labels = entries.map(([label]) => label);
  const values = entries.map(([, value]) => Number(value || 0));
  const isServiceChart = canvasId === 'chart-services';
  const isDestinationChart = canvasId === 'chart-destinations';
  _saveChart(canvasId, new Chart(canvas, {
    type: 'bar',
    data: {
      labels,
      datasets: [{
        data: values,
        backgroundColor: 'rgba(245,197,24,0.68)',
        borderColor: 'rgba(245,197,24,0.95)',
        borderWidth: 1,
        borderRadius: 4,
        barThickness: 16,
      }],
    },
    options: {
      ..._chartBaseOptions(),
      indexAxis: 'y',
      scales: {
        x: {
          beginAtZero: true,
          ticks: {
            color: 'rgba(255,255,255,0.78)',
            precision: 0,
            font: { size: 13, weight: '800' },
            padding: 8,
          },
          grid: { color: 'rgba(255,255,255,0.075)' },
          border: { display: false },
        },
        y: {
          afterFit: function(scale) {
            if (isServiceChart) {
              scale.width = Math.max(scale.width, 330);
            }
            if (isDestinationChart) {
              scale.width = Math.max(scale.width, 44);
            }
          },
          ticks: {
            color: 'rgba(255,255,255,0.96)',
            font: {
              size: isDestinationChart ? 14 : 13,
              weight: '900',
            },
            padding: isDestinationChart ? 12 : 10,
            autoSkip: false,
            callback: function(value) {
              return String(this.getLabelForValue(value) || '');
            },
          },
          grid: { display: false },
          border: { display: false },
        },
      },
    },
  }));
}

function _drawSparkline(canvasId, values, color) {
  const canvas = document.getElementById(canvasId);
  if (!canvas || typeof Chart === 'undefined') return;
  _destroyChart(canvasId);
  const data = values.length ? values : [0, 0, 0, 0];
  const ctx = canvas.getContext('2d');
  const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height || 42);
  gradient.addColorStop(0, color.replace('1)', '0.38)'));
  gradient.addColorStop(1, color.replace('1)', '0)'));
  _saveChart(canvasId, new Chart(canvas, {
    type: 'line',
    data: { labels: data.map((_, i) => i + 1), datasets: [{ data, borderColor: color, backgroundColor: gradient, pointRadius: 0, tension: 0.35, fill: true, borderWidth: 2 }] },
    options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false }, tooltip: { enabled: false } }, scales: { x: { display: false }, y: { display: false, beginAtZero: true } }, elements: { line: { capBezierPoints: true } } },
  }));
}

function _drawMetricSparklines(weekly, data) {
  const labels = Object.keys(weekly).sort();
  const values = labels.map(k => Number(weekly[k] || 0));
  const sample = values.length ? values : [0, 1, 1, 2, 2, 3, 4, 4];
  _drawSparkline('spark-total', sample, 'rgba(245,197,24,1)');
  _drawSparkline('spark-rate', sample.map((n, i) => Math.max(1, n + i * 0.2)), 'rgba(76,175,125,1)');
  _drawSparkline('spark-confidence', sample.map((n, i) => Math.max(1, n + i * 0.1)), 'rgba(79,195,247,1)');
  _drawSparkline('spark-staff', sample.map((n, i) => Math.max(1, n + (i % 3))), 'rgba(245,197,24,1)');
}

function _renderTypeLegend(counts, total) {
  const el = document.getElementById('type-legend');
  if (!el) return;
  const entries = Object.entries(counts || {});
  if (!entries.length) {
    el.innerHTML = '<div class="analytics-empty">No objection types yet.</div>';
    return;
  }
  el.innerHTML = entries.slice(0, 6).map(([label, value], i) => {
    const pct = total ? Math.round(Number(value || 0) / total * 100) : 0;
    return '<div class="analytics-type-row">' +
      '<span class="analytics-swatch" style="background:' + CHART_COLOURS[i % CHART_COLOURS.length] + '"></span>' +
      '<strong>' + esc(label || 'Unknown') + '</strong>' +
      '<span>' + _formatNumber(value) + '</span>' +
      '<em>' + pct + '%</em>' +
      '</div>';
  }).join('');
}

function _renderTopClusters(counts, deltas) {
  const el = document.getElementById('top-clusters-list');
  if (!el) return;
  const entries = Object.entries(counts || {}).filter(([label]) => label);
  if (!entries.length) {
    el.innerHTML = '<div class="analytics-empty">No clusters logged yet.</div>';
    return;
  }
  const max = Math.max(...entries.map(([, value]) => Number(value || 0)), 1);
  el.innerHTML = entries.slice(0, 8).map(([label, value], i) => {
    const width = Math.max(8, Math.round(Number(value || 0) / max * 100));
    const delta = Number((deltas || {})[label] || 0);
    const deltaClass = delta < 0 ? 'negative' : delta === 0 ? 'flat' : '';
    const deltaText = _formatDelta(delta);
    return '<div class="analytics-cluster-row">' +
      '<div class="analytics-cluster-meta">' +
      '<span>' + String(i + 1).padStart(2, '0') + '</span>' +
      '<strong>' + esc(label) + '</strong>' +
      '<em class="' + deltaClass + '">' + deltaText + '</em>' +
      '<b>' + _formatNumber(value) + '</b>' +
      '</div>' +
      '<div class="analytics-progress"><span style="width:' + width + '%"></span></div>' +
      '</div>';
  }).join('');
}

function _renderEmptyCanvas(canvas) {
  const ctx = canvas.getContext('2d');
  ctx.clearRect(0, 0, canvas.width, canvas.height);
}

function _renderTrackingFilterControls() {
  const fields = document.getElementById('tracking-filter-fields');
  if (!fields) return;
  const options = TRACKING_FILTER_COLUMNS.map(([key, label]) =>
    '<option value="' + esc(key) + '">' + esc(label) + '</option>'
  ).join('');
  fields.innerHTML =
    '<div class="analytics-filter-builder">' +
      '<div class="field">' +
        '<label class="field-label" for="tracking-filter-column">Column</label>' +
        '<select id="tracking-filter-column" class="select" onchange="onTrackingFilterColumnChange()">' +
          '<option value="">Select a column</option>' + options +
        '</select>' +
      '</div>' +
      '<div class="field analytics-filter-value-field" id="tracking-filter-value-field" hidden></div>' +
      '<button class="btn btn-outline btn-sm analytics-filter-add-btn" id="tracking-filter-add-btn" onclick="applyTrackingFilters()" type="button" disabled>Add filter</button>' +
    '</div>';
  _renderActiveTrackingFilters();
}

function toggleTrackingFilterPanel() {
  const panel = document.getElementById('tracking-filter-panel');
  const btn = document.getElementById('tracking-filter-toggle');
  if (!panel) return;
  panel.hidden = !panel.hidden;
  if (btn) btn.classList.toggle('is-active', !panel.hidden);
}

function closeTrackingFilterPanel() {
  const panel = document.getElementById('tracking-filter-panel');
  const btn = document.getElementById('tracking-filter-toggle');
  if (panel) panel.hidden = true;
  if (btn) btn.classList.remove('is-active');
}

function onTrackingFilterColumnChange() {
  const column = document.getElementById('tracking-filter-column');
  const valueField = document.getElementById('tracking-filter-value-field');
  const addBtn = document.getElementById('tracking-filter-add-btn');
  const key = column ? column.value : '';
  const hasColumn = Boolean(key);
  if (valueField) valueField.hidden = !hasColumn;
  if (addBtn) addBtn.disabled = !hasColumn;
  if (valueField) valueField.innerHTML = hasColumn ? _trackingFilterValueControl(key) : '';
  const valueInput = document.getElementById('tracking-filter-value');
  if (hasColumn && valueInput) valueInput.focus();
}

function _trackingFilterValueControl(key) {
  const selectOptions = _trackingFilterSelectOptions(key);
  if (selectOptions) {
    const options = selectOptions.map(value =>
      '<option value="' + esc(value) + '">' + esc(value) + '</option>'
    ).join('');
    return '<label class="field-label" for="tracking-filter-value">Contains</label>' +
      '<select id="tracking-filter-value" class="select analytics-filter-input">' +
        '<option value="">Select an option</option>' + options +
      '</select>';
  }
  if (TRACKING_FILTER_DATE_COLUMNS.has(key)) {
    return '<label class="field-label" for="tracking-filter-value">Contains</label>' +
      '<input id="tracking-filter-value" class="input analytics-filter-input analytics-filter-date-input consultant-date-input" type="text" inputmode="none" autocomplete="off" readonly placeholder="Select date" data-themed-date="true" data-date-picker-mode="analytics-filter" onclick="openAnalyticsFilterDatePicker(this)" onfocus="openAnalyticsFilterDatePicker(this)" onkeydown="if(event.key === \'Enter\') applyTrackingFilters()" />';
  }
  if (TRACKING_FILTER_AUTOCOMPLETE_COLUMNS.has(key)) {
    return '<label class="field-label" for="tracking-filter-value">Contains</label>' +
      '<div class="analytics-filter-autocomplete">' +
        '<input id="tracking-filter-value" class="input analytics-filter-input" type="text" autocomplete="off" placeholder="Search ' + esc(_trackingFilterLabel(key).toLowerCase()) + '" oninput="updateTrackingFilterSuggestions()" onfocus="updateTrackingFilterSuggestions()" onkeydown="handleTrackingFilterAutocompleteKey(event)" />' +
        '<div id="tracking-filter-suggestions" class="analytics-filter-suggestions" hidden></div>' +
      '</div>';
  }
  return '<label class="field-label" for="tracking-filter-value">Contains</label>' +
    '<input id="tracking-filter-value" class="input analytics-filter-input" type="text" placeholder="Type value to match" onkeydown="if(event.key === \'Enter\') applyTrackingFilters()" />';
}

function _trackingFilterSelectOptions(key) {
  if (key === 'user_name') {
    const rowNames = (_analyticsRows || [])
      .map(row => String(row.user_name || '').trim())
      .filter(Boolean);
    return Array.from(new Set([...TRACKING_FILTER_STAFF_FALLBACK, ...rowNames]));
  }
  return TRACKING_FILTER_SELECT_OPTIONS[key] || null;
}

function openAnalyticsFilterDatePicker(input) {
  openConsultantDatePicker(input);
}

function updateTrackingFilterSuggestions() {
  const column = document.getElementById('tracking-filter-column');
  const input = document.getElementById('tracking-filter-value');
  const list = document.getElementById('tracking-filter-suggestions');
  if (!column || !input || !list) return;
  const key = column.value;
  const needle = input.value.trim().toLowerCase();
  const values = _trackingAutocompleteValues(key)
    .filter(value => !needle || value.toLowerCase().includes(needle))
    .slice(0, 10);
  if (!values.length || !needle) {
    list.hidden = true;
    list.innerHTML = '';
    return;
  }
  list.innerHTML = values.map(value =>
    '<button type="button" class="analytics-filter-suggestion" data-value="' + esc(value) + '" onclick="selectTrackingFilterSuggestion(this.dataset.value)">' + esc(value) + '</button>'
  ).join('');
  list.hidden = false;
}

function handleTrackingFilterAutocompleteKey(event) {
  if (event.key === 'Escape') {
    closeTrackingFilterSuggestions();
    return;
  }
  if (event.key === 'Enter') {
    event.preventDefault();
    applyTrackingFilters();
  }
}

function selectTrackingFilterSuggestion(value) {
  const input = document.getElementById('tracking-filter-value');
  if (input) input.value = value || '';
  closeTrackingFilterSuggestions();
}

function closeTrackingFilterSuggestions() {
  const list = document.getElementById('tracking-filter-suggestions');
  if (list) {
    list.hidden = true;
    list.innerHTML = '';
  }
}

function _trackingAutocompleteValues(key) {
  if (!TRACKING_FILTER_AUTOCOMPLETE_COLUMNS.has(key)) return [];
  const values = (_analyticsRows || [])
    .map(row => String(row[key] || '').trim())
    .filter(Boolean);
  return Array.from(new Set(values)).sort((a, b) => a.localeCompare(b));
}

function applyTrackingFilters() {
  const column = document.getElementById('tracking-filter-column');
  const valueInput = document.getElementById('tracking-filter-value');
  const key = column ? column.value : '';
  const value = valueInput ? valueInput.value.trim() : '';
  if (key && value) {
    _trackingFilters = { ..._trackingFilters, [key]: value };
    if (column) column.value = '';
    if (valueInput) valueInput.value = '';
    closeTrackingFilterSuggestions();
    onTrackingFilterColumnChange();
  }
  _refreshTrackingTable();
}

function clearTrackingFilters() {
  _trackingFilters = {};
  const column = document.getElementById('tracking-filter-column');
  if (column) column.value = '';
  onTrackingFilterColumnChange();
  _refreshTrackingTable();
}

function removeTrackingFilter(key) {
  delete _trackingFilters[key];
  _refreshTrackingTable();
}

function _refreshTrackingTable() {
  _analyticsFilteredRows = _filterTrackingRows(_analyticsRows);
  _renderAnalyticsTable(_analyticsFilteredRows);
  _updateTrackingFilterSummary();
  _renderActiveTrackingFilters();
}

function _filterTrackingRows(rows) {
  const filters = Object.entries(_trackingFilters).filter(([, value]) => String(value || '').trim());
  if (!filters.length) return rows || [];
  return (rows || []).filter(row => filters.every(([key, value]) => {
    const haystack = String(row[key] == null ? '' : row[key]).toLowerCase();
    return haystack.includes(String(value).toLowerCase());
  }));
}

function _updateTrackingFilterSummary() {
  const summary = document.getElementById('tracking-filter-summary');
  const btn = document.getElementById('tracking-filter-toggle');
  const activeCount = Object.keys(_trackingFilters).length;
  const shown = (_analyticsFilteredRows || []).length;
  const total = (_analyticsRows || []).length;
  if (summary) {
    summary.textContent = activeCount ? activeCount + ' filter' + (activeCount === 1 ? '' : 's') + ' active - showing ' + shown + ' of ' + total : 'No filters applied';
  }
  if (btn) {
    btn.textContent = activeCount ? 'Filters (' + activeCount + ')' : 'Filter columns';
    btn.classList.toggle('has-active-filters', activeCount > 0);
  }
}

function _trackingFilterLabel(key) {
  const found = TRACKING_FILTER_COLUMNS.find(([columnKey]) => columnKey === key);
  return found ? found[1] : key;
}

function _renderActiveTrackingFilters() {
  const list = document.getElementById('tracking-active-filters');
  if (!list) return;
  const entries = Object.entries(_trackingFilters);
  if (!entries.length) {
    list.innerHTML = '<div class="analytics-filter-empty">No column filters selected.</div>';
    return;
  }
  list.innerHTML = entries.map(([key, value]) =>
    '<div class="analytics-filter-chip">' +
      '<span><strong>' + esc(_trackingFilterLabel(key)) + '</strong> contains "' + esc(value) + '"</span>' +
      '<button type="button" onclick="removeTrackingFilter(\'' + esc(key) + '\')" aria-label="Remove ' + esc(_trackingFilterLabel(key)) + ' filter">&times;</button>' +
    '</div>'
  ).join('');
}

function _initAnalyticsTableScrollSync() {
  const topScroll = document.getElementById('analytics-table-top-scroll');
  const tableWrap = document.querySelector('.analytics-table-wrap');
  if (!topScroll || !tableWrap || _analyticsScrollSyncReady) return;
  _analyticsScrollSyncReady = true;
  topScroll.addEventListener('scroll', () => _syncAnalyticsTableScroll(topScroll, tableWrap), { passive: true });
  tableWrap.addEventListener('scroll', () => _syncAnalyticsTableScroll(tableWrap, topScroll), { passive: true });
  window.addEventListener('resize', () => {
    _updateAnalyticsTableScrollbar();
    _syncAnalyticsEditPanelPosition();
  });
  _updateAnalyticsTableScrollbar();
  _syncAnalyticsEditPanelPosition();
}

function _syncAnalyticsTableScroll(source, target) {
  if (_analyticsScrollSyncing) return;
  _analyticsScrollSyncing = true;
  target.scrollLeft = source.scrollLeft;
  requestAnimationFrame(() => {
    _analyticsScrollSyncing = false;
    _syncAnalyticsEditPanelPosition();
  });
}

function _syncAnalyticsEditPanelPosition() {
  const tableWrap = document.querySelector('.analytics-table-wrap');
  const panel = document.querySelector('.analytics-edit-inline-panel');
  if (!tableWrap || !panel) return;
  const width = Math.max(320, Math.floor(tableWrap.clientWidth || window.innerWidth || 320));
  panel.style.width = width + 'px';
  panel.style.maxWidth = width + 'px';
  panel.style.transform = 'translateX(' + Math.max(0, Math.floor(tableWrap.scrollLeft || 0)) + 'px)';
}

function _updateAnalyticsTableScrollbar() {
  const topScroll = document.getElementById('analytics-table-top-scroll');
  const spacer = document.getElementById('analytics-table-scroll-spacer');
  const tableWrap = document.querySelector('.analytics-table-wrap');
  const table = document.getElementById('interactions-table');
  if (!topScroll || !spacer || !tableWrap || !table) return;
  const scrollWidth = Math.max(table.scrollWidth, tableWrap.scrollWidth, tableWrap.clientWidth);
  spacer.style.width = scrollWidth + 'px';
  topScroll.hidden = scrollWidth <= tableWrap.clientWidth + 1;
  topScroll.scrollLeft = tableWrap.scrollLeft;
}

function _renderAnalyticsTable(rows) {
  const tbody   = document.getElementById('interactions-body');
  const thCheck = document.getElementById('th-check');
  if (!tbody) return;
  if (thCheck) thCheck.hidden = !_deleteMode;
  if (!rows.length) {
    const emptyText = Object.keys(_trackingFilters).length ? 'No interactions match the current filters.' : 'No interactions in this date range.';
    tbody.innerHTML = '<tr><td colspan="16" class="text-center text-muted analytics-empty-row">' + emptyText + '</td></tr>';
    _updateAnalyticsTableScrollbar();
    return;
  }
  tbody.innerHTML = rows.map(r => {
    const id = Number(r.id || 0);
    return '<tr data-id="' + r.id + '">' +
    '<td id="td-check-' + r.id + '"' + (_deleteMode ? '' : ' hidden') + '><input type="checkbox" data-id="' + r.id + '" onchange="_toggleSelectRow(' + r.id + ', this.checked)"' + (_selectedIds.has(Number(r.id)) ? ' checked' : '') + ' /></td>' +
    '<td class="analytics-time">' + esc(_displayTime(r.timestamp)) + '</td>' +
    '<td class="analytics-staff">' + esc(r.user_name || 'Unknown') + '</td>' +
    '<td class="analytics-customer-cell" title="' + esc(r.customer_name || '') + '">' + esc(r.customer_name || '--') + '</td>' +
    '<td>' + _statusSelect(r) + '</td>' +
    '<td class="analytics-date-cell">' + esc(r.first_contact_date || '--') + '</td>' +
    '<td class="analytics-date-cell">' + esc(r.objection_date || '--') + '</td>' +
    '<td class="analytics-platform-cell" title="' + esc(r.main_contact_platform || '') + '">' + esc(r.main_contact_platform || '--') + '</td>' +
    '<td>' + _leadQualitySelect(r) + '</td>' +
    '<td class="analytics-service-cell" title="' + esc(r.service || '') + '">' + esc(r.service || '--') + '</td>' +
    '<td class="analytics-source-cell" title="' + esc(r.ad_source || '') + '">' + esc(r.ad_source || '--') + '</td>' +
    '<td>' + _typeBadge(r.objection_type) + '</td>' +
    '<td class="analytics-cluster-cell">' + esc(r.cluster || 'Unclustered') + '</td>' +
    '<td>' + severityBadge(r.severity) + '</td>' +
    '<td class="analytics-quote" title="' + esc(r.quote || '') + '">' + esc(_quotePreview(r.quote || '')) + '</td>' +
    '<td class="analytics-action-cell"><button type="button" class="btn btn-outline btn-sm analytics-edit-row-btn" onclick="toggleAnalyticsEditRow(' + id + ')">' + (Number(_analyticsEditRowId) === id ? 'Close' : 'Edit') + '</button></td>' +
    '</tr>' +
    (Number(_analyticsEditRowId) === id ? _analyticsEditInlineRow(r) : '');
  }).join('');
  _updateAnalyticsTableScrollbar();
  requestAnimationFrame(_syncAnalyticsEditPanelPosition);
}

function _displayTime(value) {
  if (!value) return '--';
  const d = new Date(String(value).replace(' ', 'T'));
  if (Number.isNaN(d.getTime())) return String(value).slice(11, 16) || String(value).slice(0, 5);
  return d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', hour12: false });
}

function _quotePreview(value) {
  const clean = String(value || '').trim();
  return clean.length > 34 ? '"' + clean.slice(0, 32) + '..."' : '"' + clean + '"';
}

function _typeBadge(value) {
  const label = String(value || 'Other').trim() || 'Other';
  return '<span class="pill pill-neutral analytics-type-pill">' + esc(label) + '</span>';
}

function _trackingBadge(value) {
  const label = String(value || '--').trim() || '--';
  return '<span class="pill pill-neutral analytics-type-pill">' + esc(label) + '</span>';
}

function _normaliseObjectionStatus(value) {
  return String(value || '').trim().toLowerCase() === 'solved' ? 'Solved' : 'Unsolved';
}

function _normaliseLeadQuality(value) {
  const raw = String(value || '').trim();
  const found = LEAD_QUALITY_OPTIONS.find(item => item.toLowerCase() === raw.toLowerCase());
  return found || 'Qualified';
}

function _leadQualityClass(value) {
  if (!String(value || '').trim()) return '';
  const normalised = _normaliseLeadQuality(value);
  if (normalised === 'Qualified' || normalised === 'Converted') return ' analytics-lead-quality-positive';
  if (normalised === 'Not Qualified' || normalised === 'Lost') return ' analytics-lead-quality-negative';
  if (normalised === 'Intake') return ' analytics-lead-quality-intake';
  if (normalised === 'Awaiting Documents') return ' analytics-lead-quality-awaiting';
  return '';
}

function _analyticsChoiceOptionClass(kind, value) {
  if (kind === 'lead_quality') return _leadQualityClass(value).replace('analytics-lead-quality-', 'analytics-choice-option-');
  const status = _normaliseObjectionStatus(value);
  return status === 'Solved' ? ' analytics-choice-option-positive' : ' analytics-choice-option-negative';
}

function _statusSelect(row) {
  const id = Number(row && row.id ? row.id : 0);
  const value = _normaliseObjectionStatus(row ? row.objection_status : '');
  const statusClass = value === 'Solved' ? ' analytics-status-solved' : ' analytics-status-unsolved';
  return '<button type="button" class="analytics-status-toggle analytics-choice-toggle' + statusClass + '" data-kind="status" data-id="' + id + '" data-value="' + esc(value) + '" onclick="toggleAnalyticsChoiceMenu(event, this)">' +
    '<span>' + esc(value) + '</span><b aria-hidden="true">▾</b>' +
    '</button>';
}

function _leadQualitySelect(row) {
  const id = Number(row && row.id ? row.id : 0);
  const raw = String(row && row.lead_quality ? row.lead_quality : '').trim();
  const value = raw ? _normaliseLeadQuality(raw) : '--';
  const dataValue = value === '--' ? '' : value;
  return '<button type="button" class="analytics-lead-quality-toggle analytics-choice-toggle' + _leadQualityClass(dataValue) + '" data-kind="lead_quality" data-id="' + id + '" data-value="' + esc(dataValue) + '" onclick="toggleAnalyticsChoiceMenu(event, this)">' +
    '<span>' + esc(value) + '</span><b aria-hidden="true">▾</b>' +
    '</button>';
}

function toggleAnalyticsChoiceMenu(event, button) {
  if (event) event.stopPropagation();
  if (!button) return;
  const id = Number(button.dataset.id || 0);
  const kind = button.dataset.kind || 'status';
  const isLeadQuality = kind === 'lead_quality';
  const options = isLeadQuality ? LEAD_QUALITY_OPTIONS : ['Solved', 'Unsolved'];
  const current = isLeadQuality
    ? _normaliseLeadQuality(button.dataset.value || button.textContent || '')
    : _normaliseObjectionStatus(button.dataset.value || button.textContent || '');
  closeObjectionStatusMenu();

  const rect = button.getBoundingClientRect();
  _statusMenuEl = document.createElement('div');
  _statusMenuEl.className = 'analytics-choice-menu';
  _statusMenuEl.style.left = Math.round(rect.left) + 'px';
  _statusMenuEl.style.top = Math.round(rect.bottom + 6) + 'px';
  _statusMenuEl.style.minWidth = Math.max(isLeadQuality ? 184 : 128, Math.round(rect.width)) + 'px';
  _statusMenuEl.innerHTML = options.map(option => {
    const selected = option === current ? ' is-selected' : '';
    const toneClass = _analyticsChoiceOptionClass(kind, option);
    const safeKind = kind.replace(/'/g, "\\'");
    const safeOption = option.replace(/'/g, "\\'");
    return '<button type="button" class="analytics-choice-option' + toneClass + selected + '" onclick="chooseAnalyticsChoice(' + id + ', \'' + safeKind + '\', \'' + safeOption + '\')">' + esc(option) + '</button>';
  }).join('');
  document.body.appendChild(_statusMenuEl);
}

function closeObjectionStatusMenu() {
  if (_statusMenuEl) {
    _statusMenuEl.remove();
    _statusMenuEl = null;
  }
}

async function chooseAnalyticsChoice(id, kind, value) {
  const button = document.querySelector('.analytics-choice-toggle[data-kind="' + kind + '"][data-id="' + id + '"]');
  closeObjectionStatusMenu();
  if (kind === 'lead_quality') {
    await updateLeadQuality(id, value, button);
  } else {
    await updateObjectionStatus(id, value, button);
  }
}

async function updateObjectionStatus(id, status, controlEl) {
  id = Number(id || 0);
  status = _normaliseObjectionStatus(status);
  if (!id) return;
  const previous = _normaliseObjectionStatus(controlEl ? controlEl.dataset.value : '');
  if (status === previous) return;
  if (controlEl) controlEl.disabled = true;
  try {
    await postJSON('/analytics/status', { id, objection_status: status });
    const row = (_analyticsRows || []).find(item => Number(item.id) === id);
    if (row) row.objection_status = status;
    const filteredRow = (_analyticsFilteredRows || []).find(item => Number(item.id) === id);
    if (filteredRow) filteredRow.objection_status = status;
    if (controlEl) {
      controlEl.dataset.value = status;
      const label = controlEl.querySelector('span');
      if (label) label.textContent = status;
      controlEl.classList.toggle('analytics-status-solved', status === 'Solved');
      controlEl.classList.toggle('analytics-status-unsolved', status === 'Unsolved');
    }
  } catch (e) {
    alert(e.detail || 'Failed to update objection status.');
  } finally {
    if (controlEl) controlEl.disabled = false;
  }
}

async function updateLeadQuality(id, leadQuality, controlEl) {
  id = Number(id || 0);
  leadQuality = _normaliseLeadQuality(leadQuality);
  if (!id) return;
  const previous = controlEl ? _normaliseLeadQuality(controlEl.dataset.value || controlEl.textContent || '') : '';
  if (leadQuality === previous) return;
  if (controlEl) controlEl.disabled = true;
  try {
    await postJSON('/analytics/lead-quality', { id, lead_quality: leadQuality });
    const row = (_analyticsRows || []).find(item => Number(item.id) === id);
    if (row) row.lead_quality = leadQuality;
    const filteredRow = (_analyticsFilteredRows || []).find(item => Number(item.id) === id);
    if (filteredRow) filteredRow.lead_quality = leadQuality;
    if (controlEl) {
      controlEl.dataset.value = leadQuality;
      const label = controlEl.querySelector('span');
      if (label) label.textContent = leadQuality;
      controlEl.classList.toggle('analytics-lead-quality-positive', leadQuality === 'Qualified' || leadQuality === 'Converted');
      controlEl.classList.toggle('analytics-lead-quality-negative', leadQuality === 'Not Qualified' || leadQuality === 'Lost');
      controlEl.classList.toggle('analytics-lead-quality-intake', leadQuality === 'Intake');
      controlEl.classList.toggle('analytics-lead-quality-awaiting', leadQuality === 'Awaiting Documents');
    }
  } catch (e) {
    alert(e.detail || 'Failed to update lead quality.');
  } finally {
    if (controlEl) controlEl.disabled = false;
  }
}

function toggleAnalyticsEditRow(id) {
  id = Number(id || 0);
  const row = (_analyticsRows || []).find(item => Number(item.id) === id);
  if (!row) return;
  _analyticsEditRowId = Number(_analyticsEditRowId) === id ? null : id;
  _refreshTrackingTable();
  if (_analyticsEditRowId) {
    requestAnimationFrame(() => {
      _syncAnalyticsEditPanelPosition();
      const editRow = document.querySelector('[data-edit-row-id="' + id + '"]');
      if (editRow) editRow.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
    });
  }
}

function openAnalyticsEditModal(id) {
  toggleAnalyticsEditRow(id);
}

function closeAnalyticsEditModal() {
  _analyticsEditRowId = null;
  _refreshTrackingTable();
}

function _analyticsEditFieldId(name, id) {
  return 'analytics-edit-' + name + '-' + Number(id || 0);
}

function _analyticsEditValue(name, id) {
  const el = document.getElementById(_analyticsEditFieldId(name, id));
  return ((el || {}).value || '').trim();
}

function _analyticsOption(value, label, selected) {
  const selectedAttr = String(value || '') === String(selected || '') ? ' selected' : '';
  return '<option value="' + esc(value) + '"' + selectedAttr + '>' + esc(label == null ? value : label) + '</option>';
}

function _analyticsEditInlineRow(row) {
  const id = Number(row && row.id ? row.id : 0);
  const objectionStatus = _normaliseObjectionStatus(row ? row.objection_status : '');
  const leadQuality = row && row.lead_quality ? _normaliseLeadQuality(row.lead_quality) : '';
  const mainPlatformOptions = ['Explorer Webapp', 'Explorer by SL', 'Explorer Travel Agency'];
  const severityOptions = ['Low', 'Medium', 'High'];
  const context = (row.customer_name || 'Customer') + ' | ' + (row.service || 'No service');
  return '<tr class="analytics-edit-inline-row" data-edit-row-id="' + id + '">' +
    '<td colspan="16">' +
      '<div class="analytics-edit-inline-panel">' +
        '<div class="analytics-edit-inline-header">' +
          '<div><div class="card-label">Edit Customer Objection</div><div class="analytics-panel-subtitle">' + esc(context) + '</div></div>' +
          '<button class="btn btn-outline btn-sm" type="button" onclick="closeAnalyticsEditModal()">Cancel</button>' +
        '</div>' +
        '<div class="analytics-edit-readonly">' +
          '<div><span>Time</span><strong>' + esc(_displayTime(row.timestamp) || '--') + '</strong></div>' +
          '<div><span>Staff</span><strong>' + esc(row.user_name || 'Unknown') + '</strong></div>' +
        '</div>' +
        '<form id="analytics-edit-form-' + id + '" class="analytics-edit-form" onsubmit="saveAnalyticsEdit(event, ' + id + ')">' +
          '<div class="analytics-edit-grid">' +
            '<div class="field"><label class="field-label" for="' + _analyticsEditFieldId('customer-name', id) + '">Customer Name</label><input class="input" type="text" id="' + _analyticsEditFieldId('customer-name', id) + '" maxlength="120" value="' + esc(row.customer_name || '') + '" /></div>' +
            '<div class="field"><label class="field-label" for="' + _analyticsEditFieldId('objection-status', id) + '">Objection Status</label><select class="select" id="' + _analyticsEditFieldId('objection-status', id) + '">' + _analyticsOption('Solved', 'Solved', objectionStatus) + _analyticsOption('Unsolved', 'Unsolved', objectionStatus) + '</select></div>' +
            '<div class="field"><label class="field-label" for="' + _analyticsEditFieldId('first-contact-date', id) + '">First Contact Date</label><input class="input" type="date" id="' + _analyticsEditFieldId('first-contact-date', id) + '" value="' + esc(row.first_contact_date || '') + '" /></div>' +
            '<div class="field"><label class="field-label" for="' + _analyticsEditFieldId('objection-date', id) + '">Objection Date</label><input class="input" type="date" id="' + _analyticsEditFieldId('objection-date', id) + '" value="' + esc(row.objection_date || '') + '" /></div>' +
            '<div class="field"><label class="field-label" for="' + _analyticsEditFieldId('main-contact-platform', id) + '">Main Contact Platform</label><select class="select" id="' + _analyticsEditFieldId('main-contact-platform', id) + '">' + _analyticsOption('', '--', row.main_contact_platform || '') + mainPlatformOptions.map(option => _analyticsOption(option, option, row.main_contact_platform || '')).join('') + '</select></div>' +
            '<div class="field"><label class="field-label" for="' + _analyticsEditFieldId('lead-quality', id) + '">Lead Quality</label><select class="select" id="' + _analyticsEditFieldId('lead-quality', id) + '">' + _analyticsOption('', '--', leadQuality) + LEAD_QUALITY_OPTIONS.map(option => _analyticsOption(option, option, leadQuality)).join('') + '</select></div>' +
            '<div class="field analytics-edit-wide"><label class="field-label" for="' + _analyticsEditFieldId('service', id) + '">Service</label><input class="input" type="text" id="' + _analyticsEditFieldId('service', id) + '" value="' + esc(row.service || '') + '" /></div>' +
            '<div class="field"><label class="field-label" for="' + _analyticsEditFieldId('ad-source', id) + '">Ad Source</label><input class="input" type="text" id="' + _analyticsEditFieldId('ad-source', id) + '" maxlength="120" value="' + esc(row.ad_source || '') + '" /></div>' +
            '<div class="field"><label class="field-label" for="' + _analyticsEditFieldId('objection-type', id) + '">Objection Type</label><input class="input" type="text" id="' + _analyticsEditFieldId('objection-type', id) + '" value="' + esc(row.objection_type || '') + '" /></div>' +
            '<div class="field"><label class="field-label" for="' + _analyticsEditFieldId('cluster', id) + '">Cluster</label><input class="input" type="text" id="' + _analyticsEditFieldId('cluster', id) + '" value="' + esc(row.cluster || '') + '" /></div>' +
            '<div class="field"><label class="field-label" for="' + _analyticsEditFieldId('severity', id) + '">Severity</label><select class="select" id="' + _analyticsEditFieldId('severity', id) + '">' + _analyticsOption('', '--', row.severity || '') + severityOptions.map(option => _analyticsOption(option, option, row.severity || '')).join('') + '</select></div>' +
            '<div class="field analytics-edit-wide"><label class="field-label" for="' + _analyticsEditFieldId('quote', id) + '">Exact Quote</label><textarea class="textarea" id="' + _analyticsEditFieldId('quote', id) + '" rows="5" required>' + esc(row.quote || '') + '</textarea></div>' +
          '</div>' +
          '<div class="analytics-edit-actions">' +
            '<div id="' + _analyticsEditFieldId('message', id) + '" class="analytics-edit-message" hidden></div>' +
            '<button class="btn btn-primary" type="submit">Save Changes</button>' +
            '<button class="btn btn-outline" type="button" onclick="closeAnalyticsEditModal()">Cancel</button>' +
          '</div>' +
        '</form>' +
      '</div>' +
    '</td>' +
  '</tr>';
}

async function saveAnalyticsEdit(event, id) {
  if (event) event.preventDefault();
  const rowId = Number(id || 0);
  const form = document.getElementById('analytics-edit-form-' + rowId);
  const btn = form ? form.querySelector('button[type="submit"]') : null;
  const msg = document.getElementById(_analyticsEditFieldId('message', rowId));
  const payload = {
    id: rowId,
    customer_name: _analyticsEditValue('customer-name', rowId),
    objection_status: _analyticsEditValue('objection-status', rowId),
    first_contact_date: _analyticsEditValue('first-contact-date', rowId),
    objection_date: _analyticsEditValue('objection-date', rowId),
    main_contact_platform: _analyticsEditValue('main-contact-platform', rowId),
    lead_quality: _analyticsEditValue('lead-quality', rowId),
    service: _analyticsEditValue('service', rowId),
    ad_source: _analyticsEditValue('ad-source', rowId),
    objection_type: _analyticsEditValue('objection-type', rowId),
    cluster: _analyticsEditValue('cluster', rowId),
    severity: _analyticsEditValue('severity', rowId),
    quote: _analyticsEditValue('quote', rowId),
  };
  if (!payload.quote) {
    if (msg) { msg.textContent = 'Exact quote is required.'; msg.style.color = 'var(--red)'; msg.hidden = false; }
    return;
  }
  if (btn) { btn.disabled = true; btn.textContent = 'Saving...'; }
  if (msg) msg.hidden = true;
  try {
    const data = await postJSON('/analytics/interaction/edit', payload);
    [_analyticsRows, _analyticsFilteredRows].forEach(list => {
      const editRow = (list || []).find(item => Number(item.id) === Number(payload.id));
      if (editRow) {
        Object.assign(editRow, {
          customer_name: data.customer_name,
          quote: data.quote,
          objection_status: data.objection_status,
          first_contact_date: data.first_contact_date,
          objection_date: data.objection_date,
          main_contact_platform: data.main_contact_platform,
          lead_quality: data.lead_quality,
          service: data.service,
          destination: data.destination,
          ad_source: data.ad_source,
          objection_type: data.objection_type,
          cluster: data.cluster,
          severity: data.severity,
        });
      }
    });
    _analyticsEditRowId = null;
    _refreshTrackingTable();
  } catch (e) {
    if (msg) { msg.textContent = e.detail || 'Failed to save changes.'; msg.style.color = 'var(--red)'; msg.hidden = false; }
    else alert(e.detail || 'Failed to save changes.');
  } finally {
    if (btn) { btn.disabled = false; btn.textContent = 'Save Changes'; }
  }
}

/* Legacy modal implementation removed from the active inline edit flow.
function openAnalyticsEditModal(id) {
  const row = (_analyticsRows || []).find(item => Number(item.id) === Number(id));
  if (!row) return;
  const overlay = document.getElementById('analytics-edit-overlay');
  if (!overlay) return;

  _setAnalyticsEditValue('analytics-edit-id', row.id || '');
  _setAnalyticsEditText('analytics-edit-time', _displayTime(row.timestamp) || '--');
  _setAnalyticsEditText('analytics-edit-staff', row.user_name || 'Unknown');
  _setAnalyticsEditText('analytics-edit-context', (row.customer_name || 'Customer') + ' · ' + (row.service || 'No service'));
  _setAnalyticsEditValue('analytics-edit-customer-name', row.customer_name || '');
  _setAnalyticsEditValue('analytics-edit-objection-status', _normaliseObjectionStatus(row.objection_status || 'Unsolved'));
  _setAnalyticsEditValue('analytics-edit-first-contact-date', row.first_contact_date || '');
  _setAnalyticsEditValue('analytics-edit-objection-date', row.objection_date || '');
  _setAnalyticsEditValue('analytics-edit-main-contact-platform', row.main_contact_platform || '');
  _setAnalyticsEditValue('analytics-edit-lead-quality', row.lead_quality || '');
  _setAnalyticsEditValue('analytics-edit-service', row.service || '');
  _setAnalyticsEditValue('analytics-edit-ad-source', row.ad_source || '');
  _setAnalyticsEditValue('analytics-edit-objection-type', row.objection_type || '');
  _setAnalyticsEditValue('analytics-edit-cluster', row.cluster || '');
  _setAnalyticsEditValue('analytics-edit-severity', row.severity || '');
  _setAnalyticsEditValue('analytics-edit-quote', row.quote || '');
  const msg = document.getElementById('analytics-edit-message');
  if (msg) { msg.hidden = true; msg.textContent = ''; msg.style.color = ''; }
  overlay.hidden = false;
}

function closeAnalyticsEditModal() {
  const overlay = document.getElementById('analytics-edit-overlay');
  if (overlay) overlay.hidden = true;
}

function _setAnalyticsEditValue(id, value) {
  const el = document.getElementById(id);
  if (el) el.value = value == null ? '' : String(value);
}

function _setAnalyticsEditText(id, value) {
  const el = document.getElementById(id);
  if (el) el.textContent = value == null ? '' : String(value);
}

async function saveAnalyticsEdit(event) {
  if (event) event.preventDefault();
  const form = document.getElementById('analytics-edit-form');
  const btn = form ? form.querySelector('button[type="submit"]') : null;
  const msg = document.getElementById('analytics-edit-message');
  const payload = {
    id: Number((document.getElementById('analytics-edit-id') || {}).value || 0),
    customer_name: ((document.getElementById('analytics-edit-customer-name') || {}).value || '').trim(),
    objection_status: ((document.getElementById('analytics-edit-objection-status') || {}).value || '').trim(),
    first_contact_date: ((document.getElementById('analytics-edit-first-contact-date') || {}).value || '').trim(),
    objection_date: ((document.getElementById('analytics-edit-objection-date') || {}).value || '').trim(),
    main_contact_platform: ((document.getElementById('analytics-edit-main-contact-platform') || {}).value || '').trim(),
    lead_quality: ((document.getElementById('analytics-edit-lead-quality') || {}).value || '').trim(),
    service: ((document.getElementById('analytics-edit-service') || {}).value || '').trim(),
    ad_source: ((document.getElementById('analytics-edit-ad-source') || {}).value || '').trim(),
    objection_type: ((document.getElementById('analytics-edit-objection-type') || {}).value || '').trim(),
    cluster: ((document.getElementById('analytics-edit-cluster') || {}).value || '').trim(),
    severity: ((document.getElementById('analytics-edit-severity') || {}).value || '').trim(),
    quote: ((document.getElementById('analytics-edit-quote') || {}).value || '').trim(),
  };
  if (!payload.quote) {
    if (msg) { msg.textContent = 'Exact quote is required.'; msg.style.color = 'var(--red)'; msg.hidden = false; }
    return;
  }
  if (btn) { btn.disabled = true; btn.textContent = 'Saving...'; }
  if (msg) msg.hidden = true;
  try {
    const data = await postJSON('/analytics/interaction/edit', payload);
    [_analyticsRows, _analyticsFilteredRows].forEach(list => {
      const row = (list || []).find(item => Number(item.id) === Number(payload.id));
      if (row) {
        Object.assign(row, {
          customer_name: data.customer_name,
          quote: data.quote,
          objection_status: data.objection_status,
          first_contact_date: data.first_contact_date,
          objection_date: data.objection_date,
          main_contact_platform: data.main_contact_platform,
          lead_quality: data.lead_quality,
          service: data.service,
          destination: data.destination,
          ad_source: data.ad_source,
          objection_type: data.objection_type,
          cluster: data.cluster,
          severity: data.severity,
        });
      }
    });
    closeAnalyticsEditModal();
    _refreshTrackingTable();
  } catch (e) {
    if (msg) { msg.textContent = e.detail || 'Failed to save changes.'; msg.style.color = 'var(--red)'; msg.hidden = false; }
    else alert(e.detail || 'Failed to save changes.');
  } finally {
    if (btn) { btn.disabled = false; btn.textContent = 'Save Changes'; }
  }
}
*/

function _exportAnalyticsCsv() {
  const rows = _analyticsFilteredRows || _analyticsRows || [];
  if (!rows.length) return;
  const columns = [
    ['Time', 'timestamp'],
    ['Staff', 'user_name'],
    ['Customer Name', 'customer_name'],
    ['Objection Status', 'objection_status'],
    ['First Contact Date', 'first_contact_date'],
    ['Objection Date', 'objection_date'],
    ['Main Contact Platform', 'main_contact_platform'],
    ['Lead Quality', 'lead_quality'],
    ['Group', 'customer_group'],
    ['Destination', 'destination'],
    ['Service', 'service'],
    ['Ad Source', 'ad_source'],
    ['Objection Type', 'objection_type'],
    ['Cluster', 'cluster'],
    ['Severity', 'severity'],
    ['Exact Quote', 'quote'],
  ];
  const csv = [columns.map(([label]) => label).join(',')].concat(rows.map(row => columns.map(([, key]) => {
    const value = String(row[key] == null ? '' : row[key]).replace(/"/g, '""');
    return '"' + value + '"';
  }).join(','))).join('\n');
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'explorer-analytics.csv';
  document.body.appendChild(a);
  a.click();
  a.remove();
  URL.revokeObjectURL(url);
}

function toggleDeleteMode() {
  _deleteMode = !_deleteMode;
  _selectedIds.clear();
  const btn    = document.getElementById('delete-mode-btn');
  const delBtn = document.getElementById('delete-selected-btn');
  const thCheck = document.getElementById('th-check');
  if (_deleteMode) {
    if (btn) { btn.textContent = 'Cancel selection'; btn.style.color = 'var(--red)'; }
    if (delBtn) delBtn.hidden = false;
    if (thCheck) thCheck.hidden = false;
    document.querySelectorAll('[id^="td-check-"]').forEach(td => td.hidden = false);
  } else {
    if (btn) { btn.textContent = 'Select to delete'; btn.style.color = ''; }
    if (delBtn) delBtn.hidden = true;
    if (thCheck) thCheck.hidden = true;
    document.querySelectorAll('[id^="td-check-"]').forEach(td => { td.hidden = true; const cb = td.querySelector('input'); if (cb) cb.checked = false; });
  }
}

function _toggleSelectRow(id, checked) {
  checked ? _selectedIds.add(id) : _selectedIds.delete(id);
  const delBtn = document.getElementById('delete-selected-btn');
  if (delBtn) delBtn.textContent = 'Delete selected (' + _selectedIds.size + ')';
}

async function deleteSelected() {
  if (!_selectedIds.size) return;
  if (!confirm('Delete ' + _selectedIds.size + ' selected interaction(s)?')) return;
  try {
    const data = await postJSON('/analytics/delete', { ids: [..._selectedIds] });
    alert('Deleted ' + data.deleted + ' record(s).');
    _deleteMode = false; loadAnalytics();
  } catch (e) { alert(e.detail || 'Delete failed.'); }
}

async function bulkDelete() {
  const from  = (document.getElementById('bulk-from') || {}).value;
  const to    = (document.getElementById('bulk-to')   || {}).value;
  const msgEl = document.getElementById('bulk-delete-msg');
  if (msgEl) msgEl.hidden = true;
  if (!from || !to) {
    if (msgEl) { msgEl.textContent = 'Please select both dates.'; msgEl.style.color = 'var(--red)'; msgEl.hidden = false; }
    return;
  }
  if (!confirm('Delete ALL interactions from ' + from + ' to ' + to + '?')) return;
  try {
    const data = await postJSON('/analytics/delete', { date_from: from, date_to: to });
    if (msgEl) { msgEl.textContent = 'Deleted ' + data.deleted + ' record(s).'; msgEl.style.color = 'var(--green,#4caf50)'; msgEl.hidden = false; }
    loadAnalytics();
  } catch (e) {
    if (msgEl) { msgEl.textContent = e.detail || 'Delete failed.'; msgEl.style.color = 'var(--red)'; msgEl.hidden = false; }
  }
}

// =============================================================================
// ADMIN PAGE
// =============================================================================

function initAdmin() {}

function switchTab(name) {
  document.querySelectorAll('.tab-panel').forEach(el => el.classList.add('hidden'));
  document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));
  const panel = document.getElementById('tab-' + name);
  if (panel) panel.classList.remove('hidden');
  const btn = [...document.querySelectorAll('.tab-btn')]
    .find(b => b.textContent.trim().toLowerCase() === name.toLowerCase());
  if (btn) btn.classList.add('active');
}

function openEditUser(email, name, role, active) {
  document.getElementById('edit-user-email').value        = email;
  document.getElementById('edit-user-email-display').textContent = email;
  document.getElementById('edit-user-name').value         = name;
  document.getElementById('edit-user-role').value         = role;
  document.getElementById('edit-user-active').value       = active ? '1' : '0';
  document.getElementById('edit-user-password').value     = '';
  document.getElementById('edit-user-overlay').hidden     = false;
}

function closeEditUser() {
  document.getElementById('edit-user-overlay').hidden = true;
}