"use strict";

import {Controller} from "@hotwired/stimulus";
import "@tailwindplus/elements";

export default class extends Controller {
  static targets = ["dialog", "dynamicContent", "panel"];

  connect() {
    this.observer = null;
    this.hide = this.hide.bind(this);
    this.clearContent = this.clearContent.bind(this);

    window.addEventListener("turbo:before-visit", this.hide);
    window.addEventListener("turbo:before-render", this.hide);

    this.handleToggle = this.handleToggle.bind(this);
    this.element.addEventListener("toggle", this.handleToggle);
    this.element.addEventListener("close", this.clearContent);

    if (this.hasDynamicContentTarget) {
      this.observer = new MutationObserver(() => {
        const hasContent =
          this.dynamicContentTarget.innerHTML.trim().length > 0;
        if (hasContent) {
          this.element.show();
        } else {
          this.element.hide();
        }
      });
      this.observer.observe(this.dynamicContentTarget, {
        childList: true,
        characterData: true,
        subtree: true,
      });
    }
  }

  disconnect() {
    window.removeEventListener("turbo:before-visit", this.hide);
    window.removeEventListener("turbo:before-render", this.hide);
    this.element.removeEventListener("toggle", this.handleToggle);
    this.element.removeEventListener("close", this.clearContent);

    if (this.observer) {
      this.observer.disconnect();
    }
    this.hide();
  }

  hide() {
    this.element.hide();
  }

  handleToggle(event) {
    if (event.newState === "closed") {
      this.clearContent();
    }
  }

  clearContent() {
    if (this.hasDynamicContentTarget) {
      this.dynamicContentTarget.innerHTML = "";
      this.dynamicContentTarget.removeAttribute("src");
    }
  }
}
