"use strict";

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

export default class extends Controller {
  connect() {
    this.hide = this.hide.bind(this);

    // Only close on a true page navigation, NOT on `turbo:before-render`.
    // The render event also fires for in-page Live re-renders (e.g. when a
    // user types into a debounced search input) — using it as a close
    // trigger killed freshly-opened context menus mid-click.
    window.addEventListener("turbo:before-visit", this.hide);
  }

  disconnect() {
    window.removeEventListener("turbo:before-visit", this.hide);
    // Intentionally NOT calling hide() here. If morphdom replaces the
    // element, the old popover closes naturally; if the element survives
    // the morph (most common case), forcing a hide would close a popover
    // the user just opened.
  }

  hide() {
    if (typeof this.element.hide === "function") {
      this.element.hide();
    }
  }
}
