
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
    connect() {
        // Écoute tous les clics sur .open-modal -> détournement vers #lastStep + MAJ des options du formulaire
      document.querySelectorAll('.participant-box').forEach(element => {
          element.addEventListener('click', this.handleClick.bind(this))
      })
    }

    handleClick(event) {
        event.preventDefault()
        const participantId = event.currentTarget.dataset.id
        const box = event.currentTarget;
        const icon = box.querySelector('.icon');

        if (!participantId) return

        // Etape 1
        fetch(`/checkin/participant/${participantId}`, {
          method: 'POST',
          headers: {
            'Accept': 'application/json'
          }
        })
          .then(response => {
            if (!response.ok) {
              throw new Error(`Erreur API: ${response.status}`);
            }
            return response.json();
          })
          .then(data => {
            
            // Etape 2
            console.log('ID du particpant cliqué :', participantId);
            console.log('ÉTAT DU SLOT :', data.status);

            if (data.status === "CHECKED") {
              box.classList.add('has-background-primary');
              box.classList.remove('has-background-danger');
              icon.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-check2-circle" viewBox="0 0 16 16">'+
                '<path d="M2.5 8a5.5 5.5 0 0 1 8.25-4.764.5.5 0 0 0 .5-.866A6.5 6.5 0 1 0 14.5 8a.5.5 0 0 0-1 0 5.5 5.5 0 1 1-11 0"/>'+
                '<path d="M15.354 3.354a.5.5 0 0 0-.708-.708L8 9.293 5.354 6.646a.5.5 0 1 0-.708.708l3 3a.5.5 0 0 0 .708 0z"/>'+
                '</svg>';

            } else if (data.status === "UNCHECKED") {
              box.classList.remove('has-background-primary');
              box.classList.add('has-background-danger');
              icon.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-circle" viewBox="0 0 16 16">'+
                '<path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14m0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16"/>'+
                '</svg>';
            } else {
              console.warn("Statut de réponse sans action :", data.status);
            }

          })
          .catch(error => {
            console.error('Erreur lors de la récupération des slots :', error);
          });



        





    }

    disconnect() {
    this.element.querySelectorAll('.planning-cell-free').forEach(element => {
        element.removeEventListener('click', this.handleClick)
    })
}


}