/**
 * Date/time helpers for calendar and duty display.
 * Ported from webapp/js/dateUtils.js.
 */

/**
 * YYYY-MM-DD in local time (for calendar keys, "today", request range).
 */
export function localDateString(d: Date): string {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${y}-${m}-${day}`;
}

/** Duty-like object with start_at and end_at (UTC ISO strings). */
export interface DutyLike {
  start_at: string;
  end_at: string;
}

/**
 * True if duty (start_at/end_at UTC) overlaps the local day YYYY-MM-DD.
 */
export function dutyOverlapsLocalDay(d: DutyLike, dateKey: string): boolean {
  const [y, m, day] = dateKey.split("-").map(Number);
  const dayStart = new Date(y, m - 1, day, 0, 0, 0, 0);
  const dayEnd = new Date(y, m - 1, day, 23, 59, 59, 999);
  const start = new Date(d.start_at);
  const end = new Date(d.end_at);
  return end > dayStart && start < dayEnd;
}

/**
 * True if duty overlaps any local day in the range [firstKey, lastKey] (inclusive).
 */
export function dutyOverlapsLocalRange(
  d: DutyLike,
  firstKey: string,
  lastKey: string
): boolean {
  const [y1, m1, day1] = firstKey.split("-").map(Number);
  const [y2, m2, day2] = lastKey.split("-").map(Number);
  const rangeStart = new Date(y1, m1 - 1, day1, 0, 0, 0, 0);
  const rangeEnd = new Date(y2, m2 - 1, day2, 23, 59, 59, 999);
  const start = new Date(d.start_at);
  const end = new Date(d.end_at);
  return end > rangeStart && start < rangeEnd;
}

export function firstDayOfMonth(d: Date): Date {
  return new Date(d.getFullYear(), d.getMonth(), 1);
}

export function lastDayOfMonth(d: Date): Date {
  return new Date(d.getFullYear(), d.getMonth() + 1, 0);
}

/** Returns Monday of the week for the given date. */
export function getMonday(d: Date): Date {
  const day = d.getDay();
  const diff = d.getDate() - day + (day === 0 ? -6 : 1);
  return new Date(d.getFullYear(), d.getMonth(), diff);
}

/**
 * Format UTC date from ISO string as DD.MM for display.
 */
export function formatDateKey(isoDateStr: string): string {
  const d = new Date(isoDateStr);
  const day = String(d.getDate()).padStart(2, "0");
  const month = String(d.getMonth() + 1).padStart(2, "0");
  return `${day}.${month}`;
}

/**
 * Format YYYY-MM-DD as DD.MM for list header.
 * Returns key unchanged if it does not match YYYY-MM-DD format.
 */
export function dateKeyToDDMM(key: string): string {
  if (key.length < 10 || key[4] !== "-" || key[7] !== "-") return key;
  return key.slice(8, 10) + "." + key.slice(5, 7);
}

/**
 * Format ISO string as HH:MM (local).
 */
export function formatHHMM(isoStr: string): string {
  if (!isoStr) return "";
  const d = new Date(isoStr);
  const h = d.getHours();
  const m = d.getMinutes();
  return (h < 10 ? "0" : "") + h + ":" + (m < 10 ? "0" : "") + m;
}
