import { Directive, ElementRef, Input, OnInit, OnDestroy } from '@angular/core';
import { UiAnimationsService } from './ui-animations.service';

@Directive({
  selector: '[uiAnimate]',
  standalone: true
})
export class AnimateDirective implements OnInit, OnDestroy {
  @Input('uiAnimate') animationClass: string = '';
  @Input() animationTrigger: 'immediate' | 'hover' | 'click' | 'manual' = 'immediate';
  @Input() animationOnce: boolean = false;

  private hoverHandler?: () => void;
  private clickHandler?: () => void;

  constructor(
    private elementRef: ElementRef<HTMLElement>,
    private animationService: UiAnimationsService
  ) {}

  ngOnInit() {
    if (this.animationTrigger === 'immediate') {
      this.animate();
    } else if (this.animationTrigger === 'hover') {
      this.setupHoverTrigger();
    } else if (this.animationTrigger === 'click') {
      this.setupClickTrigger();
    }
  }

  ngOnDestroy() {
    if (this.hoverHandler) {
      this.elementRef.nativeElement.removeEventListener('mouseenter', this.hoverHandler);
    }
    if (this.clickHandler) {
      this.elementRef.nativeElement.removeEventListener('click', this.clickHandler);
    }
  }

  private setupHoverTrigger() {
    this.hoverHandler = () => this.animate();
    this.elementRef.nativeElement.addEventListener('mouseenter', this.hoverHandler);
  }

  private setupClickTrigger() {
    this.clickHandler = () => this.animate();
    this.elementRef.nativeElement.addEventListener('click', this.clickHandler);
  }

  private animate() {
    if (!this.animationClass) return;

    if (this.animationOnce) {
      this.animationService.animateOnce(this.elementRef.nativeElement, this.animationClass);
    } else {
      this.animationService.animate(this.elementRef.nativeElement, this.animationClass);
    }
  }

  /**
   * Manually trigger animation (for manual trigger mode)
   */
  public trigger() {
    this.animate();
  }
}