import type { EventItem } from './fallback-data';

function isDateOnly(value: string): boolean {
  return /^\d{4}-\d{2}-\d{2}$/.test(value);
}

function getEventEndTime(event: EventItem): number {
  const value = event.end_datetime || event.start_datetime;
  const timestamp = new Date(isDateOnly(value) ? `${value}T23:59:59` : value).getTime();
  return Number.isFinite(timestamp) ? timestamp : 0;
}

function getEventStartTime(event: EventItem): number {
  const value = event.start_datetime;
  const timestamp = new Date(isDateOnly(value) ? `${value}T00:00:00` : value).getTime();
  return Number.isFinite(timestamp) ? timestamp : 0;
}

export function isUpcomingEvent(event: EventItem, now = new Date()): boolean {
  return getEventEndTime(event) >= now.getTime();
}

export function sortEventsByStartDate(events: EventItem[]): EventItem[] {
  return [...events].sort((left, right) => getEventStartTime(left) - getEventStartTime(right));
}

export function getUpcomingEvents(events: EventItem[], now = new Date()): EventItem[] {
  return sortEventsByStartDate(events.filter((event) => isUpcomingEvent(event, now)));
}
