File size: 36,567 Bytes
2ae57cb
 
81341b4
2ae57cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22b00f2
 
 
 
 
 
 
 
 
2ae57cb
 
 
 
 
81341b4
2ae57cb
 
 
 
 
 
 
81341b4
 
 
 
 
 
 
 
 
2ae57cb
 
 
 
 
 
 
81341b4
2ae57cb
 
 
 
 
 
 
81341b4
 
 
 
 
 
 
 
 
2ae57cb
 
 
81341b4
 
 
2ae57cb
 
 
 
 
 
 
 
 
 
 
 
 
 
81341b4
 
2ae57cb
 
 
 
 
 
 
 
 
 
 
 
 
81341b4
2ae57cb
 
 
 
49fbb3a
2ae57cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81341b4
 
2ae57cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22b00f2
 
2ae57cb
 
 
 
 
 
 
 
 
 
22b00f2
2ae57cb
 
 
49fbb3a
 
 
 
 
cb47676
49fbb3a
 
 
 
 
 
 
2ae57cb
 
 
308d699
2ae57cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
308d699
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81341b4
308d699
2ae57cb
 
 
 
81341b4
2ae57cb
 
 
 
 
 
 
81341b4
2ae57cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
308d699
2ae57cb
 
 
 
 
 
 
 
22b00f2
308d699
 
22b00f2
 
 
44441db
308d699
 
44441db
 
 
2ae57cb
22b00f2
308d699
 
44441db
 
2ae57cb
 
308d699
2ae57cb
 
 
 
 
 
 
 
 
 
 
 
 
 
308d699
 
 
 
 
2ae57cb
 
 
 
 
 
 
 
308d699
2ae57cb
 
308d699
2ae57cb
 
 
 
 
308d699
 
 
 
2ae57cb
308d699
 
2ae57cb
 
308d699
2ae57cb
 
 
 
 
 
 
81341b4
308d699
2ae57cb
 
 
 
 
308d699
2ae57cb
 
308d699
 
 
 
 
 
 
 
5cee863
308d699
 
 
 
 
 
 
 
 
 
 
 
 
 
1f41a8a
 
 
 
2ae57cb
 
 
308d699
 
 
 
2ae57cb
 
 
308d699
 
2ae57cb
308d699
 
 
 
 
2ae57cb
 
 
308d699
2ae57cb
 
 
 
 
 
81341b4
2ae57cb
 
 
308d699
2ae57cb
 
 
 
 
 
308d699
2ae57cb
 
 
 
 
 
 
308d699
2ae57cb
 
 
 
308d699
 
 
 
 
 
 
 
 
1f41a8a
8255e28
 
 
 
 
 
1f41a8a
330157f
308d699
 
 
 
 
 
 
 
8255e28
 
308d699
 
227e456
2ae57cb
 
 
 
22b00f2
308d699
 
22b00f2
 
 
2ae57cb
308d699
81341b4
22b00f2
 
308d699
22b00f2
 
 
 
2ae57cb
 
 
 
308d699
2ae57cb
22b00f2
308d699
2ae57cb
81341b4
2ae57cb
 
 
308d699
2ae57cb
 
 
 
 
 
 
 
308d699
2ae57cb
 
a1b807c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e2c190
a1b807c
 
 
 
 
 
 
 
 
 
 
 
 
 
e83166d
 
 
a1b807c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ae57cb
 
 
 
 
308d699
 
 
 
2ae57cb
 
 
 
 
 
 
 
 
308d699
2ae57cb
 
 
22b00f2
2ae57cb
 
 
 
 
 
81341b4
2ae57cb
308d699
 
 
 
 
 
 
 
2ae57cb
 
 
22b00f2
2ae57cb
 
 
 
 
 
308d699
 
22b00f2
 
 
 
81341b4
22b00f2
 
81341b4
22b00f2
 
 
 
 
 
81341b4
22b00f2
2ae57cb
 
81341b4
2ae57cb
 
 
 
 
 
 
 
308d699
2ae57cb
 
 
 
81341b4
2ae57cb
 
22b00f2
2ae57cb
 
 
 
 
 
 
 
 
 
81341b4
2ae57cb
 
 
 
 
 
81341b4
2ae57cb
 
 
 
 
 
 
 
 
 
 
81341b4
 
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
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Interview - Interactive Session</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .interview-container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 800px;
            min-height: 600px;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .header {
            background: linear-gradient(45deg, #4CAF50, #45a049);
            color: white;
            padding: 20px;
            text-align: center;
            position: relative;
        }

        .header h1 {
            font-size: 1.8rem;
            margin-bottom: 5px;
        }

        .header p {
            opacity: 0.9;
            font-size: 0.9rem;
        }

        .chat-area {
            flex: 1;
            padding: 20px;
            display: flex;
            flex-direction: column;
            gap: 20px;
            max-height: 400px;
            overflow-y: auto;
        }

        .ai-message {
            display: flex;
            align-items: flex-start;
            gap: 15px;
            animation: slideIn 0.5s ease-out;
        }

        .ai-avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: linear-gradient(45deg, #667eea, #764ba2);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 1.2rem;
            position: relative;
            flex-shrink: 0;
        }

        .ai-avatar.talking {
            animation: pulse 1.5s infinite;
        }

        .ai-avatar.talking::before {
            content: '';
            position: absolute;
            width: 100%;
            height: 100%;
            border-radius: 50%;
            background: rgba(102, 126, 234, 0.3);
            animation: ripple 1.5s infinite;
        }

        .message-bubble {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 15px 20px;
            max-width: 70%;
            position: relative;
        }

        .message-bubble::before {
            content: '';
            position: absolute;
            left: -10px;
            top: 15px;
            width: 0;
            height: 0;
            border-top: 10px solid transparent;
            border-bottom: 10px solid transparent;
            border-right: 10px solid #f8f9fa;
        }

        .user-message {
            display: flex;
            justify-content: flex-end;
            animation: slideIn 0.5s ease-out;
        }

        .user-bubble {
            background: linear-gradient(45deg, #4CAF50, #45a049);
            color: white;
            border-radius: 15px;
            padding: 15px 20px;
            max-width: 70%;
            position: relative;
        }

        .user-bubble::before {
            content: '';
            position: absolute;
            right: -10px;
            top: 15px;
            width: 0;
            height: 0;
            border-top: 10px solid transparent;
            border-bottom: 10px solid transparent;
            border-left: 10px solid #4CAF50;
        }

        .controls-area {
            background: #f8f9fa;
            padding: 20px;
            border-top: 1px solid #e9ecef;
        }

        .recording-section {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .mic-container {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 20px;
        }

        .mic-button {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            border: none;
            background: linear-gradient(45deg, #ff6b6b, #ee5a52);
            color: white;
            font-size: 1.8rem;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
        }

        .mic-button:hover {
            transform: scale(1.05);
            box-shadow: 0 8px 25px rgba(255, 107, 107, 0.3);
        }

        .mic-button.recording {
            background: linear-gradient(45deg, #ff4757, #ff3742);
            animation: recordPulse 1s infinite;
        }

        .mic-button.recording::before {
            content: '';
            position: absolute;
            width: 100%;
            height: 100%;
            border-radius: 50%;
            background: rgba(255, 71, 87, 0.3);
            animation: ripple 1s infinite;
        }

        .recording-status {
            font-size: 0.9rem;
            color: #666;
            text-align: center;
        }

        .transcript-area {
            background: white;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 15px;
            font-size: 0.9rem;
            color: #333;
            min-height: 60px;
            max-height: 120px;
            overflow-y: auto;
            transition: border-color 0.3s ease;
        }

        .transcript-area:focus {
            outline: none;
            border-color: #4CAF50;
        }

        .action-buttons {
            display: flex;
            gap: 10px;
            justify-content: center;
            margin-top: 15px;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: linear-gradient(45deg, #4CAF50, #45a049);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(76, 175, 80, 0.3);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #545b62;
            transform: translateY(-2px);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .question-counter {
            position: absolute;
            top: 15px;
            right: 20px;
            background: rgba(255, 255, 255, 0.2);
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
        }

        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
        }

        .summary-panel {
            display: none;
            background: white;
            border-radius: 15px;
            padding: 30px;
            margin: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
        }

        .summary-panel h2 {
            color: #333;
            margin-bottom: 20px;
            text-align: center;
        }

        .summary-item {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            border-left: 4px solid #4CAF50;
        }

        .summary-item h4 {
            color: #333;
            margin-bottom: 8px;
        }

        .summary-item p {
            color: #666;
            margin-bottom: 5px;
            line-height: 1.4;
        }

        .evaluation-score {
            display: inline-block;
            background: #4CAF50;
            color: white;
            padding: 4px 8px;
            border-radius: 15px;
            font-size: 0.8rem;
            font-weight: bold;
        }

        .error-message {
            background: #ff4757;
            color: white;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
            text-align: center;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes pulse {

            0%,
            100% {
                transform: scale(1);
            }

            50% {
                transform: scale(1.1);
            }
        }

        @keyframes ripple {
            0% {
                transform: scale(1);
                opacity: 1;
            }

            100% {
                transform: scale(1.4);
                opacity: 0;
            }
        }

        @keyframes recordPulse {

            0%,
            100% {
                transform: scale(1);
            }

            50% {
                transform: scale(1.05);
            }
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        @media (max-width: 768px) {
            .interview-container {
                margin: 10px;
                min-height: 90vh;
            }

            .mic-button {
                width: 70px;
                height: 70px;
                font-size: 1.5rem;
            }

            .message-bubble,
            .user-bubble {
                max-width: 85%;
            }

            .header h1 {
                font-size: 1.5rem;
            }
        }

        audio {
            display: none;
        }
    </style>
</head>

<body>
    <div class="interview-container">
        <div class="header">
            <div class="question-counter">
                Question <span id="currentQuestionNum">1</span> of <span id="totalQuestions">{{ job.num_questions }}</span>
            </div>
            <h1>🤖 AI Interview Assistant</h1>
            <p>Answer thoughtfully and take your time</p>
        </div>

        <div class="chat-area" id="chatArea">
            <div class="ai-message">
                <div class="ai-avatar" id="aiAvatar">AI</div>
                <div class="message-bubble">
                    <div id="loadingMessage">
                        <div class="loading"></div>
                        <span style="margin-left: 10px;">Generating your first question...</span>
                    </div>
                </div>
            </div>
        </div>

        <div class="controls-area">
            <div class="recording-section">
                <div class="mic-container">
                    <button class="mic-button" id="micButton" disabled>
                        <span id="micIcon">🎤</span>
                    </button>
                </div>
                <div class="recording-status" id="recordingStatus">
                    Click the microphone to record your answer
                </div>
                <div class="transcript-area" id="transcriptArea" contenteditable="true"
                    placeholder="Your transcribed answer will appear here..."></div>
                <div class="action-buttons">
                    <button class="btn btn-primary" id="confirmButton" disabled>
                        <span>Confirm Answer</span>
                        <span id="confirmLoading" style="display: none;">
                            <div class="loading" style="width: 16px; height: 16px; border-width: 2px;"></div>
                        </span>
                    </button>
                    <button class="btn btn-secondary" id="retryRecording" style="display: none;">
                        🔄 Re-record
                    </button>
                </div>
            </div>
        </div>

        <!-- Summary Panel (hidden initially) -->
        <div class="summary-panel" id="summaryPanel">
            <h2>📋 Interview Summary</h2>
            <div id="summaryContent"></div>
            <div style="text-align: center; margin-top: 30px;">
                <button class="btn btn-primary" onclick="window.location.href='/jobs'">
                    Back to Jobs
                </button>
            </div>
        </div>
    </div>

    <!-- Hidden audio element for TTS playback -->
    <audio id="ttsAudio" preload="auto"></audio>

    <script>
        const JOB_ID = {{ job.id }};

        class AIInterviewer {
            constructor() {
                this.currentQuestionIndex = 0;
                // Set the total number of questions based on the job configuration.
                // The value is read from the DOM element #totalQuestions, which
                // has been populated server‑side using ``job.num_questions``.
                const totalSpan = document.getElementById('totalQuestions');
                const parsedTotal = parseInt(totalSpan && totalSpan.textContent);
                this.totalQuestions = Number.isNaN(parsedTotal) || parsedTotal <= 0 ? 4 : parsedTotal;
                // Ensure the counter display shows the correct total number of
                // questions.  Without this update the span would retain the
                // server‑rendered value even if the fallback above changed
                // ``this.totalQuestions``.
                if (totalSpan) {
                    totalSpan.textContent = this.totalQuestions;
                }
                this.isRecording = false;
                this.mediaRecorder = null;
                this.audioChunks = [];
                this.currentQuestion = "";
                this.interviewData = {
                    questions: [],
                    answers: [],
                    evaluations: []
                };
                this.initializeElements();
                this.initializeInterview();
            }

            initializeElements() {
                this.chatArea = document.getElementById('chatArea');
                this.micButton = document.getElementById('micButton');
                this.micIcon = document.getElementById('micIcon');
                this.recordingStatus = document.getElementById('recordingStatus');
                this.transcriptArea = document.getElementById('transcriptArea');
                this.confirmButton = document.getElementById('confirmButton');
                this.confirmLoading = document.getElementById('confirmLoading');
                this.retryButton = document.getElementById('retryRecording');
                this.aiAvatar = document.getElementById('aiAvatar');
                this.ttsAudio = document.getElementById('ttsAudio');
                this.summaryPanel = document.getElementById('summaryPanel');
                this.currentQuestionNum = document.getElementById('currentQuestionNum');
                this.totalQuestionsSpan = document.getElementById('totalQuestions');
                this.bindEvents();
            }

            bindEvents() {
                // Mouse events for desktop
                this.micButton.addEventListener('mousedown', (e) => {
                    e.preventDefault();
                    this.startRecording();
                });

                this.micButton.addEventListener('mouseup', (e) => {
                    e.preventDefault();
                    this.stopRecording();
                });

                this.micButton.addEventListener('mouseleave', (e) => {
                    e.preventDefault();
                    this.stopRecording();
                });

                // Touch events for mobile
                this.micButton.addEventListener('touchstart', (e) => {
                    e.preventDefault();
                    this.startRecording();
                });

                this.micButton.addEventListener('touchend', (e) => {
                    e.preventDefault();
                    this.stopRecording();
                });

                this.confirmButton.addEventListener('click', () => this.submitAnswer());
                this.retryButton.addEventListener('click', () => this.resetRecording());

                this.transcriptArea.addEventListener('input', () => {
                    const hasText = this.transcriptArea.textContent.trim().length > 0;
                    this.confirmButton.disabled = !hasText;
                });

                this.ttsAudio.addEventListener('play', () => {
                    this.aiAvatar.classList.add('talking');
                });

                this.ttsAudio.addEventListener('ended', () => {
                    this.aiAvatar.classList.remove('talking');
                    this.enableControls();
                });

                this.ttsAudio.addEventListener('error', (e) => {
                    console.error('Audio playback error:', e);
                    this.aiAvatar.classList.remove('talking');
                    this.enableControls();
                });
            }

            async initializeInterview() {
                try {
                    console.log('Starting interview...');
                    const response = await fetch('/api/start_interview', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ job_id: JOB_ID })
                    });

                    if (!response.ok) {
                        const errorText = await response.text();
                        console.error('Server response:', response.status, errorText);
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }

                    const data = await response.json();
                    console.log('Received interview data:', data);

                    if (data.error) {
                        this.showError(data.error);
                        return;
                    }

                    // Store the current question for evaluation
                    this.currentQuestion = data.question;
                    this.displayQuestion(data.question, data.audio_url);
                    this.interviewData.questions.push(data.question);
                } catch (error) {
                    console.error('Error starting interview:', error);
                    this.showError('Failed to start interview. Please check your connection and try again.');
                }
            }

            displayQuestion(question, audioUrl = null) {
                // Remove loading message
                const loadingMsg = document.getElementById('loadingMessage');
                if (loadingMsg) {
                    loadingMsg.remove();
                }

                // Create question message
                const messageDiv = document.createElement('div');
                messageDiv.className = 'ai-message';
                messageDiv.innerHTML = `
            <div class="ai-avatar">AI</div>
            <div class="message-bubble">
                <p>${question}</p>
            </div>
        `;
                this.chatArea.appendChild(messageDiv);
                this.chatArea.scrollTop = this.chatArea.scrollHeight;

                // Update question counter
                this.currentQuestionNum.textContent = this.currentQuestionIndex + 1;

                // Play audio if available
                if (audioUrl) {
                    console.log('Playing audio:', audioUrl);
                    this.playQuestionAudio(audioUrl);
                } else {
                    console.log('No audio URL provided, enabling controls');
                    setTimeout(() => this.enableControls(), 1000);
                }
            }

            playQuestionAudio(audioUrl) {
                // Add talking animation immediately
                const avatars = this.chatArea.querySelectorAll('.ai-avatar');
                avatars.forEach(avatar => avatar.classList.add('talking'));

                this.ttsAudio.src = audioUrl;
                this.ttsAudio.load(); // Ensure audio is loaded

                this.ttsAudio.play().catch(error => {
                    console.error('Audio play error:', error);
                    avatars.forEach(avatar => avatar.classList.remove('talking'));
                    this.enableControls();
                });
            }

            enableControls() {
                this.micButton.disabled = false;
                this.recordingStatus.textContent = 'Click and hold to record your answer';

                // Remove talking animation from all avatars
                const avatars = this.chatArea.querySelectorAll('.ai-avatar');
                avatars.forEach(avatar => avatar.classList.remove('talking'));
            }

            async startRecording() {
                if (this.isRecording || this.micButton.disabled) return;

                try {
                    console.log('Starting recording...');
                    const stream = await navigator.mediaDevices.getUserMedia({
                        audio: {
                            echoCancellation: true,
                            noiseSuppression: true,
                            autoGainControl: true,
                            sampleRate: 16000
                        }
                    });

                    // Use webm format with opus codec for better compatibility
                    const options = {
                        mimeType: 'audio/webm;codecs=opus'
                    };

                    // Fallback for browsers that don't support webm
                    if (!MediaRecorder.isTypeSupported(options.mimeType)) {
                        options.mimeType = 'audio/webm';
                    }
                    if (!MediaRecorder.isTypeSupported(options.mimeType)) {
                        delete options.mimeType;
                    }

                    this.mediaRecorder = new MediaRecorder(stream, {
                        mimeType: 'audio/webm;codecs=opus'
                    });

                    this.audioChunks = [];

                    this.mediaRecorder.ondataavailable = (event) => {
                        if (event.data.size > 0) {
                            this.audioChunks.push(event.data);
                            console.log('Audio chunk received:', event.data.size, 'bytes');
                        }
                    };

                    this.mediaRecorder.onstop = () => {
                        console.log('Recording stopped, processing...');
                        stream.getTracks().forEach(track => track.stop());
                        this.processRecording();
                    };

                    this.mediaRecorder.onerror = (event) => {
                        console.error('MediaRecorder error:', event.error);
                        this.recordingStatus.textContent = 'Recording error. Please try again.';
                        stream.getTracks().forEach(track => track.stop());
                    };

                    this.mediaRecorder.start(1000); // Collect data every second
                    this.isRecording = true;

                    // Update UI
                    this.micButton.classList.add('recording');
                    this.micIcon.textContent = '🔴';
                    this.recordingStatus.textContent = 'Recording... Release to stop';

                } catch (error) {
                    console.error('Error starting recording:', error);
                    this.recordingStatus.textContent = 'Microphone access denied. Please allow microphone access and try again.';
                    this.recordingStatus.style.color = '#ff4757';
                }
            }

            stopRecording() {
                if (!this.isRecording || !this.mediaRecorder) return;

                console.log('Stopping recording...');
                this.mediaRecorder.stop();
                this.isRecording = false;

                // Update UI
                this.micButton.classList.remove('recording');
                this.micIcon.textContent = '🎤';
                this.recordingStatus.textContent = 'Processing audio...';
                this.recordingStatus.style.color = '#666';
            }

            async processRecording() {
                try {
                    if (this.audioChunks.length === 0) {
                        console.error('No audio chunks recorded');
                        this.recordingStatus.textContent = 'No audio recorded. Please try again.';
                        return;
                    }

                    console.log('Processing', this.audioChunks.length, 'audio chunks');

                    // Create blob from audio chunks
                    const audioBlob = new Blob(this.audioChunks, { type: 'audio/webm' });

                    // Initialise a new FormData instance AFTER creating the blob
                    // and append the audio. Previously a call to `formData.append` was
                    // made before the variable was declared, causing a reference
                    // error and triggering the generic "Error processing audio" message.
                    const formData = new FormData();
                    formData.append('audio', audioBlob, 'recording.webm');

                    console.log('Created audio blob:', audioBlob.size, 'bytes');

                    if (audioBlob.size === 0) {
                        console.error('Audio blob is empty');
                        this.recordingStatus.textContent = 'No audio data captured. Please try again.';
                        return;
                    }

                    // formData has already been created and the audio appended above.
                    // Do not recreate or re-append here.

                    console.log('Sending audio for transcription...');
                    const response = await fetch('/api/transcribe_audio', {
                        method: 'POST',
                        body: formData
                    });

                    if (!response.ok) {
                        const errorText = await response.text();
                        console.error('Transcription error:', response.status, errorText);
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }

                    const data = await response.json();
                    console.log('Transcription response:', data);

                    if (data.error) {
                        this.recordingStatus.textContent = data.error;
                        this.recordingStatus.style.color = '#ff4757';
                        return;
                    }

                    if (data.transcript && data.transcript.trim()) {
                        this.transcriptArea.textContent = data.transcript;
                        this.confirmButton.disabled = false;
                        this.retryButton.style.display = 'inline-flex';
                        this.recordingStatus.textContent = 'Transcription complete. Review and confirm your answer.';
                        this.recordingStatus.style.color = '#4CAF50';
                    } else {
                        this.recordingStatus.textContent = 'No speech detected. Please try recording again.';
                        this.recordingStatus.style.color = '#ff4757';
                    }

                } catch (error) {
                    console.error('Error processing recording:', error);
                    this.recordingStatus.textContent = 'Error processing audio. Please try again.';
                    this.recordingStatus.style.color = '#ff4757';
                }
            }

            resetRecording() {
                this.transcriptArea.textContent = '';
                this.confirmButton.disabled = true;
                this.retryButton.style.display = 'none';
                this.recordingStatus.textContent = 'Click and hold to record your answer';
                this.recordingStatus.style.color = '#666';
            }

            async submitAnswer() {
                const answer = this.transcriptArea.textContent.trim();
                if (!answer) return;

                console.log('Submitting answer:', answer);

                // Show loading state
                this.confirmButton.disabled = true;
                this.confirmLoading.style.display = 'inline-block';
                this.confirmButton.querySelector('span').style.display = 'none';

                // Add user message to chat
                this.addUserMessage(answer);

                try {
                    const response = await fetch('/api/process_answer', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            answer: answer,
                            questionIndex: this.currentQuestionIndex,
                            current_question: this.currentQuestion,
                            job_id: JOB_ID
                        })
                    });

                    if (!response.ok) {
                        const errorText = await response.text();
                        console.error('Process answer error:', response.status, errorText);
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }

                    const data = await response.json();
                    console.log('Process answer response:', data);

                    if (!data.success) {
                        this.showError(data.error || 'Failed to process answer. Please try again.');
                        return;
                    }

                    // Record the user's answer and its evaluation
                    this.interviewData.answers.push(answer);
                    this.interviewData.evaluations.push(data.evaluation || {});

                    if (data.is_complete) {
                        console.log('Interview completed');
                        if (data.redirect_url) {
                            window.location.href = data.redirect_url;
                        }
                        this.showInterviewSummary();
                    } else {
                        console.log('Moving to next question');
                        this.currentQuestionIndex++;
                        this.currentQuestion = data.next_question;
                        this.displayQuestion(data.next_question, data.audio_url);
                        this.interviewData.questions.push(data.next_question);
                        this.resetForNextQuestion();
                    }
                } catch (error) {
                    console.error('Error submitting answer:', error);
                    this.showError('Connection error. Please try again.');
                } finally {
                    // Reset button state
                    this.confirmLoading.style.display = 'none';
                    this.confirmButton.querySelector('span').style.display = 'inline';
                }
            }

            addUserMessage(message) {
                const messageDiv = document.createElement('div');
                messageDiv.className = 'user-message';
                messageDiv.innerHTML = `
            <div class="user-bubble">
                <p>${message}</p>
            </div>
        `;
                this.chatArea.appendChild(messageDiv);
                this.chatArea.scrollTop = this.chatArea.scrollHeight;
            }

            resetForNextQuestion() {
                this.transcriptArea.textContent = '';
                this.confirmButton.disabled = true;
                this.retryButton.style.display = 'none';
                this.recordingStatus.textContent = 'Wait for the next question...';
                this.recordingStatus.style.color = '#666';
                this.micButton.disabled = true;
            }

            showInterviewSummary() {
                const summaryContent = document.getElementById('summaryContent');
                let summaryHtml = '';

                this.interviewData.questions.forEach((question, index) => {
                    const answer = this.interviewData.answers[index] || 'No answer provided';
                    const evaluation = this.interviewData.evaluations[index] || {};

                    summaryHtml += `
                <div class="summary-item">
                    <h4>Question ${index + 1}:</h4>
                    <p><strong>Q:</strong> ${question}</p>
                    <p><strong>A:</strong> ${answer}</p>
                    <p><strong>Score:</strong> <span class="evaluation-score">${evaluation.score || 'N/A'}</span></p>
                    <p><strong>Feedback:</strong> ${evaluation.feedback || 'No feedback provided'}</p>
                </div>
            `;
                });

                summaryContent.innerHTML = summaryHtml;

                // Hide main interface and show summary
                document.querySelector('.interview-container').style.display = 'none';
                this.summaryPanel.style.display = 'block';
            }

            showError(message) {
                console.error('Showing error:', message);

                // Create error message element
                const errorDiv = document.createElement('div');
                errorDiv.className = 'error-message';
                errorDiv.textContent = message;

                // Insert at the top of chat area
                this.chatArea.insertBefore(errorDiv, this.chatArea.firstChild);

                // Remove after 5 seconds
                setTimeout(() => {
                    if (errorDiv.parentNode) {
                        errorDiv.parentNode.removeChild(errorDiv);
                    }
                }, 5000);

                // Also update recording status
                this.recordingStatus.textContent = message;
                this.recordingStatus.style.color = '#ff4757';

                setTimeout(() => {
                    this.recordingStatus.style.color = '#666';
                }, 3000);
            }
        }

        // Initialize the interview when page loads
        document.addEventListener('DOMContentLoaded', () => {
            console.log('DOM loaded, initializing AI Interviewer...');
            new AIInterviewer();
        });

        // Add placeholder attribute support for contenteditable
        document.addEventListener('DOMContentLoaded', function () {
            const transcriptArea = document.getElementById('transcriptArea');
            const placeholder = transcriptArea.getAttribute('placeholder');

            function checkPlaceholder() {
                if (transcriptArea.textContent.trim() === '') {
                    transcriptArea.style.color = '#999';
                    transcriptArea.textContent = placeholder;
                } else if (transcriptArea.textContent === placeholder) {
                    transcriptArea.style.color = '#333';
                    transcriptArea.textContent = '';
                }
            }

            transcriptArea.addEventListener('focus', function () {
                if (transcriptArea.textContent === placeholder) {
                    transcriptArea.textContent = '';
                    transcriptArea.style.color = '#333';
                }
            });

            transcriptArea.addEventListener('blur', function () {
                if (transcriptArea.textContent.trim() === '') {
                    transcriptArea.style.color = '#999';
                    transcriptArea.textContent = placeholder;
                }
            });

            // Initial check
            checkPlaceholder();
        });
    </script>
</body>

</html>