import { Controller } from "@hotwired/stimulus"

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

  connect() {
    this.boundClickOutside = this.clickOutside.bind(this)
    this.boundKeydown = this.keydown.bind(this)
  }

  disconnect() {
    this.stopListening()
  }

  toggle(event) {
    event.preventDefault()
    this.isOpen ? this.close() : this.open()
  }

  open() {
    this.buttonTarget.setAttribute("aria-expanded", "true")
    this.menuTarget.hidden = false
    document.addEventListener("mousedown", this.boundClickOutside)
    document.addEventListener("keydown", this.boundKeydown)
  }

  close() {
    this.buttonTarget.setAttribute("aria-expanded", "false")
    this.menuTarget.hidden = true
    this.stopListening()
  }

  stopListening() {
    document.removeEventListener("mousedown", this.boundClickOutside)
    document.removeEventListener("keydown", this.boundKeydown)
  }

  get isOpen() {
    return this.buttonTarget.getAttribute("aria-expanded") === "true"
  }

  clickOutside(event) {
    if (this.element.contains(event.target)) return
    this.close()
  }

  keydown(event) {
    if (event.key === "Escape") {
      this.close()
      this.buttonTarget.focus()
    }
  }
}
