{% extends "base.html" %}

{% block title %}{{ page_title }}{% endblock %}

{% block extra_styles %}{% endblock %}

{% block content %}
<div class="voice-enhanced-page py-3">
  <div class="card mc-panel">
    <div class="card-header mc-panel-header" style="text-align:center;">// ENHANCED VOICE CONTROL</div>
    <div class="card-body">
      <p style="color:var(--text-dim); text-align:center; font-size:0.85rem;">Natural language with audio responses</p>

      <div class="wave-container" id="wave-container">
        <div class="wave-bar"></div>
        <div class="wave-bar"></div>
        <div class="wave-bar"></div>
        <div class="wave-bar"></div>
        <div class="wave-bar"></div>
        <div class="wave-bar"></div>
        <div class="wave-bar"></div>
        <div class="wave-bar"></div>
        <div class="wave-bar"></div>
      </div>

      <div class="voice-btn-row">
        <button id="start-btn" onclick="startRecording()">&#x1F3A4; Start Recording</button>
        <button id="stop-btn" onclick="stopRecording()" style="display: none;">&#x23F9; Stop Recording</button>
      </div>

      <div id="status-text">Click Start to begin</div>

      <div id="result-container" style="display: none;">
        <div class="result-box">
          <strong>YOU SAID</strong>
          <p id="user-text" style="margin:0;"></p>
        </div>
        <div class="result-box timmy-reply">
          <strong>TIMMY</strong>
          <p id="timmy-text" style="margin:0;"></p>
        </div>
        <audio id="audio-player" controls style="display: none;"></audio>
      </div>
    </div>
  </div>
</div>

<script>
var recognition = null;
var isRecording = false;

if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
    var SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
    recognition = new SpeechRecognition();
    recognition.continuous = false;
    recognition.interimResults = true;
    recognition.lang = 'en-US';

    recognition.onstart = function() {
        isRecording = true;
        document.getElementById('start-btn').style.display = 'none';
        document.getElementById('stop-btn').style.display = 'inline-flex';
        document.getElementById('wave-container').classList.add('listening');
        document.getElementById('status-text').textContent = 'Listening...';
    };

    recognition.onresult = function(event) {
        var finalTranscript = '';
        for (var i = event.resultIndex; i < event.results.length; i++) {
            if (event.results[i].isFinal) {
                finalTranscript += event.results[i][0].transcript;
            }
        }
        if (finalTranscript) { processCommand(finalTranscript); }
    };

    recognition.onerror = function(event) {
        console.error('Speech error:', event.error);
        document.getElementById('status-text').textContent = 'Error: ' + event.error;
        stopRecording();
    };

    recognition.onend = function() {
        if (isRecording) { stopRecording(); }
    };
} else {
    document.getElementById('status-text').textContent = 'Speech recognition not supported';
    document.getElementById('start-btn').disabled = true;
}

function startRecording() {
    if (recognition) { recognition.start(); }
}
function stopRecording() {
    isRecording = false;
    if (recognition) { recognition.stop(); }
    document.getElementById('start-btn').style.display = 'inline-flex';
    document.getElementById('stop-btn').style.display = 'none';
    document.getElementById('wave-container').classList.remove('listening');
    document.getElementById('status-text').textContent = 'Processing...';
}

async function processCommand(text) {
    document.getElementById('user-text').textContent = text;

    try {
        var response = await fetch('/voice/enhanced', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'text=' + encodeURIComponent(text)
        });
        var data = await response.json();

        document.getElementById('timmy-text').textContent = data.response_text;
        document.getElementById('result-container').style.display = 'block';
        document.getElementById('status-text').textContent = 'Done!';

        if (data.audio_url) {
            var audio = document.getElementById('audio-player');
            audio.src = data.audio_url;
            audio.style.display = 'block';
            audio.play();
        } else {
            var utterance = new SpeechSynthesisUtterance(data.response_text);
            utterance.rate = 1.1;
            window.speechSynthesis.speak(utterance);
        }
    } catch (e) {
        document.getElementById('timmy-text').textContent = 'Sorry, I had trouble with that.';
        document.getElementById('result-container').style.display = 'block';
        document.getElementById('status-text').textContent = 'Error';
    }
}
</script>
{% endblock %}
