export type ZonedDateParts = { year: number; month: number; day: number; hour: number };

export function zonedDateParts(date = new Date(), timeZone = "Asia/Dhaka"): ZonedDateParts {
  const parts = new Intl.DateTimeFormat("en-CA", {
    timeZone,
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    hourCycle: "h23",
  }).formatToParts(date);
  const value = (type: Intl.DateTimeFormatPartTypes) => Number(parts.find((part) => part.type === type)?.value ?? 0);
  return { year: value("year"), month: value("month"), day: value("day"), hour: value("hour") };
}

export function localIsoDate(date = new Date(), timeZone = "Asia/Dhaka") {
  const { year, month, day } = zonedDateParts(date, timeZone);
  return `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
}

export function greetingFor(date = new Date(), timeZone = "Asia/Dhaka") {
  const { hour } = zonedDateParts(date, timeZone);
  if (hour < 12) return "Good morning";
  if (hour < 17) return "Good afternoon";
  return "Good evening";
}

export function formatInTimeZone(date: Date, timeZone = "Asia/Dhaka", options: Intl.DateTimeFormatOptions = {}) {
  return new Intl.DateTimeFormat("en", { timeZone, ...options }).format(date);
}
