// PRE — Voice Input
(() => {
  (async function initVoice() {
    const voiceBtn = document.getElementById('voice-btn');
    if (!voiceBtn) return;

    // Check if voice capabilities are available
    try {
      const res = await fetch('/api/voice/status');
      const status = await res.json();
      if (status.whisper) {
        voiceBtn.classList.remove('hidden');
      }
    } catch {
      // Voice not available — leave button hidden
      return;
    }

    let mediaRecorder = null;
    let audioChunks = [];
    let isRecording = false;

    voiceBtn.addEventListener('mousedown', startRecording);
    voiceBtn.addEventListener('mouseup', stopRecording);
    voiceBtn.addEventListener('mouseleave', stopRecording);
    // Touch support
    voiceBtn.addEventListener('touchstart', (e) => { e.preventDefault(); startRecording(); });
    voiceBtn.addEventListener('touchend', (e) => { e.preventDefault(); stopRecording(); });

    async function startRecording() {
      if (isRecording) return;
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        audioChunks = [];
        mediaRecorder = new MediaRecorder(stream, { mimeType: 'audio/webm' });
        mediaRecorder.ondataavailable = (e) => { if (e.data.size > 0) audioChunks.push(e.data); };
        mediaRecorder.onstop = async () => {
          stream.getTracks().forEach(t => t.stop());
          if (audioChunks.length === 0) return;
          const blob = new Blob(audioChunks, { type: 'audio/webm' });
          const reader = new FileReader();
          reader.onloadend = async () => {
            const base64 = reader.result.split(',')[1];
            voiceBtn.title = 'Transcribing...';
            try {
              const res = await fetch('/api/voice/transcribe', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ audio: base64, mime_type: 'audio/webm' }),
              });
              const data = await res.json();
              if (data.text) {
                const input = document.getElementById('chat-input');
                if (input) {
                  input.value = (input.value ? input.value + ' ' : '') + data.text;
                  input.focus();
                  input.dispatchEvent(new Event('input'));
                }
              }
            } catch {}
            voiceBtn.title = 'Voice input (hold to record)';
          };
          reader.readAsDataURL(blob);
        };
        mediaRecorder.start();
        isRecording = true;
        voiceBtn.classList.add('recording');
        voiceBtn.title = 'Recording... release to transcribe';
      } catch {
        // Microphone permission denied or not available
      }
    }

    function stopRecording() {
      if (!isRecording || !mediaRecorder) return;
      isRecording = false;
      voiceBtn.classList.remove('recording');
      if (mediaRecorder.state === 'recording') {
        mediaRecorder.stop();
      }
    }
  })();
})();
