import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

const STORAGE_KEY = 'dailymeals.lang';

@Injectable({ providedIn: 'root' })
export class LanguageService {
  constructor(private readonly translate: TranslateService) {}

  init(): void {
    const stored = localStorage.getItem(STORAGE_KEY);
    const lang =
      stored === 'en' || stored === 'pl'
        ? stored
        : navigator.language.toLowerCase().startsWith('pl')
          ? 'pl'
          : 'en';
    this.translate.addLangs(['en', 'pl']);
    this.translate.setFallbackLang('en');
    this.setLanguage(lang);
  }

  setLanguage(lang: 'en' | 'pl'): void {
    this.translate.use(lang);
    localStorage.setItem(STORAGE_KEY, lang);
    document.documentElement.lang = lang;
  }

  currentLanguage(): 'en' | 'pl' {
    const current = this.translate.getCurrentLang();
    return current?.startsWith('pl') ? 'pl' : 'en';
  }
}
