import { Component, OnInit, OnDestroy } from '@angular/core';
import { I18nService, SupportedLanguage } from './Services/i18n.service';
import { Subscription } from 'rxjs';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  title = 'Smart Mapping';
  textDirection: 'ltr' | 'rtl' = 'ltr';
  private langSubscription?: Subscription;

  constructor(private i18nService: I18nService, private router: Router) {}

  ngOnInit() {
    // Subscribe to language changes to update text direction
    this.langSubscription = this.i18nService.currentLanguage$.subscribe(lang => {
      this.textDirection = lang === 'ar' ? 'rtl' : 'ltr';
      // Update HTML dir attribute for RTL support
      document.documentElement.setAttribute('dir', this.textDirection);
      // Update HTML lang attribute
      document.documentElement.setAttribute('lang', lang);
    });
  window.addEventListener('wheel', (e) => {
    window.parent.postMessage(
      { type: 'IFRAME_WHEEL', deltaY: e.deltaY, deltaX: e.deltaX },
      '*'
    );
  }, { passive: true });
    // Update language from any URL segment when navigation happens (supports both /fr/... and /embed-cesium/fr).
    this.router.events.pipe(filter(e => e instanceof NavigationEnd)).subscribe((e: NavigationEnd) => {
      const url = e.urlAfterRedirects || e.url || '';
      const segments = url.split('/').filter(Boolean);
      const langSegment = [...segments].reverse().find(s => ['en', 'ar', 'fr'].includes(s));
      if (langSegment) {
        const lang = langSegment as SupportedLanguage;
        this.i18nService.setLanguage(lang);
      }
    });
  }

  ngOnDestroy() {
    this.langSubscription?.unsubscribe();
  }
}

