
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
    connect() {
        this._closeListener = () => this.close()
        this._escapeListener = (event) => {
            if (event.key === 'Escape') {
                this.close()
            }
        }
        window.addEventListener('modal:close', this._closeListener)
        document.addEventListener('keydown', this._escapeListener)

        // Écoute tous les clics sur .open-modal
        document.querySelectorAll('.open-modal').forEach(element => {
            element.addEventListener('click', this.handleClick.bind(this))
        })
    }

    disconnect() {
        window.removeEventListener('modal:close', this._closeListener)
        document.removeEventListener('keydown', this._escapeListener)

        // Nettoie les événements attachés
        document.querySelectorAll('.open-modal').forEach(element => {
            element.removeEventListener('click', this.handleClick.bind(this))
        })
    }

    handleClick(event) {
        event.preventDefault()
        const url = event.currentTarget.getAttribute('href') || event.currentTarget.dataset.url

        if (!url) return

        fetch(url, {
            headers: { "Turbo-Frame": "modal-content" }
        })
        .then(response => response.text())
        .then(html => {
            document.getElementById('modal-content').innerHTML = html
            document.getElementById('modal').classList.add('is-active')
        })
    }

    close() {
        document.getElementById('modal').classList.remove('is-active')
        document.getElementById('modal-content').innerHTML = ''
    }
}