// assets/controllers/dropdown_controller.js
import { Controller } from '@hotwired/stimulus'

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

  toggle(event) {
    event.stopPropagation()

    const menu = this.menuTarget

    if (menu.classList.contains('is-active')) {
      // Fermeture avec délai pour laisser la transition jouer
      menu.classList.remove('is-active')
      setTimeout(() => {
        menu.style.display = 'none'
      }, 200) // correspond à la durée CSS
    } else {
      menu.style.display = 'block'
      // force reflow pour permettre l’animation
      void menu.offsetWidth
      menu.classList.add('is-active')
    }
  }

  closeOnOutsideClick = (event) => {
    if (!this.element.contains(event.target)) {
      const menu = this.menuTarget
      if (menu.classList.contains('is-active')) {
        menu.classList.remove('is-active')
        setTimeout(() => {
          menu.style.display = 'none'
        }, 200)
      }
    }
  }

  connect() {
    document.addEventListener('click', this.closeOnOutsideClick)
  }

  disconnect() {
    document.removeEventListener('click', this.closeOnOutsideClick)
  }
}