import { ThreadsReply } from "../api/haixun";

export type ReplyMediaPreview = {
  src: string;
  kind: "gif" | "image" | "video";
  label: string;
};

function previewFromChild(child: NonNullable<ThreadsReply["media_children"]>[number]): ReplyMediaPreview | null {
  const mediaType = (child.media_type || "").toUpperCase();
  const mediaURL = (child.media_url || "").trim();
  const thumbURL = (child.thumbnail_url || "").trim();

  if (mediaType === "VIDEO") {
    const src = thumbURL || mediaURL;
    if (src) return { src, kind: "video", label: "影片" };
  }
  if (mediaType === "IMAGE" || mediaType === "CAROUSEL_ALBUM") {
    const src = mediaURL || thumbURL;
    if (src) return { src, kind: "image", label: "圖片" };
  }
  if (mediaURL) {
    return { src: mediaURL, kind: mediaType === "VIDEO" ? "video" : "image", label: "媒體" };
  }
  if (thumbURL) {
    return { src: thumbURL, kind: "image", label: "預覽" };
  }
  return null;
}

export function replyMediaPreviews(reply: ThreadsReply): ReplyMediaPreview[] {
  const children = reply.media_children || [];
  if (children.length > 0) {
    const previews = children.map(previewFromChild).filter((item): item is ReplyMediaPreview => Boolean(item));
    if (previews.length > 0) {
      const capped = previews.slice(0, 9);
      return capped.map((item, index) => ({
        ...item,
        label: capped.length > 1 ? `圖 ${index + 1}/${capped.length}` : item.label
      }));
    }
  }

  const single = replyMediaPreview(reply);
  return single ? [single] : [];
}

export function replyMediaPreview(reply: ThreadsReply): ReplyMediaPreview | null {
  const gif = (reply.gif_url || "").trim();
  if (gif) {
    return { src: gif, kind: "gif", label: "GIF" };
  }

  const mediaType = (reply.media_type || "").toUpperCase();
  const mediaURL = (reply.media_url || "").trim();
  const thumbURL = (reply.thumbnail_url || "").trim();

  if (mediaType === "VIDEO") {
    const src = thumbURL || mediaURL;
    if (src) return { src, kind: "video", label: "影片" };
  }
  if (mediaType === "IMAGE" || mediaType === "CAROUSEL_ALBUM") {
    const src = mediaURL || thumbURL;
    if (src) return { src, kind: "image", label: mediaType === "CAROUSEL_ALBUM" ? "多圖" : "圖片" };
  }
  if (mediaURL) {
    return { src: mediaURL, kind: mediaType === "VIDEO" ? "video" : "image", label: "媒體" };
  }
  if (thumbURL) {
    return { src: thumbURL, kind: "image", label: "預覽" };
  }
  return null;
}