import { Component, OnInit, OnDestroy, AfterViewInit, ViewChild, ElementRef, PLATFORM_ID, Inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

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

  @ViewChild('riveCanvas', { static: false }) riveCanvas: ElementRef<HTMLCanvasElement>;

  private riveInstance: any;
  private isBrowser: boolean;
  private mouseMoveListener: any;
  private resizeListener: any;

  constructor(@Inject(PLATFORM_ID) private platformId: Object) {
    this.isBrowser = isPlatformBrowser(this.platformId);
  }

  ngOnInit(): void {
    // Component initialization
  }

  ngAfterViewInit(): void {
    // Only initialize Rive in browser environment
    if (this.isBrowser) {
      this.initializeRive();
    }
  }

  ngOnDestroy(): void {
    // Remove event listeners
    if (this.mouseMoveListener) {
      window.removeEventListener('mousemove', this.mouseMoveListener);
    }
    if (this.resizeListener) {
      window.removeEventListener('resize', this.resizeListener);
    }

    // Clean up Rive instance
    if (this.riveInstance) {
      this.riveInstance.cleanup();
      this.riveInstance = null;
    }
  }

  /**
   * Initialize Rive animation with State Machine
   * Animation file has: Timeline 1, UnNear, Near animations
   * State Machine 1 with Boolean input: Mouse Enter
   */
  private async initializeRive(): Promise<void> {
    try {
      // Dynamically import Rive to avoid SSR issues
      const { Rive } = await import('@rive-app/canvas');

      const canvas = this.riveCanvas.nativeElement;
      console.log('Canvas element:', canvas);
      console.log('Canvas dimensions:', canvas.width, 'x', canvas.height);

      // Create Rive instance
      this.riveInstance = new Rive({
        src: 'assets/animations/welcome_bg_animation.riv',
        canvas: canvas,
        autoplay: false, // Changed to false - we'll control playback manually
        onLoad: () => {
          console.log('=== Rive animation loaded successfully ===');

          // Resize canvas to fit the container
          this.riveInstance.resizeDrawingSurfaceToCanvas();
          console.log('Canvas resized. New dimensions:', canvas.width, 'x', canvas.height);

          // Log all available methods and properties
          console.log('Rive instance methods:', Object.getOwnPropertyNames(Object.getPrototypeOf(this.riveInstance)));

          // Check available animations
          console.log('Available animations:', this.riveInstance.animationNames);

          // Play the default UnNear animation initially
          this.riveInstance.play('UnNear', true); // true = loop
          console.log('Started playing UnNear animation (loop)');

          // Track last state
          let lastLoggedState: boolean | null = null;

          // Setup mouse move listener on window to track if mouse is over canvas
          this.mouseMoveListener = (event: MouseEvent) => {
            const rect = canvas.getBoundingClientRect();
            const mouseX = event.clientX;
            const mouseY = event.clientY;

            // Check if mouse is within canvas bounds
            const isInside = (
              mouseX >= rect.left &&
              mouseX <= rect.right &&
              mouseY >= rect.top &&
              mouseY <= rect.bottom
            );

            // Update animation based on mouse position
            if (isInside && lastLoggedState !== true) {
              console.log('>>> Mouse ENTERED - Playing "Near" animation');
              this.riveInstance.play('Near', true); // Play Near animation on loop
              console.log('Currently playing:', this.riveInstance.playingAnimationNames);
              lastLoggedState = true;
            } else if (!isInside && lastLoggedState !== false) {
              console.log('<<< Mouse LEFT - Playing "UnNear" animation');
              this.riveInstance.play('UnNear', true); // Play UnNear animation on loop
              console.log('Currently playing:', this.riveInstance.playingAnimationNames);
              lastLoggedState = false;
            }
          };

          // Add event listener to window
          window.addEventListener('mousemove', this.mouseMoveListener);

          console.log('Mouse move listener attached to window');
          console.log('Initial animation playing:', this.riveInstance.playingAnimationNames);

          // Setup resize listener
          this.resizeListener = () => {
            if (this.riveInstance) {
              this.riveInstance.resizeDrawingSurfaceToCanvas();
              console.log('Canvas resized on window resize');
            }
          };

          window.addEventListener('resize', this.resizeListener);
        },
        onLoadError: (error: any) => {
          console.error('❌ Failed to load Rive animation:', error);
        }
      });

      console.log('Rive instance created:', this.riveInstance);

    } catch (error) {
      console.error('❌ Error initializing Rive:', error);
    }
  }
}
