document.addEventListener('DOMContentLoaded', () => {
  const audio = document.getElementById('ugfxAudio');
  const streamButtons = document.querySelectorAll('[data-player-toggle]');

  streamButtons.forEach((btn) => {
    btn.addEventListener('click', () => {
      const streamUrl = btn.getAttribute('data-stream-url') || (audio ? audio.getAttribute('src') : '') || '/stream-proxy.php';
      if (audio && streamUrl && btn.closest('.ugfx-playerbar')) {
        audio.setAttribute('src', streamUrl);
        if (audio.paused) {
          audio.play().then(() => {
            btn.innerHTML = '<i class="bi bi-pause-fill"></i> Pause';
          }).catch(() => {
            window.open(streamUrl, '_blank', 'noopener');
          });
        } else {
          audio.pause();
          btn.innerHTML = '<i class="bi bi-play-fill"></i> Play Live';
        }
      } else if (streamUrl) {
        window.open(streamUrl, '_blank', 'noopener');
      }
    });
  });

  const copyButtons = document.querySelectorAll('[data-copy-stream]');
  copyButtons.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'));
  }

  ugfxRefreshIcecast();
  setInterval(ugfxRefreshIcecast, 15000);
});

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

async function ugfxRefreshIcecast() {
  try {
    const response = await fetch('api/icecast.php', { cache: 'no-store' });
    if (!response.ok) return;
    const data = await response.json();
    document.querySelectorAll('.listener-count').forEach((el) => {
      el.textContent = Number(data.server_listeners || 0).toLocaleString();
    });
    document.querySelectorAll('.current-track').forEach((el) => {
      if (data.title) el.textContent = data.title;
    });
    document.querySelectorAll('.current-artist').forEach((el) => {
      if (data.artist) el.textContent = data.artist;
    });
    const audio = document.getElementById('ugfxAudio');
    if (audio && data.stream_url) {
      audio.setAttribute('src', data.stream_url);
    }
    document.querySelectorAll('[data-player-toggle]').forEach((btn) => {
      if (data.stream_url) btn.setAttribute('data-stream-url', data.stream_url);
    });
    document.querySelectorAll('[data-copy-stream]').forEach((btn) => {
      if (data.direct_stream_url || data.public_stream_url) btn.setAttribute('data-copy-stream', data.direct_stream_url || data.public_stream_url);
    });
    document.querySelectorAll('[data-direct-stream]').forEach((el) => {
      const directUrl = data.direct_stream_url || data.public_stream_url;
      if (directUrl) el.setAttribute('href', directUrl);
    });
  } catch (e) {}
}
