import { CommonModule } from '@angular/common';
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  HostListener,
  input,
  OnDestroy,
  OnInit,
  output,
} from '@angular/core';

@Component({
  selector: 'app-modal',
  imports: [CommonModule],
  changeDetection: ChangeDetectionStrategy.OnPush,
  templateUrl: './modal.html',
  styleUrl: './modal.css',
})
export class Modal implements OnInit, OnDestroy {
  open = input<boolean>(false);
  title = input<string>('Modifier');
  size = input<'sm' | 'md' | 'lg' | 'xl' | 'xxl'>('md');
  closeOnBackdrop = input<boolean>(true);
  showFooter = input<boolean>(true);

  close = output<void>();

  sizeClass = computed(
    () =>
      ({
        sm: 'max-w-sm',
        md: 'max-w-lg',
        lg: 'max-w-2xl',
        xl: 'max-w-4xl',
        xxl: 'max-w-6xl',
      }[this.size()])
  );

  onBackdrop() {
    if (this.closeOnBackdrop()) this.close.emit();
  }

  ngOnInit() {
    // Scroll lock quand la modale est ouverte
    if (this.open()) document.documentElement.style.overflow = 'hidden';
  }

  ngOnDestroy() {
    document.documentElement.style.overflow = '';
  }

  @HostListener('document:keydown.escape') onEsc() {
    if (this.open()) this.close.emit();
  }
}
