/**
 * Internationalization: message dictionary (en/ru) and pure translation helpers.
 * Ported from webapp/js/i18n.js. Language is read from window.__DT_LANG (backend config).
 */

export type Lang = "ru" | "en";

export const MESSAGES: Record<Lang, Record<string, string>> = {
  en: {
    "app.title": "Duty Calendar",
    loading: "Loading…",
    access_denied: "Access denied.",
    error_load_failed: "Load failed",
    error_network: "Could not load data. Check your connection.",
    error_generic: "Could not load data.",
    "error.retry": "Retry",
    "nav.prev_month": "Previous month",
    "nav.next_month": "Next month",
    "weekdays.mon": "Mon",
    "weekdays.tue": "Tue",
    "weekdays.wed": "Wed",
    "weekdays.thu": "Thu",
    "weekdays.fri": "Fri",
    "weekdays.sat": "Sat",
    "weekdays.sun": "Sun",
    "month.jan": "January",
    "month.feb": "February",
    "month.mar": "March",
    "month.apr": "April",
    "month.may": "May",
    "month.jun": "June",
    "month.jul": "July",
    "month.aug": "August",
    "month.sep": "September",
    "month.oct": "October",
    "month.nov": "November",
    "month.dec": "December",
    "aria.duty": "On duty",
    "aria.unavailable": "Unavailable",
    "aria.vacation": "Vacation",
    "aria.day_info": "Day info",
    "event_type.duty": "Duty",
    "event_type.unavailable": "Unavailable",
    "event_type.vacation": "Vacation",
    "event_type.other": "Other",
    "duty.now_on_duty": "On duty now",
    "duty.none_this_month": "No duties this month.",
    "duty.none_this_month_hint": "Duties will appear after the schedule is loaded.",
    "duty.today": "Today",
    "duty.until": "until {time}",
    "hint.from": "from",
    "hint.to": "until",
    "hint.duty_title": "Duty:",
    "hint.events": "Events:",
    "day_detail.close": "Close",
    "day_detail.no_events": "No duties or events this day.",
    "contact.label": "Contact",
    "contact.show": "Contacts",
    "contact.back": "Back",
    "contact.phone": "Phone",
    "contact.telegram": "Telegram",
    "contact.aria_call": "Call {name}",
    "contact.aria_telegram": "Message {name} on Telegram",
    "current_duty.title": "Current Duty",
    "current_duty.no_duty": "No one is on duty right now",
    "current_duty.shift": "Shift",
    "current_duty.shift_tz": "Shift ({tz}):",
    "current_duty.shift_local": "Shift (your time):",
    "current_duty.remaining": "Remaining: {hours}h {minutes}min",
    "current_duty.remaining_label": "Remaining",
    "current_duty.remaining_value": "{hours}h {minutes}min",
    "current_duty.ends_at": "Until end of shift at {time}",
    "current_duty.back": "Back to calendar",
    "current_duty.close": "Close",
    "current_duty.open_calendar": "Open calendar",
    "current_duty.contact_info_not_set": "Contact info not set",
    "error_boundary.message": "Something went wrong.",
    "error_boundary.description": "An unexpected error occurred. Try reloading the app.",
    "error_boundary.reload": "Reload",
    "not_found.title": "Page not found",
    "not_found.description": "The page you are looking for does not exist.",
    "not_found.open_calendar": "Open calendar",
    "access_denied.hint": "Open the app again from Telegram.",
  },
  ru: {
    "app.title": "Календарь дежурств",
    loading: "Загрузка…",
    access_denied: "Доступ запрещён.",
    error_load_failed: "Ошибка загрузки",
    error_network: "Не удалось загрузить данные. Проверьте интернет.",
    error_generic: "Не удалось загрузить данные.",
    "error.retry": "Повторить",
    "nav.prev_month": "Предыдущий месяц",
    "nav.next_month": "Следующий месяц",
    "weekdays.mon": "Пн",
    "weekdays.tue": "Вт",
    "weekdays.wed": "Ср",
    "weekdays.thu": "Чт",
    "weekdays.fri": "Пт",
    "weekdays.sat": "Сб",
    "weekdays.sun": "Вс",
    "month.jan": "Январь",
    "month.feb": "Февраль",
    "month.mar": "Март",
    "month.apr": "Апрель",
    "month.may": "Май",
    "month.jun": "Июнь",
    "month.jul": "Июль",
    "month.aug": "Август",
    "month.sep": "Сентябрь",
    "month.oct": "Октябрь",
    "month.nov": "Ноябрь",
    "month.dec": "Декабрь",
    "aria.duty": "Дежурные",
    "aria.unavailable": "Недоступен",
    "aria.vacation": "Отпуск",
    "aria.day_info": "Информация о дне",
    "event_type.duty": "Дежурство",
    "event_type.unavailable": "Недоступен",
    "event_type.vacation": "Отпуск",
    "event_type.other": "Другое",
    "duty.now_on_duty": "Сейчас дежурит",
    "duty.none_this_month": "В этом месяце дежурств нет.",
    "duty.none_this_month_hint": "Дежурства появятся после загрузки расписания.",
    "duty.today": "Сегодня",
    "duty.until": "до {time}",
    "hint.from": "с",
    "hint.to": "до",
    "hint.duty_title": "Дежурство:",
    "hint.events": "События:",
    "day_detail.close": "Закрыть",
    "day_detail.no_events": "В этот день нет дежурств и событий.",
    "contact.label": "Контакт",
    "contact.show": "Контакты",
    "contact.back": "Назад",
    "contact.phone": "Телефон",
    "contact.telegram": "Telegram",
    "contact.aria_call": "Позвонить {name}",
    "contact.aria_telegram": "Написать {name} в Telegram",
    "current_duty.title": "Сейчас дежурит",
    "current_duty.no_duty": "Сейчас никто не дежурит",
    "current_duty.shift": "Смена",
    "current_duty.shift_tz": "Смена ({tz}):",
    "current_duty.shift_local": "Смена (ваше время):",
    "current_duty.remaining": "Осталось: {hours}ч {minutes}мин",
    "current_duty.remaining_label": "Осталось",
    "current_duty.remaining_value": "{hours}ч {minutes}мин",
    "current_duty.ends_at": "До конца смены в {time}",
    "current_duty.back": "Назад к календарю",
    "current_duty.close": "Закрыть",
    "current_duty.open_calendar": "Открыть календарь",
    "current_duty.contact_info_not_set": "Контактные данные не указаны",
    "error_boundary.message": "Что-то пошло не так.",
    "error_boundary.description": "Произошла непредвиденная ошибка. Попробуйте перезагрузить приложение.",
    "error_boundary.reload": "Обновить",
    "not_found.title": "Страница не найдена",
    "not_found.description": "Запрашиваемая страница не существует.",
    "not_found.open_calendar": "Открыть календарь",
    "access_denied.hint": "Откройте приложение снова из Telegram.",
  },
};

const MONTH_KEYS = [
  "month.jan",
  "month.feb",
  "month.mar",
  "month.apr",
  "month.may",
  "month.jun",
  "month.jul",
  "month.aug",
  "month.sep",
  "month.oct",
  "month.nov",
  "month.dec",
];

const WEEKDAY_KEYS = [
  "weekdays.mon",
  "weekdays.tue",
  "weekdays.wed",
  "weekdays.thu",
  "weekdays.fri",
  "weekdays.sat",
  "weekdays.sun",
];

/**
 * Normalize language code to 'ru' or 'en'.
 */
export function normalizeLang(code: string | null | undefined): Lang {
  if (!code || typeof code !== "string") return "en";
  const lower = code.toLowerCase();
  if (lower.startsWith("ru")) return "ru";
  return "en";
}

/**
 * Get application language from backend config (window.__DT_LANG).
 * Set by /app/config.js from DEFAULT_LANGUAGE. Fallback to 'en' if missing or invalid.
 * Only valid in browser; returns 'en' when window is undefined (SSR).
 */
export function getLang(): Lang {
  if (typeof window === "undefined") return "en";
  const raw =
    (window as unknown as { __DT_LANG?: string }).__DT_LANG != null
      ? String((window as unknown as { __DT_LANG?: string }).__DT_LANG)
      : "";
  const lang = normalizeLang(raw);
  return lang === "ru" ? "ru" : "en";
}

function tEventType(lang: Lang, key: string): string {
  const dict = MESSAGES[lang] ?? MESSAGES.en;
  const enDict = MESSAGES.en;
  let s = dict[key];
  if (s === undefined) s = enDict[key];
  if (s === undefined) {
    s =
      dict["event_type.other"] ??
      enDict["event_type.other"] ??
      enDict["event_type.duty"] ??
      key;
  }
  return s;
}

/**
 * Get translated string; fallback to en if key missing in lang. Supports {placeholder}.
 */
export function translate(
  lang: Lang,
  key: string,
  params: Record<string, string> = {}
): string {
  const dict = MESSAGES[lang] ?? MESSAGES.en;
  let s = dict[key];
  if (s === undefined) s = MESSAGES.en[key];
  if (s === undefined && key.startsWith("event_type.")) {
    return tEventType(lang, key);
  }
  if (s === undefined) return key;
  for (const k of Object.keys(params)) {
    s = s.split(`{${k}}`).join(params[k]);
  }
  return s;
}

/**
 * Get month name by 0-based index (0–11).
 */
export function monthName(lang: Lang, month: number): string {
  const key = MONTH_KEYS[month];
  return key ? translate(lang, key) : "";
}

/**
 * Get weekday short labels (Mon–Sun order) for given lang.
 */
export function weekdayLabels(lang: Lang): string[] {
  return WEEKDAY_KEYS.map((k) => translate(lang, k));
}
