export const generateThumbnailFromVideo = (videoFile: File): Promise<Blob> => {
  return new Promise((resolve, reject) => {
    const video = document.createElement("video");
    video.preload = "metadata";
    video.muted = true;
    video.crossOrigin = "anonymous"; // helpful for safety with canvas

    const canvas = document.createElement("canvas");
    const fileURL = URL.createObjectURL(videoFile);
    video.src = fileURL;

    video.onloadedmetadata = () => {
      // Seek to 0.5s or middle of video if it's shorter
      video.currentTime = Math.min(0.5, video.duration / 2);
    };

    video.onseeked = () => {
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;

      const ctx = canvas.getContext("2d");
      if (!ctx) {
        URL.revokeObjectURL(fileURL);
        return reject("Canvas context not found");
      }

      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

      canvas.toBlob((blob) => {
        URL.revokeObjectURL(fileURL); // Clean up the video URL
        if (blob) {
          resolve(blob);
        } else {
          reject("Thumbnail generation failed");
        }
      }, "image/jpeg");
    };

    video.onerror = () => {
      URL.revokeObjectURL(fileURL);
      reject("Error loading video");
    };
  });
};
