export function pad2(n: number) {
  return n < 10 ? `0${n}` : `${n}`;
}

export function formatDisplayDateTime(input?: string | Date | null) {
  if (!input) return "";
  const date = input instanceof Date ? input : new Date(input);
  if (Number.isNaN(date.getTime())) return "";
  const y = date.getFullYear();
  const m = pad2(date.getMonth() + 1);
  const d = pad2(date.getDate());
  const hh = pad2(date.getHours());
  const mm = pad2(date.getMinutes());
  return `${y}-${m}-${d} ${hh}:${mm}`;
}

export function normalizeDisplayDateTime(value?: string | null) {
  if (!value) return "";
  const v = value.trim();
  if (!v) return "";
  if (v.includes("T")) return formatDisplayDateTime(v);
  const [datePart, timePart = "00:00"] = v.split(" ");
  if (!datePart || !timePart) return "";
  const [y, m, d] = datePart.split("-").map(Number);
  const [hh, mm] = timePart.split(":").map(Number);
  if (!y || !m || !d || Number.isNaN(hh) || Number.isNaN(mm)) return "";
  return `${y}-${pad2(m)}-${pad2(d)} ${pad2(hh)}:${pad2(mm)}`;
}

export function splitDisplayDateTime(value?: string | null) {
  const normalized = normalizeDisplayDateTime(value);
  if (!normalized) return { date: "", time: "" };
  const [date, time] = normalized.split(" ");
  return { date, time };
}

export function combineDateTime(date: string, time: string) {
  if (!date) return "";
  return `${date} ${time || "00:00"}`;
}

export function toIsoFromDisplay(value?: string | null) {
  const normalized = normalizeDisplayDateTime(value);
  if (!normalized) return "";
  const isoBase = normalized.replace(" ", "T");
  const date = new Date(isoBase);
  if (Number.isNaN(date.getTime())) return "";
  return date.toISOString();
}
