document.addEventListener('DOMContentLoaded', () => {
  const audio = document.getElementById('myAudio');
  const playPauseBtn = document.getElementById('playPauseBtn');
  const seekSlider = document.getElementById('seekSlider');
  const progressOverlay = document.getElementById('progressOverlay');
  const title = document.getElementById('title');
  const secondTitle = document.getElementById('second-title');

  let isDragging = false;
  let animationFrameId = null;

  // Détection mobile
  const isMobile = /Mobi|Android/i.test(navigator.userAgent);

  // Initialiser le texte du bouton Play/Pause au chargement
  playPauseBtn.textContent = isMobile ? '▶' : 'Lecture';

  // Synchronisation de la barre pendant la lecture
  function updateProgress() {
    if (!isDragging) {
      seekSlider.value = audio.currentTime;
      const percent = (audio.currentTime / audio.duration) * 100;
      progressOverlay.style.width = percent + "%";
    }
    animationFrameId = requestAnimationFrame(updateProgress);
  }

  // Bouton Play/Pause
  playPauseBtn.addEventListener('click', () => {
    if (audio.paused) {
      audio.play();
      playPauseBtn.textContent = isMobile ? '⏸' : 'Pause';
      updateProgress();
    } else {
      audio.pause();
      playPauseBtn.textContent = isMobile ? '▶' : 'Lecture';
      cancelAnimationFrame(animationFrameId);
    }
  });

  // Drag slider
  seekSlider.addEventListener('input', () => {
    isDragging = true;
    const percent = (seekSlider.value / audio.duration) * 100;
    progressOverlay.style.width = percent + "%";
  });

  seekSlider.addEventListener('change', () => {
    audio.currentTime = seekSlider.value;
    isDragging = false;
  });

  // Quand un bouton "Écouter" est cliqué
  document.querySelectorAll('.listen-button').forEach(button => {
    button.addEventListener('click', () => {
      const newSrc = button.dataset.src;
      const mainTitle = button.dataset.title;
      const subTitle = button.dataset.secondTitle;

      audio.pause();
      cancelAnimationFrame(animationFrameId);

      audio.src = newSrc;
      audio.load();

      title.textContent = mainTitle;
      secondTitle.textContent = subTitle;

      audio.addEventListener('loadedmetadata', () => {
        seekSlider.max = audio.duration;
        seekSlider.value = 0;
        progressOverlay.style.width = "0%";
        audio.play();
        playPauseBtn.textContent = isMobile ? '⏸' : 'Pause';
        updateProgress();
      }, { once: true });
    });
  });
});
