import { parseLocationContent } from "@/components/chat/LocationMessageBubble";
import { parseSharedPost } from "@/components/chat/SharedPostBubble";
import { parseSharedProduct } from "@/components/chat/SharedProductBubble";
import {
  extractStoryReactionText,
  parseSharedStory,
} from "@/components/chat/SharedStoryBubble";
import type { ChatMessage } from "@/components/chat/ChatMessageCard";

function parseForwarded(content: string): ChatMessage["forwardedFrom"] | null {
  try {
    const line = content.split("\n")[0];
    const parsed = JSON.parse(line);
    return parsed.forwardedFrom ?? null;
  } catch {
    return null;
  }
}

function stripJsonPrefix(content: string): string {
  return content.replace(/^\{.*\}\n?/, "").trim();
}

function getTextAfterFirstLine(content: string): string {
  const lines = content.split("\n");
  if (lines.length <= 1) return "";
  return lines.slice(1).join("\n").trim();
}

type CopyableMessage = {
  content?: string;
  file?: string;
  fileType?: ChatMessage["fileType"];
  forwardedFrom?: ChatMessage["forwardedFrom"];
};

export function getCopyableMessageText(
  message: CopyableMessage
): string | null {
  const content = message.content?.trim() || "";
  if (!content && !message.file) return null;

  const location =
    message.fileType === "location" ? parseLocationContent(content) : null;
  if (location) {
    const label = location.label?.trim();
    const coords = `${location.lat}, ${location.lng}`;
    return label ? `${label}\n${coords}` : coords;
  }

  const sharedPost = parseSharedPost(content);
  if (sharedPost) {
    const caption = sharedPost.caption?.trim();
    if (caption) return caption;
    return null;
  }

  const sharedProduct = parseSharedProduct(content);
  if (sharedProduct) {
    return sharedProduct.title?.trim() || null;
  }

  const sharedStory = parseSharedStory(content);
  if (sharedStory) {
    const reactionText = extractStoryReactionText(content);
    return reactionText || null;
  }

  const forwarded = message.forwardedFrom || parseForwarded(content);
  if (forwarded) {
    return getTextAfterFirstLine(content) || null;
  }

  if (parseLocationContent(content)) {
    const loc = parseLocationContent(content)!;
    const label = loc.label?.trim();
    const coords = `${loc.lat}, ${loc.lng}`;
    return label ? `${label}\n${coords}` : coords;
  }

  const text = stripJsonPrefix(content);
  return text || null;
}

export function getCopyableRoomMessageText(content?: string): string | null {
  const text = content?.trim();
  return text || null;
}

export async function copyTextToClipboard(text: string): Promise<boolean> {
  if (typeof window === "undefined") return false;

  try {
    if (navigator.clipboard?.writeText) {
      await navigator.clipboard.writeText(text);
      return true;
    }
  } catch {
    // fallback below
  }

  try {
    const textarea = document.createElement("textarea");
    textarea.value = text;
    textarea.setAttribute("readonly", "");
    textarea.style.position = "fixed";
    textarea.style.opacity = "0";
    textarea.style.pointerEvents = "none";
    document.body.appendChild(textarea);
    textarea.select();
    const copied = document.execCommand("copy");
    document.body.removeChild(textarea);
    return copied;
  } catch {
    return false;
  }
}
