// screenRecorder.js

let mediaRecorder;
let recordedChunks = [];
let isRecording = false;
let stream;

// Function to start the screen recording
export async function startRecording() {
  let stream;
  let mediaRecorder;
  let recordedChunks = [];

  try {
    // Get screen capture (user must allow this)
    stream = await navigator.mediaDevices.getDisplayMedia({
      video: { mediaSource: "screen" }
    });

    mediaRecorder = new MediaRecorder(stream);

    // Collect the video data chunks
    mediaRecorder.ondataavailable = (event) => {
      recordedChunks.push(event.data);
    };

    // When recording stops, process the chunks into a video file
    mediaRecorder.onstop = () => {
      const blob = new Blob(recordedChunks, { type: 'video/webm' });
      const videoUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = videoUrl;
      a.download = 'recording.webm';
      a.click();
    };

    // Start recording
    mediaRecorder.start();
    console.log('Recording started');

  } catch (err) {
    console.error('Error starting recording:', err);
    if (err.name === 'NotAllowedError') {
      console.error('User denied screen capture permission.');
    } else if (err.name === 'NotFoundError') {
      console.error('No available display media devices found. Is your browser configured for screen capture?');
    } else if (err.name === 'NotReadableError') {
      console.error('A camera or microphone is being used or is not accessible.');
    } else if (err.name === 'AbortError') {
      console.error('The operation was aborted (usually when the user cancels).');
    } else {
      console.error('Unknown error:', err);
    }
  }

  // Make sure to clean up the stream and media recorder when done
  return () => {
    if (mediaRecorder && mediaRecorder.state !== 'inactive') {
      mediaRecorder.stop();
    }
    if (stream) {
      stream.getTracks().forEach(track => track.stop()); // Stop all media tracks
    }
    console.log('Recording stopped and resources cleaned up');
  };
}

// Function to stop the recording
export function stopRecording() {
  if (mediaRecorder && isRecording) {
    mediaRecorder.stop();
    stream.getTracks().forEach((track) => track.stop());
    console.log('Recording stopped');
  }
}
