
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('.planning-cell-free, .planning-cell-locked').forEach(element => {
          element.addEventListener('click', this.handleClick.bind(this))
      })
    }

    handleClick(event) {
        event.preventDefault()
        const slotId = event.currentTarget.dataset.id
        const cell = event.currentTarget;
        const path = cell.querySelector('.icon path');

        if (!slotId) return

        // A partir du slotId ->
        // 1. trouver l'état du slot cliqué et le basculer dans la BDD (LOCKED/UNLOCKED/GAME)
        // 2. mettre à jour le style de la case cliquée

        // Etape 1
        fetch(`/api/slot/${slotId}/toggleStatus`, {
          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 slot cliqué :', slotId);
            console.log('ÉTAT DU SLOT :', data.status);

            if (data.status === "UNLOCKED") {
              cell.classList.add('planning-cell-free');
              cell.classList.remove('planning-cell-locked');
              path.setAttribute('d', 'M12 0a4 4 0 0 1 4 4v2.5h-1V4a3 3 0 1 0-6 0v2h.5A2.5 2.5 0 0 1 12 8.5v5A2.5 2.5 0 0 1 9.5 16h-7A2.5 2.5 0 0 1 0 13.5v-5A2.5 2.5 0 0 1 2.5 6H8V4a4 4 0 0 1 4-4');
            } else if (data.status === "LOCKED") {
              cell.classList.remove('planning-cell-free');
              cell.classList.add('planning-cell-locked');
              path.setAttribute('d', 'M8 0a4 4 0 0 1 4 4v2.05a2.5 2.5 0 0 1 2 2.45v5a2.5 2.5 0 0 1-2.5 2.5h-7A2.5 2.5 0 0 1 2 13.5v-5a2.5 2.5 0 0 1 2-2.45V4a4 4 0 0 1 4-4m0 1a3 3 0 0 0-3 3v2h6V4a3 3 0 0 0-3-3');
            } 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)
    })
}


}