export type DayBucket = 'today' | 'yesterday' | 'thisWeek' | 'older';

const DAY_MS = 24 * 60 * 60 * 1000;
const SUNDAY_START_LOCALES = new Set(['en-us', 'en-ca', 'en-ph', 'ja-jp', 'he-il', 'pt-br']);

function weekStartDay(locale?: string): 0 | 1 {
	if (!locale) return 1;
	return SUNDAY_START_LOCALES.has(locale.toLowerCase()) ? 0 : 1;
}

function startOfDay(d: Date): Date {
	const x = new Date(d);
	x.setHours(0, 0, 0, 0);
	return x;
}

function startOfWeek(d: Date, firstDay: 0 | 1): Date {
	const x = startOfDay(d);
	const diff = (x.getDay() - firstDay + 7) % 7;
	x.setDate(x.getDate() - diff);
	return x;
}

export function bucketByDay(date: Date, now: Date = new Date(), locale?: string): DayBucket {
	const today = startOfDay(now);
	const target = startOfDay(date);

	if (target.getTime() === today.getTime()) return 'today';
	if (today.getTime() - target.getTime() <= DAY_MS) return 'yesterday';

	const weekStart = startOfWeek(today, weekStartDay(locale));
	if (target.getTime() >= weekStart.getTime()) return 'thisWeek';

	return 'older';
}
