import type { ChatMessage } from "@/components/chat/ChatMessageCard";
import { parseMessageDate } from "@/lib/chat/formatMessageTime";

export type BubbleGroupPosition = "single" | "first" | "middle" | "last";

function dayKey(msg: ChatMessage): string {
  const d = parseMessageDate(msg.createdAtIso ?? msg.createdAt);
  if (d) return d.toDateString();
  return "unknown-day";
}

export function sameSender(a: ChatMessage, b: ChatMessage): boolean {
  return String(a.senderId) === String(b.senderId);
}

function sameVisualGroup(a: ChatMessage, b: ChatMessage): boolean {
  return sameSender(a, b) && dayKey(a) === dayKey(b);
}

export { sameVisualGroup };

export function getBubbleGroupPosition(
  messages: ChatMessage[],
  index: number
): BubbleGroupPosition {
  const current = messages[index];
  if (!current) return "single";

  const sameAsPrev =
    index > 0 && sameVisualGroup(messages[index - 1], current);
  const sameAsNext =
    index < messages.length - 1 &&
    sameVisualGroup(messages[index + 1], current);

  if (!sameAsPrev && !sameAsNext) return "single";
  if (!sameAsPrev && sameAsNext) return "first";
  if (sameAsPrev && sameAsNext) return "middle";
  return "last";
}

/** Instagram-style corner radii (TL TR BR BL) */
export function getBubbleRadius(
  isOutgoing: boolean,
  position: BubbleGroupPosition
): string {
  const r = 18;
  const s = 4;

  if (isOutgoing) {
    switch (position) {
      case "single":
        return `${r}px ${r}px ${r}px ${s}px`;
      case "first":
        return `${r}px ${r}px ${r}px ${s}px`;
      case "middle":
        return `${s}px ${r}px ${r}px ${s}px`;
      case "last":
        return `${s}px ${r}px ${r}px ${r}px`;
    }
  }

  switch (position) {
    case "single":
      return `${r}px ${r}px ${s}px ${r}px`;
    case "first":
      return `${r}px ${r}px ${s}px ${r}px`;
    case "middle":
      return `${r}px ${s}px ${s}px ${r}px`;
    case "last":
      return `${r}px ${s}px ${r}px ${r}px`;
  }
}

export function getMessageRowSpacing(
  position: BubbleGroupPosition,
  isGroupedWithPrev: boolean
): string {
  if (isGroupedWithPrev) return "mt-[2px]";
  return "mt-3";
}
