import { useEffect, useState } from "react";
import type { Attachment } from "../../../types/post";
import {
  mobilePreviewMediaQuery,
  videoPreviewSource,
} from "../utils/videoPreviewSource";

function getMatchesMobilePreview(): boolean {
  if (typeof window === "undefined" || !window.matchMedia) return false;
  return window.matchMedia(mobilePreviewMediaQuery).matches;
}

export function useShouldUseMobilePreview(): boolean {
  const [useMobilePreview, setUseMobilePreview] = useState(
    getMatchesMobilePreview,
  );

  useEffect(() => {
    if (typeof window === "undefined" || !window.matchMedia) return;

    const media = window.matchMedia(mobilePreviewMediaQuery);
    const update = () => setUseMobilePreview(media.matches);
    update();

    media.addEventListener("change", update);
    return () => media.removeEventListener("change", update);
  }, []);

  return useMobilePreview;
}

export function useVideoPreviewSource(attachment: Attachment): string {
  return videoPreviewSource(attachment, useShouldUseMobilePreview());
}
