import { Component, ElementRef, HostListener, inject, input, output, signal } from '@angular/core';
import { RouterLink } from '@angular/router';
import { AuthUser } from '../../../services/auth/auth.interfaces';
import { CartIconComponent } from '../../../../shared/components/cart-icon/cart-icon.component';
import { IconButtonComponent } from '../../../../shared/components/icon-button/icon-button.component';
import { UserDropdownComponent } from './user-dropdown/user-dropdown.component';

@Component({
  selector: 'app-store-header',
  imports: [CartIconComponent, IconButtonComponent, RouterLink, UserDropdownComponent],
  templateUrl: './store-header.component.html',
  styleUrl: './store-header.component.scss'
})
export class StoreHeaderComponent {
  private readonly elementRef = inject(ElementRef<HTMLElement>);

  readonly logoUrl = input<string | null>(null);
  readonly cartQuantity = input<number>(0);
  readonly user = input<AuthUser | null>(null);
  readonly isAuthenticated = input<boolean>(false);
  readonly cartClick = output<void>();
  readonly loginClick = output<void>();
  readonly logoutClick = output<void>();

  protected readonly isUserDropdownOpen = signal(false);

  @HostListener('document:click', ['$event'])
  protected onDocumentClick(event: MouseEvent): void {
    if (!this.isUserDropdownOpen()) {
      return;
    }

    const target = event.target;
    if (target instanceof Node && !this.elementRef.nativeElement.contains(target)) {
      this.isUserDropdownOpen.set(false);
    }
  }

  @HostListener('document:keydown.escape')
  protected onEscapeKey(): void {
    this.isUserDropdownOpen.set(false);
  }

  protected toggleUserDropdown(): void {
    if (!this.isAuthenticated()) {
      this.loginClick.emit();
      return;
    }

    this.isUserDropdownOpen.update((isOpen) => !isOpen);
  }

  protected onLoginClick(): void {
    this.isUserDropdownOpen.set(false);
    this.loginClick.emit();
  }

  protected onLogoutClick(): void {
    this.isUserDropdownOpen.set(false);
    this.logoutClick.emit();
  }
}
