let mediaRecorder;
let audioChunks = [];
let timerInterval;

jQuery(document).ready(function($) {
    const recordBtn = $('#record-btn');
    const fileInput = document.getElementById('stt_audio_upload_file');
    const audioPreview = document.getElementById('audio-preview');
    const previewContainer = $('#audio-preview-container');
    const resultArea = $('#qc_voice_to_speech_stt-result');
    const rewriteBtn = $('#btn-rewrite');
    const createPostBtn = $('#create-post-btn');
    const copyBtn = $('#btn-copy');
    const timer = $('#recording-timer');
    const loader = $('#qc_voice_to_speech_stt-loader');

    recordBtn.on('click', async function() {
        if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
            alert("Microphone access is blocked. This feature requires an HTTPS connection or a modern browser.");
            return;
        }
        if (!mediaRecorder || mediaRecorder.state === 'inactive') {
            // Start Recording
            const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
            mediaRecorder = new MediaRecorder(stream);
            
            mediaRecorder.ondataavailable = (e) => audioChunks.push(e.data);
            
            mediaRecorder.onstop = () => {
                const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
                const audioUrl = URL.createObjectURL(audioBlob); // Generate preview URL
                
                // Show Preview
                audioPreview.src = audioUrl;
                previewContainer.show();
                
                // Attach file to input for processing
                const file = new File([audioBlob], "recording.wav", { type: "audio/wav" });
                const dataTransfer = new DataTransfer();
                dataTransfer.items.add(file);
                document.getElementById('stt_audio_upload_file').files = dataTransfer.files;
                
                audioChunks = [];
            };

            mediaRecorder.start();
            recordBtn.text('⏹ Stop Recording').addClass('is-recording');
            startTimer();
        } else {
            // Stop Recording
            mediaRecorder.stop();
            recordBtn.text('🔴 Start Recording').removeClass('is-recording');
            stopTimer();
        }
    });

    function startTimer() {
        let sec = 0;
        timer.show().text("00:00");
        timerInterval = setInterval(() => {
            sec++;
            let mins = Math.floor(sec / 60).toString().padStart(2, '0');
            let secs = (sec % 60).toString().padStart(2, '0');
            timer.text(`${mins}:${secs}`);
        }, 1000);
    }

    function stopTimer() {
        clearInterval(timerInterval);
    }

    // ACTION 1: Transcribe
    $('#btn-transcribe').on('click', function() {
        const fileInput = $('#stt_audio_upload_file')[0].files[0];
        const lang = $('#qc_voice_to_speech_stt-lang').val();

        if (!fileInput) return alert('Upload/Record a file first!');

        loader.addClass('is-active');

        const formData = new FormData();
        formData.append('action', 'qc_voice_to_speech_stt_transcribe_only');
        formData.append('audio_file', fileInput);
        formData.append('language', lang);
        formData.append('nonce', qc_voice_to_speech_stt_ajax.nonce);

        $('#qc_voice_to_speech_stt-status').text('Transcribing...');
        
        $.ajax({
            url: qc_voice_to_speech_stt_ajax.ajax_url,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(res) {
                if (res.success) {
                    let speakerCount = 1;
                    let formattedTranscript = "";
                    res.data.forEach((segment, index) => {
                        //formattedTranscript += `User ${speakerCount}:\n${segment.text.trim()}\n\n`;
                        formattedTranscript += `\n${segment.text.trim()}\n`;
                    });

                    showResult(formattedTranscript);
                    //$('#qc_voice_to_speech_stt-result').val(res.data);
                    loader.removeClass('is-active');
                    $('#btn-rewrite').prop('disabled', false); // Enable Rewrite button
                    $('#qc_voice_to_speech_stt-status').text('Transcription complete.');
                }
            }
        });
    });

    // ACTION 2: Rewrite
    $('#btn-rewrite').on('click', function() {
        const text = $('#qc_voice_to_speech_stt-result').val();

        if (!text) return alert('No text to rewrite!');

        loader.addClass('is-active');

        $('#qc_voice_to_speech_stt-status').text('AI is rewriting...');

        if (window.confirm("AI Rewrite is a Pro feature.")) {
            $('#qc_voice_to_speech_stt-status').text('');
            loader.removeClass('is-active');
        }

        loader.removeClass('is-active');

    });


    // Function to show copy button when result is populated
    function showResult(text) {
        resultArea.val(text);
        copyBtn.fadeIn(); // Show button when result arrives
        createPostBtn.fadeIn(); // Show button when result arrives
    }

    // Logic for Copy Button
    copyBtn.on('click', function() {
        const textToCopy = resultArea.val();
        
        if (!navigator.clipboard) {
            alert("Clipboard API not supported. Please use HTTPS.");
            return;
        }

        navigator.clipboard.writeText(textToCopy).then(() => {
            // Visual Feedback
            const originalText = copyBtn.html();
            copyBtn.addClass('copied').html('✅ Copied!');
            
            setTimeout(() => {
                copyBtn.removeClass('copied').html(originalText);
            }, 2000);
        }).catch(err => {
            console.error('Failed to copy: ', err);
        });
    });


    $('#create-post-btn').on('click', function() {
        const postContent = $('#qc_voice_to_speech_stt-result').val();

        if (window.confirm("AI Create WP Post is a Pro feature.")) {
            $('#qc_voice_to_speech_stt-status').text('');
            loader.removeClass('is-active');
        }

        loader.removeClass('is-active');
        
    });

    $('#btn-reset-recording').on('click', function() {
        if (!confirm("Are you sure you want to delete this recording and start over?")) return;

        // 1. Clear Audio Preview & File Input
        audioPreview.src = "";
        fileInput.value = ""; // Clears the file from the hidden input
        previewContainer.fadeOut();

        // 2. Clear Results & Status
        $('#qc_voice_to_speech_stt-status').text("Recording cleared. Ready for new input.");
        
        // 3. Reset Buttons & UI States
        rewriteBtn.prop('disabled', true);
        createPostBtn.hide();
        copyBtn.hide();
        timer.hide().text("00:00");

        // 4. Revoke the Blob URL to free up memory (Standard 2025 memory management)
        if (audioPreview.src.startsWith('blob:')) {
            URL.revokeObjectURL(audioPreview.src);
        }
    });

    


    $('.qc_voice_to_speech_stt-list li, .qc_voice_to_speech_stt-header').on('click', function() {
        const targetTab = $(this).attr('data-tab');

        // Reset all active states
        $('.qc_voice_to_speech_stt-list li, .qc_voice_to_speech_stt-header, .qc_voice_to_speech_stt-content').removeClass('active');

        // Set active state for clicked item and its content
        $('[data-tab="' + targetTab + '"]').addClass('active');
        $('#' + targetTab).addClass('active');
    });


});
