// src/app/app.ts
import { Component, Inject, PLATFORM_ID } from '@angular/core';
import { Router, NavigationEnd, RouterOutlet } from '@angular/router';
import { CommonModule, isPlatformBrowser } from '@angular/common';

import { Header } from './components/header/header';
import { FooterComponent } from './components/footer/footer';
import { AuthService } from './services/auth.service';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [
    CommonModule,
    RouterOutlet,
    Header,
    FooterComponent
  ],
  templateUrl: './app.html',
  styleUrls: ['./app.scss'],
})
export class AppComponent {
  isFullScreenPage = false;
  hideFooter = false;

  // ✅ páginas que devem esconder header/footer (tela cheia)
  private readonly fullScreenRoutes = ['/login', '/register'];

  // ✅ rotas internas (LOGADO) que devem esconder footer
  private readonly loggedPrefixes = [
    '/geral',
    '/mureg',
    '/faturamento',
    '/dadosusuarios',
    '/vigencia',
    '/trocanumero',
    '/dashboard', // ✅ ADICIONADO: esconde footer na página de dashboard
    '/notificacoes',
    '/chips-controle-recebidos',
    '/resumo',
    '/parcelamentos',
    '/historico',
    '/perfil',
    '/system',
  ];

  constructor(
    private router: Router,
    private authService: AuthService,
    @Inject(PLATFORM_ID) private platformId: object
  ) {
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        const rawUrl = event.urlAfterRedirects || event.url;

        // remove query/hash e barra final
        let url = rawUrl.split('?')[0].split('#')[0];
        url = url.replace(/\/+$/, '');

        this.isFullScreenPage = this.fullScreenRoutes.includes(url);

        const isLoggedRoute = this.loggedPrefixes.some(
          (p) => url === p || url.startsWith(p + '/')
        );

        // ✅ footer some ao logar + também no login/register
        this.hideFooter = isLoggedRoute || this.isFullScreenPage;

        // Em SSR não existe storage do navegador.
        if (!isPlatformBrowser(this.platformId)) return;

        if (isLoggedRoute && !this.hasValidSession()) {
          this.router.navigateByUrl('/login');
        }
      }
    });
  }

  private hasValidSession(): boolean {
    const token = this.authService.token;
    if (!token) return false;

    const payload = this.authService.getTokenPayload();
    const tenantId = payload?.['tenantId'] ?? payload?.['tenant'] ?? payload?.['TenantId'];
    if (!tenantId) {
      this.authService.logout();
      return false;
    }

    return true;
  }
}

export { AppComponent as App };
