"use client";

import { useSite } from "./site-context";

/**
 * Formatting that follows the admin's chosen date format.
 *
 * Dates were previously written with hardcoded formats in a dozen places,
 * so the setting existed and changed nothing.
 */
export function formatWith(value: string | number | Date, pattern: string) {
  const d = new Date(value);
  if (Number.isNaN(+d)) return "";

  const pad = (n: number) => String(n).padStart(2, "0");
  const months = [
    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
  ];

  return pattern
    .replace("d", pad(d.getDate()))
    .replace("M", months[d.getMonth()])
    .replace("m", pad(d.getMonth() + 1))
    .replace("Y", String(d.getFullYear()))
    .replace("H", pad(d.getHours()))
    .replace("i", pad(d.getMinutes()));
}

/** The site's date format, applied. */
export function useDateFormat() {
  const { datetimeFormat } = useSite();
  const pattern = datetimeFormat ?? "d/m/Y H:i";

  return {
    /** Date and time. */
    full: (value: string | number | Date) => formatWith(value, pattern),
    /** Date only, dropping the time part of the pattern. */
    date: (value: string | number | Date) =>
      formatWith(value, pattern.replace(/\s*H:i\s*/, "").trim()),
  };
}
