import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["modal", "languageSelect", "form"]

  connect() {
    this.modalTarget.classList.add("hidden")
  }

  open(event) {
    event.preventDefault()

    // Get the language code from the button that was clicked
    const languageCode = event.currentTarget.dataset.languageCode

    // Set the language select value if provided
    if (languageCode && this.hasLanguageSelectTarget) {
      this.languageSelectTarget.value = languageCode
    }

    this.modalTarget.classList.remove("hidden")
  }

  close(event) {
    if (event.target === this.modalTarget) {
      this.modalTarget.classList.add("hidden")
      this.resetForm()
    }
  }

  closeWithButton(event) {
    event.preventDefault()
    this.modalTarget.classList.add("hidden")
    this.resetForm()
  }

  stopPropagation(event) {
    event.stopPropagation()
  }

  resetForm() {
    if (this.hasFormTarget) {
      this.formTarget.reset()
    }
  }
}
