import { Component, OnDestroy, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { I18nService, SupportedLanguage } from '../Services/i18n.service';
import { MapService } from '../Services/map.service';
import { CesiumMapComponent } from '../cesium-map/cesium-map.component';

@Component({
  selector: 'app-embed-cesium-transparent',
  templateUrl: './embed-cesium-transparent.component.html',
  styleUrls: ['./embed-cesium-transparent.component.css']
})
export class EmbedCesiumTransparentComponent implements OnInit, OnDestroy, AfterViewInit {
  @ViewChild(CesiumMapComponent) cesiumMap?: CesiumMapComponent;
  @ViewChild('mapContainer') mapContainer?: ElementRef<HTMLElement>;
  showZoomControls: boolean = true;
  currentLanguage: SupportedLanguage = 'en';
  isFullscreen: boolean = false;
  navbarHeight: number = 0;
  mobileInteractionEnabled: boolean = false;
  isMobileView: boolean = false;
  private destroy$ = new Subject<void>();

  constructor(
    private i18nService: I18nService,
    private mapService: MapService
  ) {}

  ngOnInit(): void {
    this.mapService.refreshActiveMap();
    this.mapService.getActiveMap()
      .pipe(takeUntil(this.destroy$))
      .subscribe((activeMap) => {
        if (!activeMap?.id) {
          this.mapService.getDefaultMap().subscribe({
            next: (defaultMap) => {
              if (defaultMap?.id) {
                this.mapService.setActiveMap(defaultMap.id).subscribe({
                  next: () => this.mapService.refreshActiveMap(),
                  error: () => this.mapService.refreshActiveMap(),
                });
              }
            },
            error: () => {},
          });
        }
      });

    this.currentLanguage = this.i18nService.getCurrentLanguage();
    this.i18nService.currentLanguage$
      .pipe(takeUntil(this.destroy$))
      .subscribe((lang) => {
        this.currentLanguage = lang;
      });

    // detect mobile width for initial behavior
    this.isMobileView = (typeof window !== 'undefined') && window.innerWidth <= 768;
  }

  changeLanguage(language: SupportedLanguage): void {
    this.i18nService.setLanguage(language);
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }

  ngAfterViewInit(): void {
    this.blockMapInteractions();
  }

  toggleMobileInteraction(): void {
    this.mobileInteractionEnabled = !this.mobileInteractionEnabled;
    // When enabled, allow pointer events inside the embedded cesium map (handled by CesiumMapComponent)
  }

  zoomIn(): void {
    if (this.cesiumMap?.viewer) {
      const camera = this.cesiumMap.viewer.camera;
      camera.zoomIn(camera.positionCartographic.height * 0.5);
    }
  }

  zoomOut(): void {
    if (this.cesiumMap?.viewer) {
      const camera = this.cesiumMap.viewer.camera;
      camera.zoomOut(camera.positionCartographic.height * 0.5);
    }
  }

  toggleFullscreen(): void {
    const container = this.mapContainer?.nativeElement;
    if (!container) return;

    if (!this.isFullscreen) {
      const header = document.querySelector('header, nav, .navbar, .topbar, .app-navbar');
      this.navbarHeight = header instanceof HTMLElement ? header.offsetHeight : 0;
      document.body.classList.add('modal-open');
      this.isFullscreen = true;
      setTimeout(() => {
        container.focus && (container as HTMLElement).focus();
      }, 0);
    } else {
      document.body.classList.remove('modal-open');
      this.isFullscreen = false;
      this.navbarHeight = 0;
    }
  }

  /** Block ALL scroll and touch interactions on the map so the page scrolls normally */
  private blockMapInteractions(): void {
    const container = this.mapContainer?.nativeElement;
    if (!container) return;

    container.addEventListener('wheel', (event: WheelEvent) => {
      event.stopPropagation();
    }, { passive: true, capture: true });

    container.addEventListener('touchstart', (event: TouchEvent) => {
      event.stopPropagation();
    }, { passive: true, capture: true });

    container.addEventListener('touchmove', (event: TouchEvent) => {
      event.stopPropagation();
    }, { passive: true, capture: true });

    container.addEventListener('touchend', (event: TouchEvent) => {
      event.stopPropagation();
    }, { passive: true, capture: true });
  }

  getTapToInteractText(): string {
    switch (this.currentLanguage) {
      case 'ar':
        return 'إضغط للتفاعل مع الخريطة';
      case 'fr':
        return 'Appuyez pour interagir';
      default:
        return 'Tap to interact';
    }
  }

  getCloseInteractionText(): string {
    switch (this.currentLanguage) {
      case 'ar':
        return 'إغلق التفاعل';
      case 'fr':
        return 'Fermer l\'interaction';
      default:
        return 'Close interaction';
    }
  }
}
