import { Injectable, inject, signal } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import {LocalStoreConstants} from '../constants/LocalStoreConstants';

type Lang = 'de' | 'en';

@Injectable({ providedIn: 'root' })
export class LanguageService {
  private readonly translate = inject(TranslateService);
  readonly lang = signal<Lang>(this.getInitial());

  constructor() {
    // translate service lang and fallback are already configured via provideTranslateService in app.config
    // just ensure the stored preference is active on startup
    this.translate.use(this.lang());
  }

  use(l: Lang) {
    this.lang.set(l);
    this.translate.use(l);
    try { localStorage.setItem(LocalStoreConstants.LANGUAGE_KEY, l); } catch (e) { void e; }
  }

  private getInitial(): Lang {
    try {
      const stored = localStorage.getItem(LocalStoreConstants.LANGUAGE_KEY) as Lang | null;
      if (stored === 'de' || stored === 'en') return stored;
    } catch (e) { void e; }
    const browser = (navigator.language || 'en').toLowerCase();
    return browser.startsWith('de') ? 'de' : 'en';
  }
}
