/**
 * i18n utility for Vareon Calculator Suite
 * Provides translation functions that work with WordPress i18n system
 * Strings are passed from PHP via VAREONCALC_CFG.i18n
 */

/**
 * Get translated string
 * @param {string} text - The string to translate
 * @param {string} domain - Text domain (unused but kept for compatibility)
 * @returns {string} Translated string or original if not found
 */
export function __(text, domain = 'vareon-calculator-suite-lite') {
  // First check if wp.i18n is available (in admin/editor context)
  if (typeof wp !== 'undefined' && wp.i18n && typeof wp.i18n.__ === 'function') {
    return wp.i18n.__(text, domain);
  }
  
  // Fall back to VAREONCALC_CFG.i18n strings passed from PHP
  if (typeof VAREONCALC_CFG !== 'undefined' && VAREONCALC_CFG.i18n) {
    const key = text.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '');
    if (VAREONCALC_CFG.i18n[key]) {
      return VAREONCALC_CFG.i18n[key];
    }
    // Try direct key match
    if (VAREONCALC_CFG.i18n[text]) {
      return VAREONCALC_CFG.i18n[text];
    }
  }
  
  // Return original string if no translation found
  return text;
}

/**
 * Get translated string with context
 * @param {string} text - The string to translate
 * @param {string} context - Context for translators
 * @param {string} domain - Text domain
 * @returns {string} Translated string
 */
export function _x(text, context, domain = 'vareon-calculator-suite-lite') {
  if (typeof wp !== 'undefined' && wp.i18n && typeof wp.i18n._x === 'function') {
    return wp.i18n._x(text, context, domain);
  }
  return __(text, domain);
}

/**
 * Get translated singular/plural string
 * @param {string} single - Singular form
 * @param {string} plural - Plural form  
 * @param {number} number - Count to determine form
 * @param {string} domain - Text domain
 * @returns {string} Appropriate form based on count
 */
export function _n(single, plural, number, domain = 'vareon-calculator-suite-lite') {
  if (typeof wp !== 'undefined' && wp.i18n && typeof wp.i18n._n === 'function') {
    return wp.i18n._n(single, plural, number, domain);
  }
  return number === 1 ? single : plural;
}

/**
 * Sprintf-style string formatting
 * @param {string} format - Format string with %s, %d placeholders
 * @param {...*} args - Replacement values
 * @returns {string} Formatted string
 */
export function sprintf(format, ...args) {
  if (typeof wp !== 'undefined' && wp.i18n && typeof wp.i18n.sprintf === 'function') {
    return wp.i18n.sprintf(format, ...args);
  }
  
  let i = 0;
  return format.replace(/%[sd]/g, () => {
    const val = args[i++];
    return val !== undefined ? String(val) : '';
  });
}

