/* public/js/video-frames.js
 * Extract N evenly spaced frames from a video file using <video> + <canvas>.
 * Returns array of base64 PNG strings.
 */
window.extractVideoFrames = async function (file, count = 5, onProgress = null) {
  const url = URL.createObjectURL(file);
  const video = document.createElement('video');
  video.src = url;
  video.muted = true;
  video.crossOrigin = 'anonymous';
  video.preload = 'auto';

  await new Promise((res, rej) => {
    video.addEventListener('loadedmetadata', res, { once: true });
    video.addEventListener('error', () => rej(new Error('Could not load video')), { once: true });
  });

  const duration = isFinite(video.duration) ? video.duration : 0;
  if (!duration) { URL.revokeObjectURL(url); throw new Error('Video has no duration'); }

  const out = [];
  const canvas = document.createElement('canvas');
  // cap to a reasonable size for hashing
  const W = Math.min(video.videoWidth || 320, 480);
  const H = Math.round((video.videoHeight || 240) * (W / (video.videoWidth || 320)));
  canvas.width = W; canvas.height = H;
  const ctx = canvas.getContext('2d');

  for (let i = 0; i < count; i++) {
    const t = ((i + 0.5) / count) * duration;
    await new Promise((res) => {
      const onSeek = () => { video.removeEventListener('seeked', onSeek); res(); };
      video.addEventListener('seeked', onSeek);
      video.currentTime = Math.min(duration - 0.05, t);
    });
    ctx.drawImage(video, 0, 0, W, H);
    const b64 = canvas.toDataURL('image/jpeg', 0.7).split(',', 2)[1];
    out.push(b64);
    if (onProgress) onProgress(i, count);
  }
  URL.revokeObjectURL(url);
  return out;
};
