import { Controller } from '@hotwired/stimulus';

export default class extends Controller {
  static values = {
    eventId: String,       // UUIDv7 de l'événement
    gamemasterId: String   // UUIDv7 du MJ
  }

  connect() {
    console.log("Stimulus: toggle gamemaster actif");
    this.element.addEventListener('click', this.toggleGamemaster.bind(this));
  }

  async toggleGamemaster(event) {
    event.preventDefault();

    const eventId = this.eventIdValue;
    const gamemasterId = this.gamemasterIdValue;

    if (!eventId || !gamemasterId) {
      console.error("UUID manquant pour event ou gamemaster");
      return;
    }

    const url = `/admin/event/${eventId}/configure/gamemaster/toggle/`;
    console.log(gamemasterId);

    try {
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Requested-With': 'XMLHttpRequest',
          //'X-CSRF-TOKEN': this.getCsrfToken() TODO: remettre en place si néccesaire ?
        },
        body: JSON.stringify({ gamemasterId: gamemasterId })
      });

      if (!response.ok) {
        console.error("Erreur HTTP :", response.status);
        return;
      }

      const data = await response.json();
      const cell = this.element;

      if (!cell) {
        console.error("Élément <article> introuvable");
        return;
      }

      if (data.status === "DISABLE") {
        cell.classList.add('is-div-disabled');
      } else if (data.status === "ENABLE") {
        cell.classList.remove('is-div-disabled');
      } else {
        console.warn("Statut de réponse inattendu :", data.status);
      }

    } catch (error) {
      console.error("Erreur réseau :", error);
    }
  }

  getCsrfToken() {
    const token = document.querySelector('meta[name="csrf-token"]');
    return token ? token.content : '';
  }
}