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

/*
* The following line makes this controller "lazy": it won't be downloaded until needed
* See https://github.com/symfony/stimulus-bridge#lazy-controllers
*/
/* stimulusFetch: 'lazy' */
export default class extends Controller {
  // ...
  connect() {
    const topic = this.data.get('topic');
    const mercureHubUrl = 'https://mangarr.test.nestor-server.fr/.well-known/mercure';
    const eventSource = new EventSource(`${mercureHubUrl}?topic=${topic}`, {withCredentials: true});

    eventSource.onmessage = (event) => {
      const data = JSON.parse(event.data);
      console.log('Received Mercure update:', data);

      this.dispatchAlert(data.message, data.status);
    };

    eventSource.onerror = (event) => {
      console.error('EventSource failed:', event);
    };
  }

  dispatchAlert(message, level) {
    const event = new CustomEvent('alert:show', {
      detail: { message: message, level: level }
    });
    window.dispatchEvent(event);
  }
}
