import {
  formatBubbleTime,
  formatChatDateLabel,
  parseMessageDate,
} from "@/lib/chat/formatMessageTime";
import { DEFAULT_LANGUAGE, type AppLanguage } from "@/lib/i18n/registry";

export type DateGroupedItem<T> =
  | { type: "date"; label: string; key: string }
  | { type: "item"; item: T; key: string };

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

export function groupItemsByDate<T>(
  items: T[],
  getCreatedAt: (item: T) => string | null | undefined,
  getItemKey: (item: T, index: number) => string,
  lang: AppLanguage = DEFAULT_LANGUAGE,
  options?: { includeTime?: boolean }
): DateGroupedItem<T>[] {
  const groups: DateGroupedItem<T>[] = [];
  let lastDay = "";

  items.forEach((item, index) => {
    const createdAt = getCreatedAt(item);
    const dk = dayKey(createdAt);

    if (dk !== lastDay) {
      lastDay = dk;
      const dateLabel = formatChatDateLabel(createdAt, lang);
      const timeLabel = options?.includeTime
        ? formatBubbleTime(createdAt, lang)
        : "";
      groups.push({
        type: "date",
        label: timeLabel ? `${dateLabel} ${timeLabel}` : dateLabel,
        key: `date-${dk}`,
      });
    }

    groups.push({
      type: "item",
      item,
      key: getItemKey(item, index),
    });
  });

  return groups;
}
