/**
 * Translation helpers for the React UI.
 *
 * Strings flow through WordPress's standard `wp.i18n` runtime — we don't bundle
 * a separate library. WP injects translations from
 * languages/backreload-{locale}.json into `window.wp.i18n` via
 * the `wp_set_script_translations()` we set up in class-admin.php. If `wp.i18n`
 * is somehow missing (e.g. dev mode without WP), we degrade gracefully by
 * returning the source string.
 *
 * Usage:
 *   import { __, _x, _n } from '@/lib/i18n';
 *   __('Backup now', 'backreload')
 *   _x('Run',    'verb, button label', 'backreload')
 *   _n('%d backup', '%d backups', count, 'backreload')
 *
 * Per WordPress convention, the LAST argument is always the text domain. Our
 * domain is always 'backreload' — but we keep the parameter explicit because
 * `wp i18n make-pot` scans for it when extracting strings.
 */

type WpI18n = {
  __:        (text: string, domain?: string) => string;
  _x:        (text: string, context: string, domain?: string) => string;
  _n:        (single: string, plural: string, number: number, domain?: string) => string;
  _nx:       (single: string, plural: string, number: number, context: string, domain?: string) => string;
  sprintf:   (format: string, ...args: unknown[]) => string;
};

function wp(): WpI18n | null {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const w = (typeof window !== 'undefined' ? (window as any).wp : null);
  return w?.i18n ?? null;
}

export function __(text: string, domain = 'backreload'): string {
  return wp()?.__(text, domain) ?? text;
}

export function _x(text: string, context: string, domain = 'backreload'): string {
  return wp()?._x(text, context, domain) ?? text;
}

export function _n(single: string, plural: string, number: number, domain = 'backreload'): string {
  return wp()?._n(single, plural, number, domain) ?? (number === 1 ? single : plural);
}

export function _nx(single: string, plural: string, number: number, context: string, domain = 'backreload'): string {
  return wp()?._nx(single, plural, number, context, domain) ?? (number === 1 ? single : plural);
}

/** WordPress-flavoured sprintf — used to interpolate values into translated strings. */
export function sprintf(format: string, ...args: unknown[]): string {
  const w = wp();
  if (w?.sprintf) return w.sprintf(format, ...args);
  // Minimal fallback: replace %s / %d in order.
  let i = 0;
  return format.replace(/%[sd]/g, () => String(args[i++] ?? ''));
}
