import { Component, OnDestroy, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Store } from '@ngrx/store';
import { Subscription } from 'rxjs';
import { ActionTypes, StateInterface } from '../../reducers';
import { TranslationService } from '../../services/translation.service';

@Component({
  selector: 'app-language-selector',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './language-selector.html',
  styleUrl: './language-selector.scss'
})
export class LanguageSelector implements OnInit, OnDestroy {
  currentLang: string = '';
  langsList: string[] = [];
  private storeSubscription: Subscription | null = null;

  constructor(
    private store: Store<StateInterface>,
    private translationService: TranslationService
  ) {}

  ngOnInit(): void {
    // Subscribe to the store to get the current language and languages list
    this.storeSubscription = this.store.select(state => state.app)
      .subscribe(app => {
        this.currentLang = app.lang;
        this.langsList = app.langsList;
      });
  }

  ngOnDestroy(): void {
    // Unsubscribe to prevent memory leaks
    if (this.storeSubscription) {
      this.storeSubscription.unsubscribe();
    }
  }

  // Method to switch to the next language
  switchToNextLanguage(): void {
    this.store.dispatch({ type: ActionTypes.SWITCH_TO_NEXT_LANGUAGE });
  }

  // Helper method to display a friendly language name
  getLanguageDisplayName(langCode: string): string {
    switch (langCode) {
      case 'fr_FR':
        return 'Français';
      case 'en_US':
        return 'English';
      default:
        return langCode;
    }
  }
}
