import { createRoot } from "react-dom/client";
import { Popup } from "./Popup.js";

export default class PopupInfo {
  viewer;
  element;
  popup;
  reactRoot;

  constructor(viewer, options) {
    this.viewer = viewer;
    this.init(options);
  }

  init(options) {
    const { component, position, popupCommonOption, props } = options;
    const div = document.createElement("div");
    div.style.position = "absolute";
    div.className = "popup";

    this.element = div;

    if (component && typeof component === "function") {
      this.reactRoot = createRoot(div);
      this.reactRoot.render(component(props));
    }

    this.viewer.container.appendChild(div);

    this.popup = new Popup(this.viewer, {
      ...popupCommonOption,
      element: div,
      position,
    });
  }

  remove() {
    if (this.element)
      this.viewer.container.removeChild(this.element);
    if (this.reactRoot)
      this.reactRoot.unmount();
    this.popup?.destory();
    this.element = null;
  }
}
