"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isSupportedTimeZone = isSupportedTimeZone;
exports.formatHumanTimestamp = formatHumanTimestamp;
const catalog_1 = require("./catalog");
const HUMAN_TIMESTAMP_FORMATTER_OPTIONS = {
    timeZoneName: undefined,
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    hour12: false,
    hourCycle: "h23",
};
function isSupportedTimeZone(timeZone) {
    try {
        new Intl.DateTimeFormat("en-US", {
            timeZone,
            year: "numeric",
        }).format(new Date());
        return true;
    }
    catch {
        return false;
    }
}
function formatHumanTimestamp(value, locale = catalog_1.DEFAULT_APP_LOCALE, timeZone = "UTC") {
    const date = value instanceof Date ? value : new Date(value);
    if (Number.isNaN(date.getTime())) {
        return (0, catalog_1.translate)(locale, "common.placeholder.unknown");
    }
    let formatter;
    try {
        formatter = new Intl.DateTimeFormat("en-CA", {
            ...HUMAN_TIMESTAMP_FORMATTER_OPTIONS,
            timeZone,
        });
    }
    catch {
        return (0, catalog_1.translate)(locale, "common.placeholder.unknown");
    }
    const parts = new Map(formatter
        .formatToParts(date)
        .map((part) => [part.type, part.value]));
    const year = parts.get("year");
    const month = parts.get("month");
    const day = parts.get("day");
    const hour = parts.get("hour");
    const minute = parts.get("minute");
    if (year === undefined ||
        month === undefined ||
        day === undefined ||
        hour === undefined ||
        minute === undefined) {
        return (0, catalog_1.translate)(locale, "common.placeholder.unknown");
    }
    const renderedUtcMillis = Date.UTC(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute));
    if (Number.isNaN(renderedUtcMillis)) {
        return (0, catalog_1.translate)(locale, "common.placeholder.unknown");
    }
    const normalizedInputMillis = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes());
    const offsetMinutes = Math.round((renderedUtcMillis - normalizedInputMillis) / 60000);
    return `${year}/${month}/${day} ${hour}:${minute} ${formatUtcOffsetLabel(offsetMinutes)}`;
}
function formatUtcOffsetLabel(offsetMinutes) {
    if (!Number.isFinite(offsetMinutes)) {
        return "UTC";
    }
    if (offsetMinutes === 0) {
        return "UTC+0";
    }
    const sign = offsetMinutes < 0 ? "-" : "+";
    const absoluteMinutes = Math.abs(offsetMinutes);
    const hours = Math.trunc(absoluteMinutes / 60);
    const minutes = absoluteMinutes % 60;
    if (minutes === 0) {
        return `UTC${sign}${hours}`;
    }
    return `UTC${sign}${hours}:${String(minutes).padStart(2, "0")}`;
}
