document.addEventListener('DOMContentLoaded', () => {
  const btn = document.querySelector('[data-player-toggle]');
  const audio = document.getElementById('ugfxAudio');
  if (btn && audio) {
    btn.addEventListener('click', () => {
      if (audio.paused) {
        audio.play().then(() => {
          btn.innerHTML = '<i class="bi bi-pause-fill"></i> Pause';
        }).catch(() => {
          window.location.href = 'listen-live.php';
        });
      } else {
        audio.pause();
        btn.innerHTML = '<i class="bi bi-play-fill"></i> Play Live';
      }
    });
  }

  const streamButtons = document.querySelectorAll('[data-copy-stream]');
  streamButtons.forEach(button => {
    button.addEventListener('click', async () => {
      const url = button.getAttribute('data-copy-stream');
      try {
        await navigator.clipboard.writeText(url);
        const original = button.textContent;
        button.textContent = 'Copied';
        setTimeout(() => button.textContent = original, 1400);
      } catch (e) {}
    });
  });

  const chatForm = document.querySelector('[data-chat-form]');
  if (chatForm) {
    chatForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      const fd = new FormData(chatForm);
      const target = chatForm.getAttribute('action');
      const response = await fetch(target, { method: 'POST', body: fd });
      const result = await response.json();
      const status = document.querySelector('[data-chat-status]');
      if (status) status.textContent = result.message || (result.ok ? 'Sent' : 'Failed');
      if (result.ok) {
        chatForm.reset();
        setTimeout(() => location.reload(), 500);
      }
    });
  }

  const reveals = document.querySelectorAll('.reveal-up');
  if (reveals.length && 'IntersectionObserver' in window) {
    const observer = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add('is-visible');
          observer.unobserve(entry.target);
        }
      });
    }, { threshold: 0.15 });
    reveals.forEach(el => observer.observe(el));
  } else {
    reveals.forEach(el => el.classList.add('is-visible'));
  }
});

(function () {
  const mount = document.createElement('div');
  mount.className = 'body-embers';
  document.body.appendChild(mount);
  const reduced = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  if (reduced) return;
  const count = window.innerWidth < 768 ? 12 : 20;
  for (let i = 0; i < count; i++) {
    const ember = document.createElement('span');
    ember.style.left = (Math.random() * 100) + '%';
    ember.style.animationDuration = (6 + Math.random() * 7) + 's';
    ember.style.animationDelay = (Math.random() * 8) + 's';
    ember.style.setProperty('--drift', ((Math.random() * 70) - 35) + 'px');
    ember.style.opacity = 0;
    mount.appendChild(ember);
  }
})();
