import { app } from 'electron';
import type { FormatPrefs } from '../store';

export function detectFormatPrefs(): FormatPrefs {
  const locale = app.getLocale();
  const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  const hour12 = Intl.DateTimeFormat(locale, { hour: 'numeric' }).resolvedOptions().hour12;
  const timeFormat = hour12 ? '12h' : '24h';
  const dateFormat = inferDateFormat(locale);
  return { timezone, timeFormat, dateFormat };
}

export function detectLanguage(): string {
  const locale = app.getLocale(); // e.g. 'it-IT', 'en-US'
  try {
    const display = new Intl.DisplayNames([locale], { type: 'language' });
    return display.of(locale) ?? locale;
  } catch {
    return locale;
  }
}

function inferDateFormat(locale: string): string {
  // MDY locales
  const mdyLocales = ['en-US', 'en-PH', 'en-BZ'];
  if (mdyLocales.some((l) => locale.startsWith(l))) return 'MM/dd/yyyy';
  // YMD locales (CJK, ISO-oriented)
  const ymdPrefixes = ['ja', 'zh', 'ko', 'hu', 'lt', 'sv', 'fi'];
  if (ymdPrefixes.some((p) => locale.startsWith(p))) return 'yyyy-MM-dd';
  // Default: DMY (most of the world)
  return 'dd/MM/yyyy';
}
