import type { Locale } from '@/lib/i18n';
import { civilDateInZone } from '@platform-modules/util/datetime';

export const TZ = 'Asia/Jerusalem';

/**
 * Current Date in Israel timezone.
 * Workaround: new Date().toLocaleString trick avoids UTC wrong-day bugs.
 */
export function nowInIsrael(): Date {
  return new Date(new Date().toLocaleString('en-US', { timeZone: TZ }));
}

/** Current weekday index in Israel (0=Sunday ... 6=Saturday). */
export function israelWeekdayIndex(): number {
  return nowInIsrael().getDay();
}

/** Format a Date as "YYYY-MM-DD" in Israel timezone. */
export function toIsraelDateString(date: Date): string {
  return civilDateInZone(date, TZ);
}

/** Format a date with locale-aware month/year names in Israel timezone. */
export function formatDateLocale(
  date: Date | string,
  locale: Locale = 'he',
  options: Intl.DateTimeFormatOptions = { day: 'numeric', month: 'long', year: 'numeric' },
): string {
  const d = typeof date === 'string' ? new Date(date) : date;
  return new Intl.DateTimeFormat(locale === 'he' ? 'he-IL' : 'en-US', {
    timeZone: TZ,
    ...options,
  }).format(d);
}

/** Format as 'יוני 2026' / 'June 2026' — for earnings/purchases month columns. */
export function formatMonthYear(date: Date | string, locale: Locale = 'he'): string {
  return formatDateLocale(date, locale, { month: 'long', year: 'numeric' });
}

/** Convert ISO string → datetime-local input value in Israel TZ (fixes UTC seeding bug). */
export function isoToLocalDatetimeInput(isoString: string): string {
  const d = new Date(isoString);
  const datePart = new Intl.DateTimeFormat('sv', { timeZone: TZ }).format(d);
  const timePart = new Intl.DateTimeFormat('en-US', {
    timeZone: TZ,
    hour: '2-digit',
    minute: '2-digit',
    hour12: false,
  }).format(d);
  return (datePart + 'T' + timePart).slice(0, 16);
}
