const resolveBrowserTimezone = () => {
  try {
    return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
  } catch {
    return "UTC";
  }
};

let globalTimezone = resolveBrowserTimezone();

export const setGlobalTimezone = (timezone?: string | null) => {
  globalTimezone = timezone?.trim() || resolveBrowserTimezone();
};

export const getGlobalTimezone = () => globalTimezone;

export const formatWithGlobalTimezone = (
  value: string | number | Date,
  options?: Intl.DateTimeFormatOptions,
  locale = "en-US",
) => {
  const date = value instanceof Date ? value : new Date(value);
  if (Number.isNaN(date.getTime())) return "-";
  return new Intl.DateTimeFormat(locale, {
    timeZone: globalTimezone,
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    ...options,
  }).format(date);
};
