// This page runs inside a hidden iframe on the extension's origin.
// It runs SpeechRecognition on behalf of the content script, bypassing
// the host page's Permissions-Policy restrictions on microphone access.

let recognition = null;
let isRecording = false;

const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;

function post(type, data) {
  window.parent.postMessage({ source: 'sniffer-speech-worker', type, ...data }, '*');
}

// Immediately report support status
post('ready', { supported: !!SpeechRecognition });

window.addEventListener('message', async (event) => {
  const msg = event.data;
  if (!msg || msg.target !== 'sniffer-speech-worker') return;

  switch (msg.action) {
    case 'start': {
      if (!SpeechRecognition) {
        post('error', { error: 'not-supported' });
        return;
      }

      // Request mic permission from extension origin (triggers browser prompt)
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        stream.getTracks().forEach(t => t.stop());
      } catch (err) {
        post('error', { error: 'mic-denied', message: String(err) });
        return;
      }

      if (recognition) {
        try { recognition.abort(); } catch (e) { /* ignore */ }
      }

      recognition = new SpeechRecognition();
      recognition.continuous = true;
      recognition.interimResults = true;
      recognition.lang = msg.language || 'en-US';

      recognition.onresult = (event) => {
        let finalTranscript = '';
        for (let i = event.resultIndex; i < event.results.length; i++) {
          if (event.results[i].isFinal) {
            finalTranscript += event.results[i][0].transcript + ' ';
          }
        }
        if (finalTranscript) {
          post('result', { transcript: finalTranscript });
        }
      };

      recognition.onerror = (event) => {
        if (event.error === 'no-speech' || event.error === 'aborted') return;
        post('error', { error: event.error });
      };

      recognition.onend = () => {
        if (isRecording) {
          // Auto-restart for continuous mode
          try {
            recognition.start();
          } catch (e) {
            isRecording = false;
            post('ended', {});
          }
        } else {
          post('ended', {});
        }
      };

      try {
        recognition.start();
        isRecording = true;
        post('started', {});
      } catch (err) {
        post('error', { error: 'start-failed', message: String(err) });
      }
      break;
    }

    case 'stop':
      isRecording = false;
      if (recognition) {
        try { recognition.stop(); } catch (e) { /* ignore */ }
      }
      break;

    case 'abort':
      isRecording = false;
      if (recognition) {
        try { recognition.abort(); } catch (e) { /* ignore */ }
      }
      post('ended', {});
      break;
  }
});
