import { useEffect, useState } from "react";

/** 预览窗口最大 280px 宽，截取无需超过此尺寸 */
const MAX_CAPTURE_WIDTH = 480;

/**
 * 从视频 URL 截取 0.1s 处的帧，返回 JPEG data URL。
 * 失败时返回 null（降级渐变背景）。
 */
export function useVideoFrameCapture(videoUrl: string | null): string | null {
  const [frameUrl, setFrameUrl] = useState<string | null>(null);

  useEffect(() => {
    if (!videoUrl) {
      setFrameUrl(null);
      return;
    }

    let isActive = true;
    const video = document.createElement("video");
    video.muted = true;
    video.preload = "auto";
    video.playsInline = true;

    const cleanup = () => {
      video.removeEventListener("loadedmetadata", onLoaded);
      video.removeEventListener("canplay", onLoaded);
      video.removeEventListener("seeked", onSeeked);
      video.removeEventListener("error", onError);
      video.src = "";
      video.load();
    };

    const onSeeked = () => {
      if (!isActive) return;
      try {
        const vw = video.videoWidth;
        const vh = video.videoHeight;
        if (!vw || !vh) {
          if (isActive) setFrameUrl(null);
          cleanup();
          return;
        }

        const scale = Math.min(1, MAX_CAPTURE_WIDTH / vw);
        const cw = Math.round(vw * scale);
        const ch = Math.round(vh * scale);

        const canvas = document.createElement("canvas");
        canvas.width = cw;
        canvas.height = ch;
        const ctx = canvas.getContext("2d");
        if (!ctx) {
          if (isActive) setFrameUrl(null);
          cleanup();
          return;
        }
        ctx.drawImage(video, 0, 0, cw, ch);
        const dataUrl = canvas.toDataURL("image/jpeg", 0.7);
        if (isActive) setFrameUrl(dataUrl);
      } catch {
        if (isActive) setFrameUrl(null);
      }
      cleanup();
    };

    let seeked = false;
    const onLoaded = () => {
      if (!isActive || seeked) return;
      seeked = true;
      video.currentTime = 0.1;
    };

    const onError = () => {
      if (isActive) setFrameUrl(null);
      cleanup();
    };

    // 先绑定监听，再设 src
    video.addEventListener("loadedmetadata", onLoaded);
    video.addEventListener("canplay", onLoaded);
    video.addEventListener("seeked", onSeeked);
    video.addEventListener("error", onError);
    video.src = videoUrl;

    return () => {
      isActive = false;
      cleanup();
    };
  }, [videoUrl]);

  return frameUrl;
}
