import {AfterViewInit, Directive, Host, HostBinding, HostListener, ViewContainerRef} from '@angular/core';
import {MapComponent} from '@maplibre/ngx-maplibre-gl';

/**
 * Fixes an issue related to page transitions where
 * the map would only appear with a size of 300x400px
 */
@Directive({
  selector: 'mgl-map',
  standalone: true,
})
export class MapSizeFixDirective implements AfterViewInit {
  private animation: Animation;

  @HostBinding('class.ready') ready = false;

  constructor(
    @Host() private map: MapComponent,
    private viewContainerRef: ViewContainerRef,
  ) {}

  @HostListener('mapLoad')
  mapLoad() {
    this.map.mapInstance.resize();
    this.ready = true;
    const element = this.viewContainerRef.element.nativeElement as HTMLElement;
    if (element.dispatchEvent(new CustomEvent('ready', {cancelable: true}))) {
      this.animation.play();
    } else {
      this.animation.cancel();
    }
  }

  ngAfterViewInit() {
    const element: HTMLDivElement = this.viewContainerRef.element.nativeElement;
    this.animation = element.animate([{opacity: 0}, {opacity: 1}], {duration: 200, fill: 'backwards'});
    this.animation.pause();
  }
}
