import type { HistoryEvent } from '$lib/api/history';

export type DayGroup = {
  label: string;
  events: HistoryEvent[];
};

const MONTHS = [
  'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
];

function startOfDay(d: Date): Date {
  const out = new Date(d);
  out.setHours(0, 0, 0, 0);
  return out;
}

function daysBetween(later: Date, earlier: Date): number {
  const ms = startOfDay(later).getTime() - startOfDay(earlier).getTime();
  return Math.round(ms / (1000 * 60 * 60 * 24));
}

// dayBucket categorizes a played_at timestamp relative to `now`. Buckets:
//   Today        — same calendar day
//   Yesterday    — exactly 1 day before
//   This week    — 2-6 days before
//   <Mon DD>     — 7+ days before, current year
//   <Mon DD, YYYY> — 7+ days before, different year
// All comparisons use the browser-local timezone (Date methods).
export function dayBucket(playedAt: Date, now: Date): string {
  const delta = daysBetween(now, playedAt);
  if (delta <= 0) return 'Today';
  if (delta === 1) return 'Yesterday';
  if (delta < 7) return 'This week';
  const month = MONTHS[playedAt.getMonth()];
  const day = playedAt.getDate();
  if (playedAt.getFullYear() === now.getFullYear()) {
    return `${month} ${day}`;
  }
  return `${month} ${day}, ${playedAt.getFullYear()}`;
}

// groupByDay walks an array of history events (assumed sorted newest-first)
// and emits a section per bucket transition. Out-of-order input emits
// duplicate buckets — the walker doesn't dedupe.
export function groupByDay(events: HistoryEvent[], now: Date): DayGroup[] {
  const groups: DayGroup[] = [];
  let currentLabel: string | null = null;
  for (const event of events) {
    const playedAt = new Date(event.played_at);
    const label = dayBucket(playedAt, now);
    if (label !== currentLabel) {
      groups.push({ label, events: [event] });
      currentLabel = label;
    } else {
      groups[groups.length - 1].events.push(event);
    }
  }
  return groups;
}
