/**
 * Internationalization utilities for Sequensy
 *
 * Wraps WordPress i18n functions with TypeScript types and fallbacks.
 * Uses @wordpress/i18n which is externalized and provided by WordPress.
 */

const DOMAIN = 'sequensy';

/**
 * Check if wp.i18n is available
 */
function isI18nAvailable(): boolean {
  return typeof window !== 'undefined' && !!window.wp?.i18n;
}

/**
 * Translate a string.
 *
 * @param text - Text to translate
 * @returns Translated string
 *
 * @example
 * __('Dashboard') // Returns translated "Dashboard"
 */
export function __(text: string): string {
  if (!isI18nAvailable()) {
    return text;
  }
  return window.wp!.i18n!.__(text, DOMAIN);
}

/**
 * Translate with plural forms.
 *
 * @param single - Singular form
 * @param plural - Plural form
 * @param number - Number to determine form
 * @returns Translated string (singular or plural based on number)
 *
 * @example
 * _n('%d workflow', '%d workflows', count)
 */
export function _n(single: string, plural: string, number: number): string {
  if (!isI18nAvailable()) {
    return number === 1 ? single : plural;
  }
  return window.wp!.i18n!._n(single, plural, number, DOMAIN);
}

/**
 * sprintf for formatted strings with placeholders.
 *
 * @param format - Format string with %s or %d placeholders
 * @param args - Values to substitute
 * @returns Formatted string
 *
 * @example
 * sprintf(__('Welcome, %s'), userName)
 * sprintf(__('%d items selected'), count)
 */
export function sprintf(format: string, ...args: unknown[]): string {
  if (!isI18nAvailable()) {
    // Simple fallback for when wp.i18n is not available
    let result = format;
    args.forEach((arg) => {
      result = result.replace(/%[sd]/, String(arg));
    });
    return result;
  }
  return window.wp!.i18n!.sprintf(format, ...args);
}
