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'));
  }
});
