// Offscreen document for audio recording
// This bypasses the side panel's security restrictions

let mediaRecorder = null;
let audioChunks = [];

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

  switch (message.type) {
    case 'start-recording':
      startRecording(sendResponse);
      return true; // Keep channel open for async response

    case 'stop-recording':
      stopRecording(sendResponse);
      return true;

    default:
      sendResponse({ error: 'Unknown message type' });
  }
});

async function startRecording(sendResponse) {
  try {
    // Check if getUserMedia is available
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      sendResponse({
        success: false,
        error: 'getUserMedia not available in offscreen document',
        errorName: 'NotSupportedError'
      });
      return;
    }

    console.log('Requesting microphone access...');
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    console.log('Microphone access granted');

    // Find supported mimeType
    const mimeTypes = [
      'audio/webm;codecs=opus',
      'audio/webm',
      'audio/ogg;codecs=opus',
      'audio/mp4'
    ];
    let mimeType = '';
    for (const type of mimeTypes) {
      if (MediaRecorder.isTypeSupported(type)) {
        mimeType = type;
        break;
      }
    }
    console.log('Using mimeType:', mimeType || 'default');

    const options = mimeType ? { mimeType } : {};
    mediaRecorder = new MediaRecorder(stream, options);
    audioChunks = [];

    mediaRecorder.ondataavailable = (event) => {
      if (event.data.size > 0) {
        audioChunks.push(event.data);
      }
    };

    mediaRecorder.onerror = (event) => {
      console.error('MediaRecorder error:', event.error);
    };

    mediaRecorder.start(1000);
    console.log('Recording started');
    sendResponse({ success: true, mimeType: mediaRecorder.mimeType });
  } catch (error) {
    console.error('Recording error:', error.name, error.message);
    sendResponse({
      success: false,
      error: error.message || String(error),
      errorName: error.name || 'UnknownError'
    });
  }
}

async function stopRecording(sendResponse) {
  if (!mediaRecorder || mediaRecorder.state === 'inactive') {
    sendResponse({ success: false, error: 'No active recording' });
    return;
  }

  mediaRecorder.onstop = async () => {
    // Stop all tracks
    mediaRecorder.stream.getTracks().forEach(track => track.stop());

    // Create blob
    const audioBlob = new Blob(audioChunks, { type: mediaRecorder.mimeType || 'audio/webm' });

    // Convert to base64
    const reader = new FileReader();
    reader.onloadend = () => {
      sendResponse({
        success: true,
        audioData: reader.result,
        mimeType: audioBlob.type
      });
    };
    reader.onerror = () => {
      sendResponse({ success: false, error: 'Failed to read audio data' });
    };
    reader.readAsDataURL(audioBlob);
  };

  mediaRecorder.stop();
}
