export const formatAcademicYearShort = (
  yearString: string | null | undefined
): string => {
  if (!yearString) return "N/A";

  const match = yearString.match(/(\d{4})-(\d{4})/);
  if (!match) return yearString;

  const startYearShort = match[1].slice(2);
  const endYearShort = match[2].slice(2);

  return `AY ${startYearShort}-${endYearShort}`;
};

export const getEntityValue = (obj: any, entity: string, key: string) => {
  return obj?.[`${entity}__${key}`] ?? obj?.[key] ?? null;
};

export const formatEnquiryDate = (enquiryDate: string) => {
  if (!enquiryDate) return "N/A";
  const date = new Date(enquiryDate);
  return date.toLocaleDateString("en-GB", {
    day: "numeric",
    month: "short",
    year: "numeric",
  });
};

export const formatModifiedDate = (enquiryDate: string) => {
  if (!enquiryDate) return "N/A";

  const date = new Date(enquiryDate);
  const now = new Date();

  // Normalize dates to midnight for comparison
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  const inputDate = new Date(
    date.getFullYear(),
    date.getMonth(),
    date.getDate()
  );

  const diffInDays =
    (today.getTime() - inputDate.getTime()) / (1000 * 60 * 60 * 24);

  // Today → show time
  if (diffInDays === 0) {
    return date.toLocaleTimeString("en-GB", {
      hour: "2-digit",
      minute: "2-digit",
      hour12: true,
    });
  }

  // Yesterday
  if (diffInDays === 1) {
    return "Yesterday";
  }

  // Older → "27 Jun"
  return date.toLocaleDateString("en-GB", {
    day: "numeric",
    month: "short",
  });
};

export const getInitials = (name?: string) => {
  if (!name) return "";

  const parts = name.trim().split(" ");
  const first = parts[0]?.[0] || "";
  const last = parts[1]?.[0] || "";

  return (first + last).toUpperCase();
};
