import { ChangeDetectionStrategy, Component, HostListener, signal, OnDestroy, OnInit } from '@angular/core';
import { RouterLink, RouterLinkActive } from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
import { MatBadgeModule } from '@angular/material/badge';
import { NAV_DESTINATIONS } from '../../models/nav.model';

@Component({
  selector: 'app-nav-rail',
  standalone: true,
  imports: [RouterLink, RouterLinkActive, MatIconModule, MatBadgeModule],
  templateUrl: './nav-rail.component.html',
  styleUrl: './nav-rail.component.scss',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class NavRailComponent implements OnInit, OnDestroy {
  protected readonly destinations = NAV_DESTINATIONS;
  protected readonly expanded = signal(false);
  protected readonly isExpandedBreakpoint = signal(false);

  private readonly EXPANDED_BP = 1024;

  ngOnInit(): void {
    this.updateBreakpoint();
  }

  @HostListener('window:resize')
  onResize(): void {
    this.updateBreakpoint();
  }

  @HostListener('mouseenter')
  onHoverIn(): void {
    if (this.isExpandedBreakpoint()) {
      this.expanded.set(true);
    }
  }

  @HostListener('mouseleave')
  onHoverOut(): void {
    if (this.isExpandedBreakpoint()) {
      this.expanded.set(false);
    }
  }

  toggleExpand(): void {
    if (this.isExpandedBreakpoint()) {
      this.expanded.update(v => !v);
    }
  }

  private updateBreakpoint(): void {
    const isExpanded = window.innerWidth >= this.EXPANDED_BP;
    this.isExpandedBreakpoint.set(isExpanded);
    // Collapse when leaving expanded breakpoint
    if (!isExpanded) {
      this.expanded.set(false);
    }
  }

  ngOnDestroy(): void {
    // Cleanup is handled by HostListener auto-unsubscribe
  }
}