document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('.live-now-label, .live-next-label').forEach((el) => {
    if (!el.dataset.schedule) el.dataset.schedule = (el.textContent || '').trim();
  });
  let audio = document.getElementById('ugfxAudio');
  if (!audio) {
    audio = document.createElement('audio');
    audio.id = 'ugfxAudio';
    audio.preload = 'none';
    audio.style.display = 'none';
    document.body.appendChild(audio);
  }
  const streamButtons = document.querySelectorAll('[data-player-toggle]');

  const resetPlayerButtons = () => {
    streamButtons.forEach((button) => {
      button.innerHTML = '<i class="bi bi-play-fill"></i> Play Live';
      button.dataset.isPlaying = '0';
    });
  };

  audio.addEventListener('pause', resetPlayerButtons);
  audio.addEventListener('ended', resetPlayerButtons);

  streamButtons.forEach((btn) => {
    btn.addEventListener('click', async () => {
      const streamUrl = btn.getAttribute('data-stream-url') || (audio ? audio.getAttribute('src') : '') || '';
      if (!streamUrl || !audio) return;

      const isSameSource = audio.getAttribute('src') === streamUrl;
      const buttonPlaying = btn.dataset.isPlaying === '1';

      if (!audio.paused && isSameSource && buttonPlaying) {
        audio.pause();
        resetPlayerButtons();
        return;
      }

      audio.setAttribute('src', streamUrl);
      try {
        await audio.play();
        resetPlayerButtons();
        btn.innerHTML = '<i class="bi bi-pause-fill"></i> Pause';
        btn.dataset.isPlaying = '1';
      } catch (e) {
        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'));
  }

  ugfxRefreshAll();
  setInterval(ugfxRefreshAll, 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 ugfxRefreshAll() {
  try {
    const [icecastRes, statsRes, pingRes] = await Promise.all([
      fetch('api/icecast.php', { cache: 'no-store' }),
      fetch('api/stats.php', { cache: 'no-store' }),
      fetch('api/ping.php', { cache: 'no-store' })
    ]);

    if (icecastRes.ok) {
      const data = await icecastRes.json();
      document.querySelectorAll('.current-track').forEach((el) => {
        if (data.title) el.textContent = data.title;
      });
      document.querySelectorAll('.current-artist').forEach((el) => {
        const showLabel = data.display_show || data.artist || '';
        if (showLabel) el.textContent = showLabel;
      });
      // Keep the On Air panel schedule-based; do not overwrite it with track metadata.
      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);
      });
    }

    if (statsRes.ok) {
      const stats = await statsRes.json();
      document.querySelectorAll('.listener-count').forEach((el) => {
        el.textContent = Number(stats.listeners || 0).toLocaleString();
      });
      const currentListeners = document.getElementById('currentListeners');
      if (currentListeners) {
        currentListeners.textContent = Number(stats.listeners || 0).toLocaleString();
      }
    }

    document.querySelectorAll('.live-now-label, .live-next-label').forEach((el) => {
      if (el.dataset.schedule) el.textContent = el.dataset.schedule;
    });

    if (pingRes.ok) {
      const ping = await pingRes.json();
      const visitorsOnline = document.getElementById('visitorsOnline');
      if (visitorsOnline) {
        visitorsOnline.textContent = Number(ping.online || 0).toLocaleString();
      }
    }
  } catch (e) {}
}
