import { DOCUMENT } from '@angular/common';
import { Component, Inject, OnDestroy, OnInit } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';

@Component({
  selector: 'app-profil',
  templateUrl: './profil.component.html',
  styleUrls: ['./profil.component.scss'],
})
export class ProfilComponent implements OnInit, OnDestroy {

  constructor(
    public dialog: MatDialog,
    public dialogRef: MatDialogRef<ProfilComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any,
    @Inject(DOCUMENT) private document: Document
  ) {}

  ngOnInit(): void {
    // Utiliser les données injectées si disponibles, sinon localStorage
    if (this.data && Object.keys(this.data).length > 0) {
      console.log('Using injected data:', this.data);
    } else {
      // Fallback sur localStorage
      const user = localStorage.getItem('__user');
      if (user) {
        try {
          const userData = JSON.parse(user);
          console.log('Raw localStorage data:', userData);

          // Si les données sont dans infoUser, on utilise ça, sinon on prend les données directement
          if (userData.infoUser) {
            this.data = userData.infoUser;
            console.log('Using infoUser data:', this.data);
          } else {
            this.data = userData;
            console.log('Using direct user data:', this.data);
          }
        } catch (error) {
          console.error('Error parsing user data:', error);
          this.data = {};
        }
      } else {
        console.log('No user data found in localStorage');
        this.data = {};
      }
    }

    this.document.body.classList.add('pop-in');
  }

  ngOnDestroy() {
    this.document.body.classList.remove('pop-in');
  }

  generateAvatar(name: string): string {
    if (!name) return 'U';
    return name
      .split(' ')
      .map(word => word.charAt(0))
      .join('')
      .toUpperCase()
      .substring(0, 2);
  }

  closeProfile(): void {
    this.dialogRef.close();
  }

  editProfile(): void {
    console.log('Opening edit profile...');
    alert('Modification du profil : Interface de modification bientôt disponible !');
  }

  openSettings(): void {
    console.log('Opening settings...');
    alert('Paramètres utilisateur : Interface de configuration en préparation !');
  }
}
