// assets/controllers/dropdown_controller.js
import {Controller} from "@hotwired/stimulus"
import {useClickOutside} from "stimulus-use"

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

  connect() {
    useClickOutside(this)
  }

  toggle(event) {
    this.menuTarget.classList.toggle('hidden')
    if (!this.menuTarget.classList.contains('hidden')) {
      this.positionMenu()
    }
  }

  clickOutside(event) {
    this.menuTarget.classList.add('hidden')
  }

  positionMenu() {
    const buttonRect = this.buttonTarget.getBoundingClientRect()
    const menuRect = this.menuTarget.getBoundingClientRect()
    const spaceRight = window.innerWidth - buttonRect.right
    const spaceBottom = window.innerHeight - buttonRect.bottom

    if (spaceRight < menuRect.width && buttonRect.left > menuRect.width) {
      this.menuTarget.style.left = 'auto'
      this.menuTarget.style.right = '0'
    } else {
      this.menuTarget.style.left = '0'
      this.menuTarget.style.right = 'auto'
    }

    if (spaceBottom < menuRect.height && buttonRect.top > menuRect.height) {
      this.menuTarget.style.top = 'auto'
      this.menuTarget.style.bottom = '100%'
    } else {
      this.menuTarget.style.top = '100%'
      this.menuTarget.style.bottom = 'auto'
    }
  }
}
