// StellarCaptions — microphone permission helper.
// Offscreen documents and the action popup can't reliably show the mic prompt,
// so this small window requests it. Once granted for the extension origin, the
// background resumes the pending capture and the offscreen mic works.
const statusEl = document.getElementById('status')

async function run() {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
    stream.getTracks().forEach((t) => t.stop())
    statusEl.textContent = 'Microphone enabled — you can close this window.'
    statusEl.className = 'status ok'
    try { await chrome.storage.local.set({ micGranted: true }) } catch {}
    try { chrome.runtime.sendMessage({ action: 'micPermissionGranted' }) } catch {}
    setTimeout(() => window.close(), 700)
  } catch (e) {
    statusEl.textContent = 'Microphone is blocked. Click the camera/mic icon in the address bar to allow it, then reopen the extension and try again.'
    statusEl.className = 'status err'
    try {
      await chrome.storage.local.set({ micGranted: false })
      await chrome.storage.local.remove('pendingMicStart')
    } catch {}
  }
}

run()
