import { Pipe, PipeTransform, inject } from '@angular/core';
import { TranslateService } from './translate.service';
import { LanguageService } from '../services/language.service';

/**
 * Stays impure (must re-run every CD cycle so a live language switch
 * updates every binding without touching hundreds of `| translate`
 * template call sites to pass the language explicitly as a pure-pipe
 * argument). Memoized per-instance instead: repeat calls with the same
 * key/params/language - the overwhelming majority of CD cycles, since
 * nothing actually changed - hit a Map lookup instead of re-walking the
 * translation tree and re-running the interpolation regex.
 */
/** Bindings with volatile params (pagination counts, etc.) would otherwise grow this cache for the component's whole lifetime. */
const MAX_CACHE_ENTRIES = 50;

@Pipe({
  name: 'translate',
  pure: false,
})
export class TranslatePipe implements PipeTransform {
  private translateService = inject(TranslateService);
  private langService = inject(LanguageService);

  private lastLang = '';
  private readonly cache = new Map<string, string>();

  transform(key: string, params?: Record<string, string | number>): string {
    const lang = this.langService.currentLanguage();
    if (lang !== this.lastLang) {
      this.lastLang = lang;
      this.cache.clear();
    }

    const cacheKey = params ? `${key}::${JSON.stringify(params)}` : key;
    const cached = this.cache.get(cacheKey);
    if (cached !== undefined) {
      return cached;
    }

    const result = this.translateService.t(key, params);
    if (this.cache.size >= MAX_CACHE_ENTRIES) {
      this.cache.clear();
    }
    this.cache.set(cacheKey, result);
    return result;
  }
}
