const MONTHS = [
  "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];

// Deterministic UTC-based formatter so server and client render identically
// (avoids React hydration mismatches that locale/timezone formatting can cause).
export function formatTimestamp(iso: string): string {
  const d = new Date(iso);
  const mon = MONTHS[d.getUTCMonth()];
  const day = d.getUTCDate();
  let h = d.getUTCHours();
  const min = String(d.getUTCMinutes()).padStart(2, "0");
  const ampm = h >= 12 ? "PM" : "AM";
  h = h % 12 || 12;
  return `${mon} ${day}, ${h}:${min} ${ampm}`;
}

// Normalize a slug to a leading-slash path for display, e.g. "about" -> "/about".
export function slugPath(slug: string): string {
  const s = slug.trim();
  if (!s || s === "/") return "/";
  return "/" + s.replace(/^\/+/, "").replace(/\/+$/, "");
}

// Compose a full URL from a root domain and a slug. Returns null if no domain.
export function composeUrl(
  domain: string | null | undefined,
  slug: string,
): string | null {
  if (!domain) return null;
  const d = domain
    .trim()
    .replace(/^https?:\/\//, "")
    .replace(/\/+$/, "");
  if (!d) return null;
  const path = slugPath(slug);
  return `https://${d}${path === "/" ? "" : path}`;
}

// Single-line truncation helper for note previews.
export function truncate(text: string, max = 80): string {
  const clean = text.replace(/\s+/g, " ").trim();
  return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;
}

// <input type="datetime-local"> bridges. We treat the input value as UTC wall
// clock so it round-trips consistently with formatTimestamp (also UTC-based).
export function toDatetimeLocalUTC(iso: string): string {
  const d = new Date(iso);
  const p = (n: number) => String(n).padStart(2, "0");
  return `${d.getUTCFullYear()}-${p(d.getUTCMonth() + 1)}-${p(
    d.getUTCDate(),
  )}T${p(d.getUTCHours())}:${p(d.getUTCMinutes())}`;
}

export function fromDatetimeLocalUTC(value: string): string {
  // value is "YYYY-MM-DDTHH:mm"; interpret as UTC.
  return new Date(`${value}:00.000Z`).toISOString();
}
