// Pure fixture grouping helpers (no store/DOM imports — vitest-friendly).
import { dayKeyOf } from './format';
import type { Fixture } from './types';

export interface DayGroup {
  /** Stable local-day key (YYYY-MM-DD). */
  key: string;
  /** Kickoff ISO of the day's first match (for localized day headers). */
  firstKickoff: string;
  fixtures: Fixture[];
}

/** Group fixtures (as given) by local day, first `maxDays` distinct days,
 *  sorted by kickoff within and across days. Pass Infinity for all days. */
export function groupByDay(fixtures: Fixture[], maxDays: number): DayGroup[] {
  const sorted = [...fixtures].sort((a, b) => a.kickoff.localeCompare(b.kickoff));
  const groups: DayGroup[] = [];
  for (const f of sorted) {
    const key = dayKeyOf(f.kickoff);
    const last = groups[groups.length - 1];
    if (last && last.key === key) {
      last.fixtures.push(f);
    } else {
      if (groups.length >= maxDays) break;
      groups.push({ key, firstKickoff: f.kickoff, fixtures: [f] });
    }
  }
  return groups;
}

/** Scheduled fixtures after today, grouped by local day, first `maxDays`
 *  distinct days. Days and fixtures are sorted by kickoff. */
export function upcomingByDay(fixtures: Fixture[], maxDays: number, now = new Date()): DayGroup[] {
  const todayKey = dayKeyOf(now.toISOString());
  return groupByDay(
    fixtures.filter((f) => f.status === 'scheduled' && dayKeyOf(f.kickoff) > todayKey),
    maxDays,
  );
}
