import { Component, HostListener, ElementRef, ChangeDetectionStrategy } from '@angular/core';
import { LanguageService, Language, Currency } from '../../services/language.service';
import { IconComponent } from '../../shared/ui/icon/icon.component';

@Component({
  selector: 'app-language-selector',
  imports: [IconComponent],
  templateUrl: './language-selector.component.html',
  styleUrls: ['./language-selector.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class LanguageSelectorComponent {
  dropdownOpen = false;
  currencyOpen = false;

  constructor(
    public languageService: LanguageService,
    private elementRef: ElementRef
  ) {}

  toggleDropdown(): void {
    this.dropdownOpen = !this.dropdownOpen;
    this.currencyOpen = false;
  }

  toggleCurrency(): void {
    this.currencyOpen = !this.currencyOpen;
    this.dropdownOpen = false;
  }

  selectLanguage(lang: Language): void {
    if (lang.enabled) {
      this.languageService.switchLanguage(lang.code);
      this.dropdownOpen = false;
    }
  }

  selectCurrency(currency: Currency): void {
    this.languageService.setCurrency(currency.code);
    this.currencyOpen = false;
  }

  closeDropdown(): void {
    this.dropdownOpen = false;
    this.currencyOpen = false;
  }

  onKeyDown(event: KeyboardEvent): void {
    if (event.key === 'Escape') {
      this.dropdownOpen = false;
    } else if (event.key === 'Enter' || event.key === ' ') {
      event.preventDefault();
      this.toggleDropdown();
    }
  }

  @HostListener('document:click', ['$event'])
  onClickOutside(event: Event): void {
    if (!this.elementRef.nativeElement.contains(event.target)) {
      this.dropdownOpen = false;
      this.currencyOpen = false;
    }
  }
}
