/**
 * offscreen.js — 运行在 offscreen document 里，负责语音识别
 * offscreen document 是真正的扩展页面（chrome-extension://），可以调用麦克风
 */

let recognition = null;
let isRecognizing = false;

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.target !== 'offscreen') return;

  if (msg.type === 'VOICE_START') {
    startRecognition();
    sendResponse({ ok: true });
  } else if (msg.type === 'VOICE_STOP') {
    stopRecognition();
    sendResponse({ ok: true });
  } else if (msg.type === 'VOICE_PAUSE') {
    pauseRecognition();
    sendResponse({ ok: true });
  } else if (msg.type === 'VOICE_RESUME') {
    resumeRecognition();
    sendResponse({ ok: true });
  }
  return true;
});

function initRecognition() {
  const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
  if (!SR) {
    chrome.runtime.sendMessage({ type: 'VOICE_ERROR', error: 'not-supported' });
    return null;
  }
  const rec = new SR();
  rec.lang = 'zh-CN';
  rec.continuous = true;
  rec.interimResults = true;
  rec.maxAlternatives = 1;

  rec.onresult = (event) => {
    let interim = '';
    let finalChunk = '';
    for (let i = event.resultIndex; i < event.results.length; i++) {
      const t = event.results[i][0].transcript;
      if (event.results[i].isFinal) {
        finalChunk += t;
      } else {
        interim += t;
      }
    }
    chrome.runtime.sendMessage({
      type: 'VOICE_RESULT',
      finalChunk,
      interim
    });
  };

  rec.onerror = (event) => {
    if (event.error === 'no-speech') {
      // 静音超时，自动重启
      if (isRecognizing) {
        try { rec.start(); } catch(e) {}
      }
      return;
    }
    if (event.error !== 'aborted') {
      chrome.runtime.sendMessage({ type: 'VOICE_ERROR', error: event.error });
    }
    isRecognizing = false;
  };

  rec.onend = () => {
    if (isRecognizing) {
      try { rec.start(); } catch(e) {}
    }
  };

  return rec;
}

function startRecognition() {
  if (!recognition) recognition = initRecognition();
  if (!recognition) return;
  isRecognizing = true;
  try { recognition.start(); } catch(e) {}
}

function stopRecognition() {
  isRecognizing = false;
  if (recognition) {
    try { recognition.stop(); } catch(e) {}
  }
  chrome.runtime.sendMessage({ type: 'VOICE_STOPPED' });
}

function pauseRecognition() {
  if (recognition) {
    try { recognition.stop(); } catch(e) {}
  }
  // isRecognizing 保持 true，onend 里不会重启（因为 stop 触发 onend 时 pause 状态由 background 管）
}

function resumeRecognition() {
  if (recognition) {
    try { recognition.start(); } catch(e) {}
  }
}
