jQuery(document).ready(function($) {
    var mediaRecorder;
    var audioChunks = [];

    // Initialize each test container
    $('.vmwpmdp-stt-test-container').each(function() {
        var $container = $(this);
        var sessionId = 'sess_' + Date.now() + '_' + Math.floor(Math.random() * 1000);
        $container.data('session-id', sessionId);
    });

    // Recording logic
    $(document).on('click', '.vmwpmdp-stt-test-record-btn', function() {
        var $btn = $(this);
        var $container = $btn.closest('.vmwpmdp-test-level-item');
        var $mainContainer = $btn.closest('.vmwpmdp-stt-test-container');
        var levelIndex = $btn.data('level-index');

        if ($btn.hasClass('recording')) {
            stopRecording($btn, $container, levelIndex, $mainContainer);
        } else {
            startRecording($btn, $container);
        }
    });

    var recognition;
    var finalTranscript = '';

    if (qcld_stt_test_obj.stt_type === 'speechrecognition') {
        var SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
        if (SpeechRecognition) {
            recognition = new SpeechRecognition();
            recognition.lang = qcld_stt_test_obj.lang_code;
            recognition.interimResults = true;
            recognition.continuous = true;

            recognition.onresult = function(event) {
                var interimTranscript = '';
                for (var i = event.resultIndex; i < event.results.length; ++i) {
                    if (event.results[i].isFinal) {
                        finalTranscript += event.results[i][0].transcript;
                    } else {
                        interimTranscript += event.results[i][0].transcript;
                    }
                }
                // Optional: Update UI with interim transcript if needed
            };

            recognition.onerror = function(event) {
                console.error('Speech recognition error:', event.error);
            };
        }
    }

    function startRecording($btn, $container) {
        navigator.mediaDevices.getUserMedia({ audio: true })
            .then(stream => {
                mediaRecorder = new MediaRecorder(stream);
                mediaRecorder.start();
                audioChunks = [];

                mediaRecorder.addEventListener("dataavailable", event => {
                    audioChunks.push(event.data);
                });

                if (recognition) {
                    finalTranscript = '';
                    recognition.start();
                }

                $btn.addClass('recording').find('.vmwpmdp-btn-text').text(qcld_stt_test_obj.stop_text);
                $container.find('.vmwpmdp-stt-test-status').show().text(qcld_stt_test_obj.recording_text);
            })
            .catch(err => {
                console.error("Error accessing microphone:", err);
                alert("Could not access microphone. Please ensure you have granted permission.");
            });
    }

    function stopRecording($btn, $container, levelIndex, $mainContainer) {
        mediaRecorder.stop();
        $btn.removeClass('recording').find('.vmwpmdp-btn-text').text(qcld_stt_test_obj.start_text);
        $container.find('.vmwpmdp-stt-test-status').text('Record Saved.').css('color', '#666');

        if (recognition) {
            recognition.stop();
        }

        mediaRecorder.addEventListener("stop", () => {
            const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
            
            // Store blob and transcript on the container to upload later
            $container.data('audio-blob', audioBlob);
            if (recognition) {
                $container.data('transcription', finalTranscript);
            }
            $container.attr('data-recorded', 'true');
            $container.find('.vmwpmdp-completion-status span').text('Recorded ✅').css('color', 'green');
        }, { once: true }); 
    }

    function uploadAudioPromise(blob, $container, levelIndex, $mainContainer) {
        return new Promise(function(resolve, reject) {
            var formData = new FormData();
            var postId = $mainContainer.data('post-id');
            var sessionId = $mainContainer.data('session-id');
            var studentName = $mainContainer.find('.vmwpmdp-student-name').val();
            var studentEmail = $mainContainer.find('.vmwpmdp-student-email').val();

            formData.append('action', 'wpvoicemessage_sff_learning_mode_test_send');
            formData.append('nonce', qcld_stt_test_obj.nonce);
            formData.append('audio_data', blob, 'test_audio.wav');
            formData.append('cform-id', postId);
            formData.append('level_index', levelIndex);
            formData.append('session_id', sessionId);
            formData.append('student_name', studentName);
            formData.append('student_email', studentEmail);

            $container.find('.vmwpmdp-stt-test-status').show().text('Uploading...').css('color', '#666');

            $.ajax({
                url: qcld_stt_test_obj.ajax_url,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        var audioId = response.data.post_id;
                        var transcription = $container.data('transcription') || '';
                        evaluateTestPromise(audioId, levelIndex, postId, $container, transcription).then(resolve).catch(reject);
                    } else {
                        reject('Upload failed: ' + response.data);
                    }
                },
                error: function(err) {
                    reject(err);
                }
            });
        });
    }

    function evaluateTestPromise(audioId, levelIndex, postId, $container, transcription) {
        return new Promise(function(resolve, reject) {
            $container.find('.vmwpmdp-stt-test-status').show().text(qcld_stt_test_obj.processing_text);
            $.post(qcld_stt_test_obj.ajax_url, {
                action: 'qcld_stt_test_evaluation',
                nonce: qcld_stt_test_obj.nonce,
                post_id: postId,
                level_index: levelIndex,
                audio_id: audioId,
                transcription: transcription
            }, function(response) {
                $container.find('.vmwpmdp-stt-test-status').hide();
                if (response.success) {
                    $container.attr('data-audio-id', audioId);
                    
                    var $resultDiv = $container.find('.vmwpmdp-stt-test-result');
                    var $details = $resultDiv.find('.vmwpmdp-result-details');
                    
                    $details.html('<strong>Transcription:</strong> ' + response.data.transcription);
                    $resultDiv.css('display', 'flex').hide().fadeIn();
                    resolve(response);
                } else {
                    reject('Evaluation error: ' + response.data);
                }
            }).fail(function(err) {
                reject(err);
            });
        });
    }

    $(document).on('click', '.vmwpmdp-submit-full-test', function() {
        var $btn = $(this);
        var $mainContainer = $btn.closest('.vmwpmdp-stt-test-container');
        var name = $mainContainer.find('.vmwpmdp-student-name').val();
        var email = $mainContainer.find('.vmwpmdp-student-email').val();
        var $msg = $mainContainer.find('.vmwpmdp-final-msg');

        if (!name || !email) {
            alert('Please enter your name and email before submitting.');
            return;
        }

        var $testItems = $mainContainer.find('.vmwpmdp-test-level-item');
        var totalLevels = $testItems.length;
        var recordedLevels = $mainContainer.find('.vmwpmdp-test-level-item[data-recorded="true"]').length;

        if (recordedLevels < totalLevels) {
            if (!confirm('You have not recorded all sentences in this test. Submit anyway?')) {
                return;
            }
        }

        $btn.prop('disabled', true).text('Submitting...');
        $msg.show().text('Processing your test results...').css('color', '#666');
        
        var uploadPromises = [];
        
        $testItems.each(function() {
            var $item = $(this);
            if ($item.attr('data-recorded') === 'true' && !$item.attr('data-audio-id')) {
                var audioBlob = $item.data('audio-blob');
                var levelIndex = $item.find('.vmwpmdp-stt-test-record-btn').data('level-index');
                var p = uploadAudioPromise(audioBlob, $item, levelIndex, $mainContainer);
                uploadPromises.push(p);
            }
        });

        if (uploadPromises.length === 0) {
            alert('No new recordings found to submit.');
            $btn.prop('disabled', false).text('Submit Test');
            $msg.hide();
            return;
        }

        Promise.all(uploadPromises).then(function() {
            $msg.html('Test submitted successfully! Thank you. <button class="button vmwpmdp-refresh-test-btn" onclick="location.reload();" style="margin-left: 20px; vertical-align: middle;">Refresh</button>').css('color', 'green');
            $btn.hide();
            $mainContainer.find('.vmwpmdp-stt-test-record-btn').prop('disabled', true);
        }).catch(function(err) {
            $msg.text('Error submitting test. Please try again.').css('color', 'red');
            $btn.prop('disabled', false).text('Submit Test');
            console.error('Test upload error:', err);
        });
    });

});
