import { Injectable, inject, signal, DOCUMENT } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { firstValueFrom } from 'rxjs';

export type Lang = 'ar' | 'en';

@Injectable({ providedIn: 'root' })
export class LanguageService {
  private translate = inject(TranslateService);
  private document = inject(DOCUMENT);

  currentLang = signal<Lang>(this.getSavedLang());

  init(): Promise<void> {
    const lang = this.currentLang();
    this.applyDirection(lang);
    return firstValueFrom(this.translate.use(lang)).then(() => {});
  }

  setLang(lang: Lang): void {
    this.currentLang.set(lang);
    this.translate.use(lang);
    localStorage.setItem('lang', lang);
    this.applyDirection(lang);
  }

  private applyDirection(lang: Lang): void {
    const html = this.document.documentElement;
    html.setAttribute('lang', lang);
    html.setAttribute('dir', lang === 'ar' ? 'rtl' : 'ltr');

    this.document.body.classList.toggle('rtl', lang === 'ar');
    this.document.body.classList.toggle('ltr', lang !== 'ar');
  }

  toggleLang(): void {
    this.setLang(this.currentLang() === 'ar' ? 'en' : 'ar');
  }

  isRtl(): boolean {
    return this.currentLang() === 'ar';
  }

  private getSavedLang(): Lang {
    return (localStorage.getItem('lang') as Lang) || 'ar';
  }
}
