/** Parse message timestamp (ISO or datetime string) for grouping */
export function parseMessageDate(createdAt?: string | null): Date | null {
  if (!createdAt) return null;
  const raw = String(createdAt).trim();
  const d = new Date(raw);
  if (!Number.isNaN(d.getTime())) return d;
  return null;
}

function isSameDay(a: Date, b: Date): boolean {
  return a.toDateString() === b.toDateString();
}

/** Telegram-style date label: امروز، دیروز، or calendar date */
export function formatChatDateLabel(createdAt?: string | null): string {
  const d = parseMessageDate(createdAt) ?? new Date();
  const today = new Date();
  const yesterday = new Date();
  yesterday.setDate(today.getDate() - 1);

  if (isSameDay(d, today)) return "امروز";
  if (isSameDay(d, yesterday)) return "دیروز";

  if (d.getFullYear() === today.getFullYear()) {
    return d.toLocaleDateString("fa-IR", { month: "long", day: "numeric" });
  }

  return d.toLocaleDateString("fa-IR", {
    year: "numeric",
    month: "long",
    day: "numeric",
  });
}

/** Bubble time: hours, minutes, seconds only (no date) */
export function formatBubbleTime(createdAt?: string | null): string {
  if (!createdAt) {
    return new Date().toLocaleTimeString("fa-IR", {
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    });
  }

  const raw = String(createdAt).trim();

  // Jalali datetime "1403-01-15 14:30:45" or ISO
  const timePart = raw.includes(" ")
    ? raw.split(" ").pop()
    : raw.length <= 8 && raw.includes(":")
      ? raw
      : null;

  if (timePart && /^\d{1,2}:\d{2}(:\d{2})?$/.test(timePart)) {
    const parts = timePart.split(":");
    if (parts.length === 2) return `${parts[0]}:${parts[1]}:00`;
    return timePart;
  }

  const d = new Date(raw);
  if (!Number.isNaN(d.getTime())) {
    return d.toLocaleTimeString("fa-IR", {
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    });
  }

  return raw;
}
