staging-org / ocean-landing-serve / src/ lib/ time-zones.ts

export type Zone = { id: string; city: string; region: string; name: string; offset: string; minutes: number };

// Browsers still list some zones under their old ICU ids, so show the name people search for.
const renamed: Record<string, string> = {
	Asmera: 'Asmara',
	Calcutta: 'Kolkata',
	Faeroe: 'Faroe',
	Godthab: 'Nuuk',
	Katmandu: 'Kathmandu',
	Kiev: 'Kyiv',
	Rangoon: 'Yangon',
	Saigon: 'Ho Chi Minh City'
};

export const canonical = (id: string) => {
	try {
		return new Intl.DateTimeFormat('en-US', { timeZone: id }).resolvedOptions().timeZone;
	} catch {
		return id;
	}
};

const part = (id: string, style: 'longGeneric' | 'shortOffset', at: Date) =>
	new Intl.DateTimeFormat('en-US', { timeZone: id, timeZoneName: style }).formatToParts(at).find((p) => p.type === 'timeZoneName')?.value ?? '';

const describe = (id: string, at: Date): Zone => {
	const segments = id.split('/');
	const raw = part(id, 'shortOffset', at);
	const match = /GMT([+-])(\d{1,2})(?::(\d{2}))?/.exec(raw);
	const minutes = match ? (match[1] === '-' ? -1 : 1) * (Number(match[2]) * 60 + Number(match[3] ?? 0)) : 0;
	return {
		id,
		city: (renamed[segments[segments.length - 1] ?? ''] ?? segments[segments.length - 1] ?? id).replaceAll('_', ' '),
		region: segments.length > 1 ? (segments[0] ?? '') : '',
		name: part(id, 'longGeneric', at),
		offset: raw === 'GMT' ? 'UTC' : raw.replace('GMT', 'UTC').replace('-', '−'),
		minutes
	};
};

// Minutes east of UTC for a zone at a moment, so working hours can be moved between zones across DST.
export const offsetMinutes = (id: string, at: Date) => describe(id, at).minutes;

export const zonesAt = (at: Date) =>
	Intl.supportedValuesOf('timeZone')
		.map((id) => describe(id, at))
		.sort((a, b) => a.minutes - b.minutes || a.city.localeCompare(b.city));

export const matches = (z: Zone, query: string) => {
	const q = query.trim().toLowerCase();
	if (!q) return true;
	return [z.city, z.region, z.name, z.offset, z.id].some((field) => field.toLowerCase().includes(q));
};