document.addEventListener('DOMContentLoaded', () => {
  const audio = document.getElementById('ugfxAudio');
  const popupAudio = document.getElementById('ugfxPopupAudio');
  const managedAudio = audio || popupAudio || null;
  const streamButtons = document.querySelectorAll('[data-player-toggle]');
  let shouldKeepPlaying = false;
  let reconnectTimer = null;

  const buildFreshUrl = (url) => {
    if (!url) return '';
    const joiner = url.includes('?') ? '&' : '?';
    return `${url}${joiner}t=${Date.now()}`;
  };

  const scheduleReconnect = () => {
    if (!managedAudio || !shouldKeepPlaying) return;
    clearTimeout(reconnectTimer);
    reconnectTimer = setTimeout(() => {
      const baseUrl = managedAudio.dataset.baseSrc || managedAudio.getAttribute('src') || '/stream-proxy.php';
      const freshUrl = buildFreshUrl(baseUrl);
      managedAudio.setAttribute('src', freshUrl);
      managedAudio.load();
      managedAudio.play().catch(() => {});
    }, 1800);
  };

  if (managedAudio) {
    managedAudio.addEventListener('playing', () => {
      clearTimeout(reconnectTimer);
    });
    ['ended', 'error', 'stalled', 'abort', 'emptied', 'suspend'].forEach((evt) => {
      managedAudio.addEventListener(evt, scheduleReconnect);
    });
    managedAudio.addEventListener('pause', () => {
      if (!managedAudio.ended && shouldKeepPlaying) {
        scheduleReconnect();
      }
    });
  }

  streamButtons.forEach((btn) => {
    btn.addEventListener('click', () => {
      const streamUrl = btn.getAttribute('data-stream-url') || (managedAudio ? managedAudio.dataset.baseSrc || managedAudio.getAttribute('src') : '') || '/stream-proxy.php';
      if (managedAudio && btn.closest('.ugfx-playerbar')) {
        managedAudio.dataset.baseSrc = streamUrl;
        if (managedAudio.paused) {
          shouldKeepPlaying = true;
          managedAudio.setAttribute('src', buildFreshUrl(streamUrl));
          managedAudio.load();
          managedAudio.play().then(() => {
            btn.innerHTML = '<i class="bi bi-pause-fill"></i> Pause';
          }).catch(() => {
            shouldKeepPlaying = false;
            window.open(streamUrl, '_blank', 'noopener');
          });
        } else {
          shouldKeepPlaying = false;
          clearTimeout(reconnectTimer);
          managedAudio.pause();
          btn.innerHTML = '<i class="bi bi-play-fill"></i> Play Live';
        }
      } else if (managedAudio && btn.closest('body.popup-player')) {
        shouldKeepPlaying = true;
        managedAudio.dataset.baseSrc = streamUrl;
        managedAudio.setAttribute('src', buildFreshUrl(streamUrl));
        managedAudio.load();
        managedAudio.play().catch(() => {
          window.open(streamUrl, '_blank', 'noopener');
        });
      } 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(managedAudio);
  setInterval(() => ugfxRefreshIcecast(managedAudio), 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(managedAudio) {
  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;
    });
    if (managedAudio && data.stream_url) {
      managedAudio.dataset.baseSrc = 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) => {
      const directUrl = data.direct_stream_url || data.public_stream_url;
      if (directUrl) btn.setAttribute('data-copy-stream', directUrl);
    });
    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) {}
}
