const STREAM_URL = 'https://hosting.radiomedia.fr:3765/stream';
const METADATA_URL = 'https://hosting.radiomedia.fr:3765/status-json.xsl';

const stream = document.getElementById('stream');
const playButton = document.getElementById('play');
const stopButton = document.getElementById('stop');
const volume = document.getElementById('volume');
const status = document.getElementById('status');
const nowPlaying = document.getElementById('now-playing');

stream.src = STREAM_URL;

function updateTitle() {
  fetch(METADATA_URL, { cache: 'no-store' })
    .then(response => {
      if (!response.ok) throw new Error('Metadata unavailable');
      return response.json();
    })
    .then(data => {
      const source = data?.icestats?.source;

      if (Array.isArray(source)) {
        nowPlaying.textContent = source[0]?.title || 'Titre indisponible';
      } else {
        nowPlaying.textContent = source?.title || 'Titre indisponible';
      }
    })
    .catch(() => {
      nowPlaying.textContent = 'Titre indisponible';
    });
}

playButton.addEventListener('click', () => {
  status.textContent = 'Connexion au flux…';

  stream.play()
    .then(() => {
      status.textContent = 'En direct';
      updateTitle();
    })
    .catch(() => {
      status.textContent = 'Impossible de lire le flux';
    });
});

stopButton.addEventListener('click', () => {
  stream.pause();
  stream.src = STREAM_URL;
  status.textContent = 'Arrêté';
  nowPlaying.textContent = 'Titre indisponible';
});

volume.addEventListener('input', () => {
  stream.volume = volume.value;
});

setInterval(updateTitle, 15000);

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js');
}