export function todayYmdUTC(): string {
  const d = new Date();
  const y = d.getUTCFullYear();
  const m = String(d.getUTCMonth() + 1).padStart(2, '0');
  const day = String(d.getUTCDate()).padStart(2, '0');
  return `${y}-${m}-${day}`;
}

export function compareYmd(a: string, b: string): number {
  // returns -1 if a<b, 0 if equal, 1 if a>b
  if (a === b) return 0;
  return a < b ? -1 : 1;
}

export function addDaysYmd(ymd: string, days: number): string {
  const d = new Date(`${ymd}T00:00:00Z`);
  d.setUTCDate(d.getUTCDate() + days);
  const y = d.getUTCFullYear();
  const m = String(d.getUTCMonth() + 1).padStart(2, '0');
  const day = String(d.getUTCDate()).padStart(2, '0');
  return `${y}-${m}-${day}`;
}

export function dueStatus(ymd: string | null, soonDays: number = 3): 'none' | 'overdue' | 'soon' {
  if (!ymd) return 'none';
  const today = todayYmdUTC();
  if (compareYmd(ymd, today) < 0) return 'overdue';
  const soonCut = addDaysYmd(today, soonDays);
  if (compareYmd(ymd, soonCut) <= 0) return 'soon';
  return 'none';
}

export function ymdToDmy(ymd: string): string {
  const m = /^\s*(\d{4})-(\d{2})-(\d{2})\s*$/.exec(ymd || '');
  if (!m) return ymd;
  return `${m[3]}/${m[2]}/${m[1]}`;
}

export function isToday(ymd: string): boolean {
  return ymd === todayYmdUTC();
}

export function isTomorrow(ymd: string): boolean {
  return ymd === addDaysYmd(todayYmdUTC(), 1);
}
