import { Component, Inject, PLATFORM_ID } from '@angular/core';
import { Router, RouterOutlet } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { StorageService } from './shared/services/storage.service';
import { isPlatformBrowser } from '@angular/common';
import { directions, supportedLanguages } from './utils/enums';
import { LoaderComponent } from './shared/components/loader/loader.component';
import { NotificationsComponent } from './shared/components/notifications/notifications.component';

@Component({
  selector: 'app-root',
  imports: [RouterOutlet, LoaderComponent, NotificationsComponent],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss'
})
export class AppComponent {
  direction: any;
  title = 'aConnect';

  constructor(
    private translateService: TranslateService,
    private storageService: StorageService,
    private router: Router,
    @Inject(PLATFORM_ID) private platformId: object
  ) { }

  ngOnInit() {
    if (!isPlatformBrowser(this.platformId)) return;

    const currentLanguage = this.storageService.getItem('language') || supportedLanguages.ENGLISH;
    this.storageService.setItem('language', currentLanguage);
    this.translateService.setDefaultLang(currentLanguage);
    this.translateService.use(currentLanguage);

    this.direction = this.storageService.getItem('direction') || directions.LTR;
    this.storageService.setItem('direction', this.direction);

  //    if (typeof document !== 'undefined') {
  //   document.documentElement.setAttribute('dir', this.direction);
  // }

    const userStr = this.storageService.getItem('user');
    if (userStr) {
      try {
        const data = JSON.parse(userStr);
        if (data?.token) {
          if (this.router.url === '/' || this.router.url === '/login') {
            this.router.navigate(['/home/dashboard']);
          }
        } else {
          if (this.router.url === '/') {
            this.router.navigate(['/login']);
          }
        }
      } catch {
        this.storageService.removeItem('user');
        if (this.router.url === '/') {
          this.router.navigate(['/login']);
        }
      }
    } else {
      if (this.router.url === '/') {
        this.router.navigate(['/login']);
      }
    }
  }
}
