import { Component } from '@angular/core';
import { I18nService, SupportedLanguage } from '../Services/i18n.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-language-switcher',
  template: `
    <div class="language-switcher">
      <button 
        *ngFor="let lang of languages" 
        [class.active]="currentLanguage === lang.code"
        (click)="goToLanguage(lang.code)"
        [title]="lang.name">
        {{ lang.label }}
      </button>
    </div>
  `,
  styles: [`
    .language-switcher {
      display: flex;
      gap: 8px;
      padding: 8px;
    }
    
    .language-switcher button {
      padding: 6px 12px;
      border: 1px solid #ccc;
      border-radius: 4px;
      background: white;
      cursor: pointer;
      font-size: 14px;
      transition: all 0.2s;
    }
    
    .language-switcher button:hover {
      background: #f0f0f0;
    }
    
    .language-switcher button.active {
      background: #2196f3;
      color: white;
      border-color: #2196f3;
    }
  `]
})
export class LanguageSwitcherComponent {
  currentLanguage: SupportedLanguage = 'en';
  
  languages = [
    { code: 'en' as SupportedLanguage, label: 'EN', name: 'English' },
    { code: 'ar' as SupportedLanguage, label: 'عر', name: 'العربية' },
    { code: 'fr' as SupportedLanguage, label: 'FR', name: 'Français' }
  ];

  constructor(private i18nService: I18nService, private router: Router) {
    this.i18nService.currentLanguage$.subscribe(lang => {
      this.currentLanguage = lang;
    });
  }

  goToLanguage(language: SupportedLanguage): void {
    // Navigate to the language-prefixed root (e.g. /fr). AppComponent listens to URL and sets language.
    this.router.navigate(['/', language]);
    // Also set immediately for faster UI feedback.
    this.i18nService.setLanguage(language);
  }
}
