// Loaded inside an invisible iframe injected by contentScript.js into the
// active http(s) page. The iframe has allow="camera; microphone" and its src is
// chrome-extension://<id>/requestPermissions.html, so the prompt that Chrome
// shows media prompts for the extension origin. Once granted, the offscreen
// document inherits these grants.

(async function run() {
  try {
    const cameraStream = await navigator.mediaDevices.getUserMedia({ video: true });
    // We only wanted the grant — release the camera immediately so the
    // offscreen doc can re-acquire it.
    cameraStream.getTracks().forEach((t) => t.stop());

    let micGranted = false;
    let micError = null;
    try {
      const micStream = await navigator.mediaDevices.getUserMedia({ audio: true });
      micStream.getTracks().forEach((t) => t.stop());
      micGranted = true;
    } catch (err) {
      micError = String(err?.name || "") + ": " + String(err?.message || err);
    }

    window.parent.postMessage({
      type: "CHAMELEON_CAMERA_PERMISSION",
      status: "granted",
      micGranted,
      micError,
    }, "*");
  } catch (err) {
    window.parent.postMessage(
      {
        type: "CHAMELEON_CAMERA_PERMISSION",
        status: "denied",
        error: String(err?.name || "") + ": " + String(err?.message || err),
      },
      "*"
    );
  }
})();
