import { Component, inject, OnInit, RendererFactory2, Renderer2 } from '@angular/core';
import { RouterOutlet, Router, NavigationEnd  } from '@angular/router';
import { TranslateService, LangChangeEvent } from '@ngx-translate/core';
import dayjs from 'dayjs/esm';
import { filter } from 'rxjs/operators';
import { CommonModule } from '@angular/common'; // Add this!

import { AccountService } from 'app/core/auth/account.service';
import { AppPageTitleStrategy } from 'app/app-page-title-strategy';
import FooterComponent from '../footer/footer.component';
import PageRibbonComponent from '../profiles/page-ribbon.component';
import { BannerComponent } from './banner/banner.component';

@Component({
  standalone: true,
  selector: 'jhi-main',
  templateUrl: './main.component.html',
  styleUrl: './main.component.css',
  providers: [AppPageTitleStrategy],
  imports: [RouterOutlet, FooterComponent, PageRibbonComponent, CommonModule, BannerComponent],
})
export default class MainComponent implements OnInit {
  private renderer: Renderer2;

  private router = inject(Router);
  private appPageTitleStrategy = inject(AppPageTitleStrategy);
  private accountService = inject(AccountService);
  private translateService = inject(TranslateService);
  private rootRenderer = inject(RendererFactory2);

  showBanner = false;

  constructor() {
    this.renderer = this.rootRenderer.createRenderer(document.querySelector('html'), null);
  }

  ngOnInit(): void {
    // try to log in automatically
    this.accountService.identity().subscribe();

    this.translateService.onLangChange.subscribe((langChangeEvent: LangChangeEvent) => {
      this.appPageTitleStrategy.updateTitle(this.router.routerState.snapshot);
      dayjs.locale(langChangeEvent.lang);
      this.renderer.setAttribute(document.querySelector('html'), 'lang', langChangeEvent.lang);
    });

    this.router.events
      .pipe(filter(event => event instanceof NavigationEnd))
      .subscribe((event) => {
        const navEndEvent = event as NavigationEnd; // Explicitly tell TypeScript
        const isLoggedIn = this.accountService.isAuthenticated();
        
        // List of routes where the banner should be shown
        const bannerRoutes = ['/'];

        // Check if current route matches one of the bannerRoutes
        // For this to work, CSS was needed. See main.component.css
        this.showBanner = bannerRoutes.some(route => this.router.url === route);
      });
  }
}
