export function localMinuteOfDay(now, timezone) {
    try {
        const parts = new Intl.DateTimeFormat("en-US", {
            timeZone: timezone,
            hour: "2-digit",
            minute: "2-digit",
            hourCycle: "h23",
        }).formatToParts(now);
        const hour = Number(parts.find((p) => p.type === "hour")?.value);
        const minute = Number(parts.find((p) => p.type === "minute")?.value);
        if (!Number.isFinite(hour) || !Number.isFinite(minute))
            return null;
        return hour * 60 + minute;
    }
    catch {
        return null;
    }
}
export function inWindow(minute, start, end) {
    if (start === end)
        return false;
    if (start < end)
        return minute >= start && minute < end;
    return minute >= start || minute < end;
}
export function windowEndsAt(now, minute, end) {
    const minutesLeft = (end - minute + 1440) % 1440;
    return new Date(now.getTime() + minutesLeft * 60_000);
}
export function evaluateGate(prefs, category, now) {
    if (!prefs)
        return { kind: "pass" };
    if (!prefs.enabled)
        return { kind: "muted" };
    if (prefs.muted_categories.includes(category))
        return { kind: "muted" };
    if (prefs.quiet_start === null || prefs.quiet_end === null || !prefs.timezone) {
        return { kind: "pass" };
    }
    const minute = localMinuteOfDay(now, prefs.timezone);
    if (minute === null)
        return { kind: "pass" };
    if (!inWindow(minute, prefs.quiet_start, prefs.quiet_end))
        return { kind: "pass" };
    return { kind: "deferred", until: windowEndsAt(now, minute, prefs.quiet_end) };
}
