export const POST_LOCATION_NOTICE_KEY = "modstagram_post_location_notice_v1";

export function hasSeenPostLocationNotice(): boolean {
  if (typeof window === "undefined") return true;
  return window.localStorage.getItem(POST_LOCATION_NOTICE_KEY) === "1";
}

export function markPostLocationNoticeSeen(): void {
  if (typeof window === "undefined") return;
  window.localStorage.setItem(POST_LOCATION_NOTICE_KEY, "1");
}

export function captureVideoFrame(
  video: HTMLVideoElement,
  timeSec: number
): Promise<Blob> {
  return new Promise((resolve, reject) => {
    const drawFrame = () => {
      try {
        const canvas = document.createElement("canvas");
        canvas.width = video.videoWidth || 720;
        canvas.height = video.videoHeight || 1280;
        const ctx = canvas.getContext("2d");
        if (!ctx) {
          reject(new Error("canvas unavailable"));
          return;
        }
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        canvas.toBlob(
          (blob) => {
            if (!blob) {
              reject(new Error("frame capture failed"));
              return;
            }
            resolve(blob);
          },
          "image/webp",
          0.88
        );
      } catch (err) {
        reject(err);
      }
    };

    const target = Math.min(
      Math.max(0, timeSec),
      Math.max(0, (video.duration || 1) - 0.05)
    );

    let settled = false;
    const finish = (fn: () => void) => {
      if (settled) return;
      settled = true;
      fn();
    };

    const timeoutId = window.setTimeout(() => {
      video.removeEventListener("seeked", onSeeked);
      finish(() => reject(new Error("seek timeout")));
    }, 5000);

    const onSeeked = () => {
      video.removeEventListener("seeked", onSeeked);
      window.clearTimeout(timeoutId);
      finish(drawFrame);
    };

    if (
      video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA &&
      Math.abs(video.currentTime - target) < 0.01
    ) {
      window.clearTimeout(timeoutId);
      finish(drawFrame);
      return;
    }

    video.addEventListener("seeked", onSeeked);
    try {
      video.currentTime = target;
    } catch (err) {
      video.removeEventListener("seeked", onSeeked);
      window.clearTimeout(timeoutId);
      finish(() => reject(err instanceof Error ? err : new Error("seek failed")));
    }
  });
}
