function collectionValues(collection) {
  if (!collection) return [];
  if (Array.isArray(collection)) return collection;
  if (typeof collection.values === "function") return [...collection.values()];
  return Object.values(collection);
}

function discordOverlayContent(message) {
  let text = String(message?.content || "");
  const media = [];
  const mediaUrls = new Set();
  const removedLinks = new Set();
  const addMedia = (url, type = "image", alt = "Animated image", sourceUrl = "") => {
    const clean = String(url || "").trim();
    if (!/^https?:\/\//i.test(clean) || mediaUrls.has(clean) || media.length >= 4) return;
    mediaUrls.add(clean);
    media.push({ url: clean, type: type === "video" ? "video" : "image", alt });
    if (sourceUrl && text.includes(sourceUrl)) removedLinks.add(sourceUrl);
  };

  for (const attachment of collectionValues(message?.attachments)) {
    const url = attachment?.url || attachment?.proxyURL;
    const contentType = String(attachment?.contentType || attachment?.content_type || "").toLowerCase();
    if (contentType === "image/gif" || /\.gif(?:$|\?)/i.test(String(url || ""))) {
      addMedia(url, "image", attachment?.name || "Animated image");
    }
  }
  for (const embed of collectionValues(message?.embeds)) {
    const sourceUrl = String(embed?.url || "");
    const embedType = String(embed?.type || "").toLowerCase();
    if (embedType !== "gifv" && !/\.(?:gif|gifv)(?:$|\?)/i.test(sourceUrl)) continue;
    const videoUrl = embed?.video?.url || embed?.video?.proxyURL || embed?.video?.proxy_url;
    const imageUrl = embed?.image?.url || embed?.image?.proxyURL || embed?.image?.proxy_url || embed?.thumbnail?.url || embed?.thumbnail?.proxyURL || embed?.thumbnail?.proxy_url;
    if (videoUrl) addMedia(videoUrl, "video", embed?.title || "Animated image", sourceUrl);
    else addMedia(imageUrl || sourceUrl, "image", embed?.title || "Animated image", sourceUrl);
  }
  for (const sticker of collectionValues(message?.stickers)) {
    addMedia(sticker?.url, "image", sticker?.name || "Sticker");
  }
  for (const match of text.matchAll(/https?:\/\/[^\s<>]+\.gif(?:\?[^\s<>]*)?/gi)) {
    addMedia(match[0], "image", "Animated image", match[0]);
  }
  for (const link of removedLinks) text = text.split(link).join("");
  text = text.replace(/[ \t]+\n/g, "\n").replace(/\n[ \t]+/g, "\n").trim();

  const emotes = [];
  for (const match of text.matchAll(/<(a?):([a-zA-Z0-9_]+):(\d+)>/g)) {
    const animated = match[1] === "a";
    emotes.push({
      start: match.index,
      end: match.index + match[0].length - 1,
      image: `https://cdn.discordapp.com/emojis/${match[3]}.${animated ? "gif" : "webp"}?size=96&quality=lossless`,
      label: `:${match[2]}:`
    });
  }
  return { text, emotes, media };
}

module.exports = { discordOverlayContent };
