/** Display dates as DD-MM-YYYY */
export function formatDate(value: Date | string | null | undefined): string {
  if (value == null || value === '') return '—';
  const s = String(value);
  const m = s.match(/^(\d{4})-(\d{2})-(\d{2})/);
  if (m) return `${m[3]}-${m[2]}-${m[1]}`;
  const d = value instanceof Date ? value : new Date(s);
  if (Number.isNaN(d.getTime())) return s;
  const dd = String(d.getDate()).padStart(2, '0');
  const mm = String(d.getMonth() + 1).padStart(2, '0');
  return `${dd}-${mm}-${d.getFullYear()}`;
}

/** HH:MM from decimal hours */
export function hoursToHhmm(hours: number | string | null | undefined): string {
  const total = Math.round(Number(hours || 0) * 60);
  const h = Math.floor(Math.abs(total) / 60);
  const m = Math.abs(total % 60);
  const sign = total < 0 ? '-' : '';
  return `${sign}${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}`;
}

/** Parse HH:MM into decimal hours */
export function parseHhmm(value: string): number {
  const s = String(value ?? '').trim();
  const m = s.match(/^(\d{1,3}):([0-5]\d)$/);
  if (!m) return NaN;
  return Math.round((Number(m[1]) + Number(m[2]) / 60) * 100) / 100;
}

export function toDateOnly(value: string | Date | null | undefined): Date | null {
  if (value == null || value === '') return null;
  if (value instanceof Date) {
    return new Date(Date.UTC(value.getFullYear(), value.getMonth(), value.getDate()));
  }
  const m = String(value).match(/^(\d{4})-(\d{2})-(\d{2})/);
  if (!m) return null;
  return new Date(`${m[1]}-${m[2]}-${m[3]}T00:00:00.000Z`);
}
