// Video player for extension iframe - runs under extension CSP (allows blob: media-src)
(function () {
  const video = document.getElementById('video-player');
  let localBlobUrl = null;

  // Emit time updates to parent
  video.addEventListener('timeupdate', () => {
    window.parent.postMessage({
      type: 'TIME_UPDATE',
      currentTime: video.currentTime,
    }, '*');
  });

  // Emit duration when metadata loads
  video.addEventListener('loadedmetadata', () => {
    window.parent.postMessage({
      type: 'DURATION_CHANGE',
      duration: video.duration,
    }, '*');
  });

  // Listen for messages from parent
  window.addEventListener('message', (event) => {
    if (!event.data || !event.data.type) return;

    switch (event.data.type) {
      case 'LOAD_VIDEO': {
        // URL-based loading (fallback)
        cleanup();
        video.src = event.data.videoUrl;
        break;
      }

      case 'LOAD_VIDEO_DATA': {
        // ArrayBuffer-based loading - creates blob locally inside extension context
        cleanup();
        const blob = new Blob([event.data.data], { type: event.data.mimeType || 'video/webm' });
        localBlobUrl = URL.createObjectURL(blob);
        video.src = localBlobUrl;
        break;
      }

      case 'SEEK': {
        if (typeof event.data.time === 'number' && !isNaN(event.data.time)) {
          video.currentTime = event.data.time;
        }
        break;
      }
    }
  });

  function cleanup() {
    if (localBlobUrl) {
      URL.revokeObjectURL(localBlobUrl);
      localBlobUrl = null;
    }
  }

  // Signal that iframe is ready
  window.parent.postMessage({ type: 'VIDEO_PLAYER_READY' }, '*');
})();
