import { Component, ChangeDetectionStrategy, inject, signal, HostListener } from '@angular/core';
import { LocationService } from '../../services/location.service';
import { Region } from '../../models/location.model';
import { TranslatePipe } from '../../i18n/translate.pipe';
import { IconComponent } from '../../shared/ui/icon/icon.component';

@Component({
  selector: 'app-region-selector',
  imports: [TranslatePipe, IconComponent],
  templateUrl: './region-selector.component.html',
  styleUrls: ['./region-selector.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class RegionSelectorComponent {
  private locationService = inject(LocationService);

  region = this.locationService.region;
  regions = this.locationService.regions;
  detecting = this.locationService.detecting;

  dropdownOpen = signal(false);

  toggleDropdown(): void {
    this.dropdownOpen.update(v => !v);
  }

  selectRegion(region: Region): void {
    this.locationService.setRegion(region);
    this.dropdownOpen.set(false);
  }

  selectGlobal(): void {
    this.locationService.clearRegion();
    this.dropdownOpen.set(false);
  }

  detectLocation(): void {
    this.locationService.detectLocation();
  }

  @HostListener('document:click', ['$event'])
  onDocumentClick(event: MouseEvent): void {
    const target = event.target as HTMLElement;
    if (!target.closest('app-region-selector')) {
      this.dropdownOpen.set(false);
    }
  }
}
