import { Component, Input, ElementRef, OnInit, OnDestroy, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-embed-monitor',
  template: `<div [id]="containerId"></div>`
})
export class EmbedMonitorComponent implements OnInit, OnDestroy, AfterViewInit {
  @Input() monitor!: string;
  @Input() theme: string = "light";
  @Input() bgc: string = "transparent";
  @Input() locale: string = "en";

  containerId = `embed-container-${Date.now()}-${Math.random().toString(36).substr(2, 5)}`;
  private iframe: HTMLIFrameElement | null = null;
  private messageListener!: (event: MessageEvent) => void;

  constructor(private el: ElementRef) {}

  ngOnInit() {}

  ngAfterViewInit() {
    this.createIframe();
  }

  ngOnChanges() {
    this.createIframe();
  }

  createIframe() {
    const container = this.el.nativeElement.querySelector(`#${this.containerId}`);
    if (!this.monitor || !container) return;

    // Remove previous iframe if it exists
    if (this.iframe) {
      this.iframe.remove();
    }

    this.iframe = document.createElement("iframe");
    this.iframe.src = `${this.monitor}?theme=${this.theme}&bgc=${this.bgc}&locale=${this.locale}`;
    this.iframe.width = "0%";
    this.iframe.height = "0";
    this.iframe.frameBorder = "0";
    this.iframe.allowTransparency = true;
    this.iframe.sandbox =
      "allow-modals allow-forms allow-same-origin allow-scripts allow-popups allow-top-navigation-by-user-activation allow-downloads";
    this.iframe.allow = "midi; geolocation; microphone; camera; display-capture; encrypted-media;";

    container.appendChild(this.iframe);

    this.messageListener = (event: MessageEvent) => {
      if (event.data?.height) this.iframe!.height = event.data.height;
      if (event.data?.width) this.iframe!.width = event.data.width;
    };

    window.addEventListener("message", this.messageListener);
  }

  ngOnDestroy() {
    window.removeEventListener("message", this.messageListener);
    if (this.iframe) {
      this.iframe.remove();
    }
  }
}