// app/javascript/controllers/dialog_controller.js
import { Controller } from "@hotwired/stimulus"

// Connects to data-controller="dialog"
export default class extends Controller {
  connect() {
    this.open()
    console.log("connect dialog", this.element)
    this.element.addEventListener("turbo:submit-end", e => {
      this.submitEnd(e) 
    })
    this.element.addEventListener("click", e => this.clickOutside(e))
  }

  disconnect() {
  }

  // hide modal on successful form submission
  // data-action="turbo:submit-end->turbo-modal#submitEnd"
  submitEnd(e) {
    if (e.detail.success) {
      this.close()
    }
  }

  open() {
    console.log("open dialog")
    this.element.showModal()
    document.body.classList.add('overflow-hidden')
    this.element.addEventListener("close", this.enableBodyScroll.bind(this))
  }

  close() {
    this.element.removeEventListener("close", this.enableBodyScroll.bind(this))
    this.element.close()
    // clean up modal content
    const frame = document.getElementById('modal')
    frame.removeAttribute("src")
    frame.innerHTML = ""
  }

  enableBodyScroll() {
    document.body.classList.remove('overflow-hidden')
  }

  clickOutside(event) {
    console.log("clickOutside", event.target, this)
    if (event.target === this.element) {
      this.close()
    }
  }
}

