import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["menu"]

  connect() {
    // Add click outside listener to close dropdown
    this.boundHide = this.hide.bind(this)
    document.addEventListener("click", this.boundHide)
  }

  disconnect() {
    document.removeEventListener("click", this.boundHide)
  }

  toggle(event) {
    event.preventDefault()
    event.stopPropagation()

    this.menuTarget.classList.toggle("hidden")
  }

  hide(event) {
    // Don't hide if clicking inside the dropdown
    if (this.element.contains(event.target)) return

    this.menuTarget.classList.add("hidden")
  }
}