export const EASTERN_TIME_ZONE = 'America/New_York';

function parseCalendarDate(dateStr: string): Date {
	const [year, month, day] = dateStr.split('-').map(Number);
	return new Date(Date.UTC(year, month - 1, day, 12));
}

function easternOffset(date: Date): string {
	const utc = new Date(date.toLocaleString('en-US', { timeZone: 'UTC' }));
	const eastern = new Date(date.toLocaleString('en-US', { timeZone: EASTERN_TIME_ZONE }));
	const diffMinutes = Math.round((eastern.getTime() - utc.getTime()) / 60000);
	const sign = diffMinutes <= 0 ? '-' : '+';
	const abs = Math.abs(diffMinutes);
	const hours = String(Math.floor(abs / 60)).padStart(2, '0');
	const minutes = String(abs % 60).padStart(2, '0');
	return `${sign}${hours}${minutes}`;
}

export function formatPostDate(dateStr: string): string {
	if (!dateStr) return '';
	return parseCalendarDate(dateStr).toLocaleDateString('en-US', {
		year: 'numeric',
		month: 'long',
		day: 'numeric',
		timeZone: EASTERN_TIME_ZONE
	});
}

export function formatRssDate(dateStr: string): string {
	if (!dateStr) return '';
	const anchored = parseCalendarDate(dateStr);
	const parts = new Intl.DateTimeFormat('en-US', {
		timeZone: EASTERN_TIME_ZONE,
		weekday: 'short',
		day: '2-digit',
		month: 'short',
		year: 'numeric',
		hour: '2-digit',
		minute: '2-digit',
		second: '2-digit',
		hour12: false
	}).formatToParts(anchored);

	const get = (type: string) => parts.find((part) => part.type === type)?.value ?? '';

	return `${get('weekday')}, ${get('day')} ${get('month')} ${get('year')} ${get('hour')}:${get('minute')}:${get('second')} ${easternOffset(anchored)}`;
}
