import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output, Inject } from '@angular/core';
import { CommonModule, DOCUMENT } from '@angular/common';

@Component({
  selector: 'app-header',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './app-header.html',
  styleUrls: ['./app-header.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppHeaderComponent implements OnInit {
  @Input() title = '';
  @Input() subtitle: string | null = null;
  @Input() showLogo = true;
  @Input() logoSrc = 'logo_SALUDUT.png';
  @Input() logoAlt = 'SALUD UT';
  @Input() badgeText: string | null = null;
  @Input() userName: string | null = null;
  @Input() userRole: string | null = null;
  @Input() showUserInfo = false;
  @Input() showLogout = false;
  @Input() logoutLabel = 'Salir';
  @Input() showBack = false;
  @Input() backLabel = 'Volver';
  @Input() showThemeToggle = true;

  @Output() logout = new EventEmitter<void>();
  @Output() back = new EventEmitter<void>();

  isDark = false;

  constructor(
    @Inject(DOCUMENT) private document: Document,
    private cdr: ChangeDetectorRef
  ) {}

  ngOnInit(): void {
    const stored = localStorage.getItem('saludut_theme');
    const isDark = stored === 'dark';
    this.applyTheme(isDark);
  }

  toggleTheme(): void {
    this.applyTheme(!this.isDark);
  }

  private applyTheme(isDark: boolean): void {
    this.isDark = isDark;
    const root = this.document.documentElement;
    if (isDark) {
      root.setAttribute('data-theme', 'dark');
      localStorage.setItem('saludut_theme', 'dark');
    } else {
      root.removeAttribute('data-theme');
      localStorage.setItem('saludut_theme', 'light');
    }
    this.cdr.markForCheck();
  }
}
