(() => {
  'use strict';
  const base = document.querySelector('meta[name="app-base-url"]')?.content || '';
  const csrf = document.querySelector('meta[name="csrf-token"]')?.content || '';

  document.querySelectorAll('[data-event-qr]').forEach(canvas => {
    const value = canvas.dataset.eventQr || '';
    if (!value || !window.AuraQRCode) return;
    try { window.AuraQRCode.render(canvas, value, 210); } catch (_) {}
  });

  const supervision = document.querySelector('[data-supervision-event]');
  if (supervision) {
    const eventId = Number(supervision.dataset.supervisionEvent || 0);
    const status = supervision.querySelector('[data-supervision-status]');
    const beat = async () => {
      if (!eventId) return;
      try {
        const response = await fetch(`${base}/api/v1/events/heartbeat.php`, {
          method: 'POST', credentials: 'same-origin',
          headers: {'Content-Type':'application/json','X-CSRF-Token':csrf},
          body: JSON.stringify({event_id:eventId}),
        });
        const data = await response.json().catch(() => ({}));
        if (!response.ok || !data.ok) throw new Error(data.erro || 'Falha na supervisão.');
        supervision.classList.remove('is-off');
        if (status) status.textContent = 'SUPERVISÃO ATIVA • ' + new Date().toLocaleTimeString('pt-BR',{hour:'2-digit',minute:'2-digit'});
      } catch (error) {
        supervision.classList.add('is-off');
        if (status) status.textContent = 'SUPERVISÃO INTERROMPIDA • ' + (error.message || 'Atualize a página');
      }
    };
    beat();
    const timer = window.setInterval(beat, 45000);
    window.addEventListener('pagehide', () => clearInterval(timer));
  }

  document.querySelectorAll('[data-copy-event-code]').forEach(button => {
    button.addEventListener('click', async () => {
      const value = button.dataset.copyEventCode || '';
      try { await navigator.clipboard.writeText(value); button.textContent = '✓ CÓDIGO COPIADO'; }
      catch (_) { window.prompt('Copie o código:', value); }
    });
  });
})();
