import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LanguageService {
  private availableLanguages = [
    { code: 'en', name: 'English', nativeName: 'English', dbValue: 'english' },
    { code: 'hi', name: 'Hindi', nativeName: 'हिन्दी', dbValue: 'hindi' },
    { code: 'mr', name: 'Marathi', nativeName: 'मराठी', dbValue: 'marathi' },
    { code: 'bn', name: 'Bangla', nativeName: 'বাংলা', dbValue: 'bengali' },
    { code: 'ta', name: 'Tamil', nativeName: 'தமிழ்', dbValue: 'tamil' },
    { code: 'te', name: 'Telugu', nativeName: 'తెలుగు', dbValue: 'telugu' }
  ];

  private currentLanguage = new BehaviorSubject<string>('en');
  currentLanguage$ = this.currentLanguage.asObservable();

  constructor() {
    // Local storage se saved language load karein
    const savedLang = localStorage.getItem('preferredLanguage');
    if (savedLang) {
      this.currentLanguage.next(savedLang);
    }
  }

  getAvailableLanguages() {
    return this.availableLanguages;
  }

  getCurrentLanguage() {
    return this.currentLanguage.value;
  }

  getCurrentLanguageForDB(): string {
    const lang = this.availableLanguages.find(l => l.code === this.currentLanguage.value);
    return lang ? lang.dbValue : 'english';
  }

  setLanguage(langCode: string) {
    this.currentLanguage.next(langCode);
    localStorage.setItem('preferredLanguage', langCode);
  }

  getLanguageName(langCode: string): string {
    const lang = this.availableLanguages.find(l => l.code === langCode);
    return lang ? lang.name : 'English';
  }

  // Database value se code find karne ke liye
  getCodeFromDBValue(dbValue: string): string {
    const lang = this.availableLanguages.find(l => l.dbValue === dbValue.toLowerCase());
    return lang ? lang.code : 'en';
  }
}
