import { cookies } from "next/headers";

/** Cookie the browser writes with its own IANA timezone (see TimezoneCookie). */
export const TIMEZONE_COOKIE = "tz";

function isValidTimezone(tz: unknown): tz is string {
  if (typeof tz !== "string" || !tz) return false;
  try {
    new Intl.DateTimeFormat("en-US", { timeZone: tz });
    return true;
  } catch {
    return false;
  }
}

/**
 * The viewer's timezone as sent by their browser. No default: undefined until
 * the browser has reported it.
 */
export async function getClientTimezone(): Promise<string | undefined> {
  const tz = (await cookies()).get(TIMEZONE_COOKIE)?.value;
  return isValidTimezone(tz) ? tz : undefined;
}
