import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class TransliterateService {
  private apiUrl = 'https://infoways.in/funtelapi/transliterate.php';
  private cache: Record<string, string> = {};

  constructor(private http: HttpClient) {}

  transliterateWord(text: string, lang: string = 'hi'): Observable<string> {
    if (!text.trim()) return of(text);
    
    const cacheKey = `${lang}:${text}`;
    if (this.cache[cacheKey]) {
      return of(this.cache[cacheKey]);
    }

    return this.http.post<any>(this.apiUrl, { text, lang }).pipe(
      map(resp => {
        const result = resp?.result?.[0] || text;
        this.cache[cacheKey] = result;
        return result;
      }),
      catchError(() => of(text)) // Fallback to original text on error
    );
  }
}